From f27a28682bdb1b4eea0ec9afca2eb2835c735f55 Mon Sep 17 00:00:00 2001 From: Greg Doermann Date: Wed, 20 Aug 2014 11:00:37 -0600 Subject: [PATCH 001/249] Frameworks throws AssertionError saying you cannot set required=True and read_only=True on editable=False model fields. We should not make the field required if editable=False. --- rest_framework/serializers.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index be8ad3f24..27af7ef33 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -831,7 +831,7 @@ class ModelSerializer(Serializer): } if model_field: - kwargs['required'] = not(model_field.null or model_field.blank) + kwargs['required'] = not(model_field.null or model_field.blank) and model_field.editable if model_field.help_text is not None: kwargs['help_text'] = model_field.help_text if model_field.verbose_name is not None: @@ -854,7 +854,7 @@ class ModelSerializer(Serializer): """ kwargs = {} - if model_field.null or model_field.blank: + if model_field.null or model_field.blank and model_field.editable: kwargs['required'] = False if isinstance(model_field, models.AutoField) or not model_field.editable: @@ -1110,7 +1110,7 @@ class HyperlinkedModelSerializer(ModelSerializer): } if model_field: - kwargs['required'] = not(model_field.null or model_field.blank) + kwargs['required'] = not(model_field.null or model_field.blank) and model_field.editable if model_field.help_text is not None: kwargs['help_text'] = model_field.help_text if model_field.verbose_name is not None: From d8eb9e6d45c227582559ec4318b1f92562c718da Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 10:48:16 +0100 Subject: [PATCH 002/249] Docs whitespace fix. --- docs/api-guide/generic-views.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index b1c4e65ad..d30b7f9bf 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -19,8 +19,8 @@ Typically when using the generic views, you'll override the view, and set severa from django.contrib.auth.models import User from myapp.serializers import UserSerializer - from rest_framework import generics - from rest_framework.permissions import IsAdminUser + from rest_framework import generics + from rest_framework.permissions import IsAdminUser class UserList(generics.ListCreateAPIView): queryset = User.objects.all() From f62c874ea9621ae67fb56e7e453dca8fd5039051 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 10:48:40 +0100 Subject: [PATCH 003/249] Remove `filter_backend`. Closes #1775. --- rest_framework/generics.py | 20 +------------------- rest_framework/settings.py | 10 ---------- 2 files changed, 1 insertion(+), 29 deletions(-) diff --git a/rest_framework/generics.py b/rest_framework/generics.py index a6f686571..8bacf470b 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -83,7 +83,6 @@ class GenericAPIView(views.APIView): slug_url_kwarg = 'slug' slug_field = 'slug' allow_empty = True - filter_backend = api_settings.FILTER_BACKEND def get_serializer_context(self): """ @@ -191,24 +190,7 @@ class GenericAPIView(views.APIView): """ Returns the list of filter backends that this view requires. """ - if self.filter_backends is None: - filter_backends = [] - else: - # Note that we are returning a *copy* of the class attribute, - # so that it is safe for the view to mutate it if needed. - filter_backends = list(self.filter_backends) - - if not filter_backends and self.filter_backend: - warnings.warn( - 'The `filter_backend` attribute and `FILTER_BACKEND` setting ' - 'are deprecated in favor of a `filter_backends` ' - 'attribute and `DEFAULT_FILTER_BACKENDS` setting, that take ' - 'a *list* of filter backend classes.', - DeprecationWarning, stacklevel=2 - ) - filter_backends = [self.filter_backend] - - return filter_backends + return list(self.filter_backends) # The following methods provide default implementations # that you may want to override for more complex cases. diff --git a/rest_framework/settings.py b/rest_framework/settings.py index 644751f87..bbe7a56ad 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -111,9 +111,6 @@ DEFAULTS = { ), 'TIME_FORMAT': None, - # Pending deprecation - 'FILTER_BACKEND': None, - } @@ -129,7 +126,6 @@ IMPORT_STRINGS = ( 'DEFAULT_PAGINATION_SERIALIZER_CLASS', 'DEFAULT_FILTER_BACKENDS', 'EXCEPTION_HANDLER', - 'FILTER_BACKEND', 'TEST_REQUEST_RENDERER_CLASSES', 'UNAUTHENTICATED_USER', 'UNAUTHENTICATED_TOKEN', @@ -196,15 +192,9 @@ class APISettings(object): if val and attr in self.import_strings: val = perform_import(val, attr) - self.validate_setting(attr, val) - # Cache the result setattr(self, attr, val) return val - def validate_setting(self, attr, val): - if attr == 'FILTER_BACKEND' and val is not None: - # Make sure we can initialize the class - val() api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS) From 0f8fdf4e72b67ff46474c13c8b532bf319a58099 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 10:57:24 +0100 Subject: [PATCH 004/249] Remove `allow_empty`. Closes #1774. --- docs/api-guide/generic-views.md | 2 -- rest_framework/generics.py | 12 +----------- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index d30b7f9bf..49be0cae8 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -212,8 +212,6 @@ Provides a `.list(request, *args, **kwargs)` method, that implements listing a q If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated. -If the queryset is empty this returns a `200 OK` response, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`. - ## CreateModelMixin Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance. diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 8bacf470b..cb8061b75 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -82,7 +82,6 @@ class GenericAPIView(views.APIView): pk_url_kwarg = 'pk' slug_url_kwarg = 'slug' slug_field = 'slug' - allow_empty = True def get_serializer_context(self): """ @@ -140,16 +139,7 @@ class GenericAPIView(views.APIView): if not page_size: return None - if not self.allow_empty: - warnings.warn( - 'The `allow_empty` parameter is deprecated. ' - 'To use `allow_empty=False` style behavior, You should override ' - '`get_queryset()` and explicitly raise a 404 on empty querysets.', - DeprecationWarning, stacklevel=2 - ) - - paginator = self.paginator_class(queryset, page_size, - allow_empty_first_page=self.allow_empty) + paginator = self.paginator_class(queryset, page_size) page_kwarg = self.kwargs.get(self.page_kwarg) page_query_param = self.request.QUERY_PARAMS.get(self.page_kwarg) page = page_kwarg or page_query_param or 1 From b3bbf416707cf8c71861b0fd6e966a557acef412 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 11:09:35 +0100 Subject: [PATCH 005/249] Remove `allow_empty` --- rest_framework/mixins.py | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index 2cc87eef1..dc4c9f353 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -70,24 +70,9 @@ class ListModelMixin(object): """ List a queryset. """ - empty_error = "Empty list and '%(class_name)s.allow_empty' is False." - def list(self, request, *args, **kwargs): self.object_list = self.filter_queryset(self.get_queryset()) - # Default is to allow empty querysets. This can be altered by setting - # `.allow_empty = False`, to raise 404 errors on empty querysets. - if not self.allow_empty and not self.object_list: - warnings.warn( - 'The `allow_empty` parameter is deprecated. ' - 'To use `allow_empty=False` style behavior, You should override ' - '`get_queryset()` and explicitly raise a 404 on empty querysets.', - DeprecationWarning - ) - class_name = self.__class__.__name__ - error_msg = self.empty_error % {'class_name': class_name} - raise Http404(error_msg) - # Switch between paginated or standard style responses page = self.paginate_queryset(self.object_list) if page is not None: From e5e6329a222def3b0745f90fc55ee36de95ada83 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 11:29:26 +0100 Subject: [PATCH 006/249] Remove `pk_url_field`, `slug_url_field`, `slug_field`. Closes #1773. --- rest_framework/generics.py | 36 ++--------- rest_framework/mixins.py | 36 +++-------- rest_framework/relations.py | 117 ++---------------------------------- 3 files changed, 15 insertions(+), 174 deletions(-) diff --git a/rest_framework/generics.py b/rest_framework/generics.py index cb8061b75..e21dc5c7b 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -76,13 +76,6 @@ class GenericAPIView(views.APIView): model_serializer_class = api_settings.DEFAULT_MODEL_SERIALIZER_CLASS paginator_class = Paginator - ###################################### - # These are pending deprecation... - - pk_url_kwarg = 'pk' - slug_url_kwarg = 'slug' - slug_field = 'slug' - def get_serializer_context(self): """ Extra context provided to the serializer class. @@ -270,7 +263,7 @@ class GenericAPIView(views.APIView): error_format = "'%s' must define 'queryset' or 'model'" raise ImproperlyConfigured(error_format % self.__class__.__name__) - def get_object(self, queryset=None): + def get_object(self): """ Returns the object the view is displaying. @@ -278,36 +271,14 @@ class GenericAPIView(views.APIView): queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ - # Determine the base queryset to use. - if queryset is None: - queryset = self.filter_queryset(self.get_queryset()) - else: - pass # Deprecation warning + queryset = self.filter_queryset(self.get_queryset()) # Perform the lookup filtering. # Note that `pk` and `slug` are deprecated styles of lookup filtering. lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field lookup = self.kwargs.get(lookup_url_kwarg, None) - pk = self.kwargs.get(self.pk_url_kwarg, None) - slug = self.kwargs.get(self.slug_url_kwarg, None) - if lookup is not None: - filter_kwargs = {self.lookup_field: lookup} - elif pk is not None and self.lookup_field == 'pk': - warnings.warn( - 'The `pk_url_kwarg` attribute is deprecated. ' - 'Use the `lookup_field` attribute instead', - DeprecationWarning - ) - filter_kwargs = {'pk': pk} - elif slug is not None and self.lookup_field == 'pk': - warnings.warn( - 'The `slug_url_kwarg` attribute is deprecated. ' - 'Use the `lookup_field` attribute instead', - DeprecationWarning - ) - filter_kwargs = {self.slug_field: slug} - else: + if lookup is None: raise ImproperlyConfigured( 'Expected view %s to be called with a URL keyword argument ' 'named "%s". Fix your URL conf, or set the `.lookup_field` ' @@ -315,6 +286,7 @@ class GenericAPIView(views.APIView): (self.__class__.__name__, self.lookup_field) ) + filter_kwargs = {self.lookup_field: lookup} obj = get_object_or_404(queryset, **filter_kwargs) # May raise a permission denied diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index dc4c9f353..ac59d9795 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -12,10 +12,9 @@ from rest_framework import status from rest_framework.response import Response from rest_framework.request import clone_request from rest_framework.settings import api_settings -import warnings -def _get_validation_exclusions(obj, pk=None, slug_field=None, lookup_field=None): +def _get_validation_exclusions(obj, lookup_field=None): """ Given a model instance, and an optional pk and slug field, return the full list of all other field names on that model. @@ -23,23 +22,13 @@ def _get_validation_exclusions(obj, pk=None, slug_field=None, lookup_field=None) For use when performing full_clean on a model instance, so we only clean the required fields. """ - include = [] - - if pk: - # Deprecated + if lookup_field == 'pk': pk_field = obj._meta.pk while pk_field.rel: pk_field = pk_field.rel.to._meta.pk - include.append(pk_field.name) + lookup_field = pk_field.name - if slug_field: - # Deprecated - include.append(slug_field) - - if lookup_field and lookup_field != 'pk': - include.append(lookup_field) - - return [field.name for field in obj._meta.fields if field.name not in include] + return [field.name for field in obj._meta.fields if field.name != lookup_field] class CreateModelMixin(object): @@ -146,26 +135,15 @@ class UpdateModelMixin(object): """ Set any attributes on the object that are implicit in the request. """ - # pk and/or slug attributes are implicit in the URL. lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field - lookup = self.kwargs.get(lookup_url_kwarg, None) - pk = self.kwargs.get(self.pk_url_kwarg, None) - slug = self.kwargs.get(self.slug_url_kwarg, None) - slug_field = slug and self.slug_field or None + lookup_value = self.kwargs[lookup_url_kwarg] - if lookup: - setattr(obj, self.lookup_field, lookup) - - if pk: - setattr(obj, 'pk', pk) - - if slug: - setattr(obj, slug_field, slug) + setattr(obj, self.lookup_field, lookup_value) # Ensure we clean the attributes so that we don't eg return integer # pk using a string representation, as provided by the url conf kwarg. if hasattr(obj, 'full_clean'): - exclude = _get_validation_exclusions(obj, pk, slug_field, self.lookup_field) + exclude = _get_validation_exclusions(obj, self.lookup_field) obj.full_clean(exclude) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 1acbdce26..56870b408 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -16,7 +16,6 @@ from rest_framework.fields import Field, WritableField, get_component, is_simple from rest_framework.reverse import reverse from rest_framework.compat import urlparse from rest_framework.compat import smart_text -import warnings # Relational fields @@ -320,11 +319,6 @@ class HyperlinkedRelatedField(RelatedField): 'incorrect_type': _('Incorrect type. Expected url string, received %s.'), } - # These are all deprecated - pk_url_kwarg = 'pk' - slug_field = 'slug' - slug_url_kwarg = None # Defaults to same as `slug_field` unless overridden - def __init__(self, *args, **kwargs): try: self.view_name = kwargs.pop('view_name') @@ -334,22 +328,6 @@ class HyperlinkedRelatedField(RelatedField): self.lookup_field = kwargs.pop('lookup_field', self.lookup_field) self.format = kwargs.pop('format', None) - # These are deprecated - if 'pk_url_kwarg' in kwargs: - msg = 'pk_url_kwarg is deprecated. Use lookup_field instead.' - warnings.warn(msg, DeprecationWarning, stacklevel=2) - if 'slug_url_kwarg' in kwargs: - msg = 'slug_url_kwarg is deprecated. Use lookup_field instead.' - warnings.warn(msg, DeprecationWarning, stacklevel=2) - if 'slug_field' in kwargs: - msg = 'slug_field is deprecated. Use lookup_field instead.' - warnings.warn(msg, DeprecationWarning, stacklevel=2) - - self.pk_url_kwarg = kwargs.pop('pk_url_kwarg', self.pk_url_kwarg) - self.slug_field = kwargs.pop('slug_field', self.slug_field) - default_slug_kwarg = self.slug_url_kwarg or self.slug_field - self.slug_url_kwarg = kwargs.pop('slug_url_kwarg', default_slug_kwarg) - super(HyperlinkedRelatedField, self).__init__(*args, **kwargs) def get_url(self, obj, view_name, request, format): @@ -361,39 +339,7 @@ class HyperlinkedRelatedField(RelatedField): """ lookup_field = getattr(obj, self.lookup_field) kwargs = {self.lookup_field: lookup_field} - try: - return reverse(view_name, kwargs=kwargs, request=request, format=format) - except NoReverseMatch: - pass - - if self.pk_url_kwarg != 'pk': - # Only try pk if it has been explicitly set. - # Otherwise, the default `lookup_field = 'pk'` has us covered. - pk = obj.pk - kwargs = {self.pk_url_kwarg: pk} - try: - return reverse(view_name, kwargs=kwargs, request=request, format=format) - except NoReverseMatch: - pass - - slug = getattr(obj, self.slug_field, None) - if slug is not None: - # Only try slug if it corresponds to an attribute on the object. - kwargs = {self.slug_url_kwarg: slug} - try: - ret = reverse(view_name, kwargs=kwargs, request=request, format=format) - if self.slug_field == 'slug' and self.slug_url_kwarg == 'slug': - # If the lookup succeeds using the default slug params, - # then `slug_field` is being used implicitly, and we - # we need to warn about the pending deprecation. - msg = 'Implicit slug field hyperlinked fields are deprecated.' \ - 'You should set `lookup_field=slug` on the HyperlinkedRelatedField.' - warnings.warn(msg, DeprecationWarning, stacklevel=2) - return ret - except NoReverseMatch: - pass - - raise NoReverseMatch() + return reverse(view_name, kwargs=kwargs, request=request, format=format) def get_object(self, queryset, view_name, view_args, view_kwargs): """ @@ -402,19 +348,8 @@ class HyperlinkedRelatedField(RelatedField): Takes the matched URL conf arguments, and the queryset, and should return an object instance, or raise an `ObjectDoesNotExist` exception. """ - lookup = view_kwargs.get(self.lookup_field, None) - pk = view_kwargs.get(self.pk_url_kwarg, None) - slug = view_kwargs.get(self.slug_url_kwarg, None) - - if lookup is not None: - filter_kwargs = {self.lookup_field: lookup} - elif pk is not None: - filter_kwargs = {'pk': pk} - elif slug is not None: - filter_kwargs = {self.slug_field: slug} - else: - raise ObjectDoesNotExist() - + lookup_value = view_kwargs[self.lookup_field] + filter_kwargs = {self.lookup_field: lookup_value} return queryset.get(**filter_kwargs) def to_native(self, obj): @@ -486,11 +421,6 @@ class HyperlinkedIdentityField(Field): lookup_field = 'pk' read_only = True - # These are all deprecated - pk_url_kwarg = 'pk' - slug_field = 'slug' - slug_url_kwarg = None # Defaults to same as `slug_field` unless overridden - def __init__(self, *args, **kwargs): try: self.view_name = kwargs.pop('view_name') @@ -502,22 +432,6 @@ class HyperlinkedIdentityField(Field): lookup_field = kwargs.pop('lookup_field', None) self.lookup_field = lookup_field or self.lookup_field - # These are deprecated - if 'pk_url_kwarg' in kwargs: - msg = 'pk_url_kwarg is deprecated. Use lookup_field instead.' - warnings.warn(msg, DeprecationWarning, stacklevel=2) - if 'slug_url_kwarg' in kwargs: - msg = 'slug_url_kwarg is deprecated. Use lookup_field instead.' - warnings.warn(msg, DeprecationWarning, stacklevel=2) - if 'slug_field' in kwargs: - msg = 'slug_field is deprecated. Use lookup_field instead.' - warnings.warn(msg, DeprecationWarning, stacklevel=2) - - self.slug_field = kwargs.pop('slug_field', self.slug_field) - default_slug_kwarg = self.slug_url_kwarg or self.slug_field - self.pk_url_kwarg = kwargs.pop('pk_url_kwarg', self.pk_url_kwarg) - self.slug_url_kwarg = kwargs.pop('slug_url_kwarg', default_slug_kwarg) - super(HyperlinkedIdentityField, self).__init__(*args, **kwargs) def field_to_native(self, obj, field_name): @@ -569,27 +483,4 @@ class HyperlinkedIdentityField(Field): if lookup_field is None: return None - try: - return reverse(view_name, kwargs=kwargs, request=request, format=format) - except NoReverseMatch: - pass - - if self.pk_url_kwarg != 'pk': - # Only try pk lookup if it has been explicitly set. - # Otherwise, the default `lookup_field = 'pk'` has us covered. - kwargs = {self.pk_url_kwarg: obj.pk} - try: - return reverse(view_name, kwargs=kwargs, request=request, format=format) - except NoReverseMatch: - pass - - slug = getattr(obj, self.slug_field, None) - if slug: - # Only use slug lookup if a slug field exists on the model - kwargs = {self.slug_url_kwarg: slug} - try: - return reverse(view_name, kwargs=kwargs, request=request, format=format) - except NoReverseMatch: - pass - - raise NoReverseMatch() + return reverse(view_name, kwargs=kwargs, request=request, format=format) From b8c8d10a18741b76355ed7035655d0101c1d778a Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 11:38:54 +0100 Subject: [PATCH 007/249] Remove `page_size` argument. `paginate_queryset` no longer takes an optional `page_size` argument. --- rest_framework/generics.py | 22 ++++------------------ 1 file changed, 4 insertions(+), 18 deletions(-) diff --git a/rest_framework/generics.py b/rest_framework/generics.py index e21dc5c7b..09035303f 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -111,26 +111,14 @@ class GenericAPIView(views.APIView): context = self.get_serializer_context() return pagination_serializer_class(instance=page, context=context) - def paginate_queryset(self, queryset, page_size=None): + def paginate_queryset(self, queryset): """ Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. """ - deprecated_style = False - if page_size is not None: - warnings.warn('The `page_size` parameter to `paginate_queryset()` ' - 'is deprecated. ' - 'Note that the return style of this method is also ' - 'changed, and will simply return a page object ' - 'when called without a `page_size` argument.', - DeprecationWarning, stacklevel=2) - deprecated_style = True - else: - # Determine the required page size. - # If pagination is not configured, simply return None. - page_size = self.get_paginate_by() - if not page_size: - return None + page_size = self.get_paginate_by() + if not page_size: + return None paginator = self.paginator_class(queryset, page_size) page_kwarg = self.kwargs.get(self.page_kwarg) @@ -152,8 +140,6 @@ class GenericAPIView(views.APIView): 'message': str(exc) }) - if deprecated_style: - return (paginator, page, page.object_list, page.has_other_pages()) return page def filter_queryset(self, queryset): From b3253b42836acd123224e88c0927f1ee6a031d94 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 12:35:53 +0100 Subject: [PATCH 008/249] Remove `.model` usage in tests. Remove the shortcut `.model` view attribute usage from test cases. --- rest_framework/generics.py | 49 +++++---------------- tests/serializers.py | 7 --- tests/test_filters.py | 65 +++++++++++++++++++--------- tests/test_generics.py | 34 +++++++++++---- tests/test_hyperlinkedserializers.py | 62 ++++++++++++++++++-------- tests/test_nullable_fields.py | 13 +++++- tests/test_pagination.py | 32 ++++++++++---- tests/test_permissions.py | 24 +++++++--- tests/test_response.py | 5 ++- tests/test_validation.py | 4 +- tests/views.py | 8 ---- 11 files changed, 185 insertions(+), 118 deletions(-) delete mode 100644 tests/serializers.py delete mode 100644 tests/views.py diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 09035303f..68222864f 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -51,11 +51,6 @@ class GenericAPIView(views.APIView): queryset = None serializer_class = None - # This shortcut may be used instead of setting either or both - # of the `queryset`/`serializer_class` attributes, although using - # the explicit style is generally preferred. - model = None - # If you want to use object lookups other than pk, set this attribute. # For more complex lookup requirements override `get_object()`. lookup_field = 'pk' @@ -71,9 +66,8 @@ class GenericAPIView(views.APIView): # The filter backend classes to use for queryset filtering filter_backends = api_settings.DEFAULT_FILTER_BACKENDS - # The following attributes may be subject to change, + # The following attribute may be subject to change, # and should be considered private API. - model_serializer_class = api_settings.DEFAULT_MODEL_SERIALIZER_CLASS paginator_class = Paginator def get_serializer_context(self): @@ -199,26 +193,13 @@ class GenericAPIView(views.APIView): (Eg. admins get full serialization, others get basic serialization) """ - serializer_class = self.serializer_class - if serializer_class is not None: - return serializer_class - - warnings.warn( - 'The `.model` attribute on view classes is now deprecated in favor ' - 'of the more explicit `serializer_class` and `queryset` attributes.', - DeprecationWarning, stacklevel=2 + assert self.serializer_class is not None, ( + "'%s' should either include a `serializer_class` attribute, " + "or override the `get_serializer_class()` method." + % self.__class__.__name__ ) - assert self.model is not None, \ - "'%s' should either include a 'serializer_class' attribute, " \ - "or use the 'model' attribute as a shortcut for " \ - "automatically generating a serializer class." \ - % self.__class__.__name__ - - class DefaultSerializer(self.model_serializer_class): - class Meta: - model = self.model - return DefaultSerializer + return self.serializer_class def get_queryset(self): """ @@ -235,19 +216,13 @@ class GenericAPIView(views.APIView): (Eg. return a list of items that is specific to the user) """ - if self.queryset is not None: - return self.queryset._clone() + assert self.queryset is not None, ( + "'%s' should either include a `queryset` attribute, " + "or override the `get_queryset()` method." + % self.__class__.__name__ + ) - if self.model is not None: - warnings.warn( - 'The `.model` attribute on view classes is now deprecated in favor ' - 'of the more explicit `serializer_class` and `queryset` attributes.', - DeprecationWarning, stacklevel=2 - ) - return self.model._default_manager.all() - - error_format = "'%s' must define 'queryset' or 'model'" - raise ImproperlyConfigured(error_format % self.__class__.__name__) + return self.queryset._clone() def get_object(self): """ diff --git a/tests/serializers.py b/tests/serializers.py deleted file mode 100644 index be7b37722..000000000 --- a/tests/serializers.py +++ /dev/null @@ -1,7 +0,0 @@ -from rest_framework import serializers -from tests.models import NullableForeignKeySource - - -class NullableFKSourceSerializer(serializers.ModelSerializer): - class Meta: - model = NullableForeignKeySource diff --git a/tests/test_filters.py b/tests/test_filters.py index 47bffd436..6f24b1abb 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -16,9 +16,14 @@ factory = APIRequestFactory() if django_filters: + class FilterableItemSerializer(serializers.ModelSerializer): + class Meta: + model = FilterableItem + # Basic filter on a list view. class FilterFieldsRootView(generics.ListCreateAPIView): - model = FilterableItem + queryset = FilterableItem.objects.all() + serializer_class = FilterableItemSerializer filter_fields = ['decimal', 'date'] filter_backends = (filters.DjangoFilterBackend,) @@ -33,7 +38,8 @@ if django_filters: fields = ['text', 'decimal', 'date'] class FilterClassRootView(generics.ListCreateAPIView): - model = FilterableItem + queryset = FilterableItem.objects.all() + serializer_class = FilterableItemSerializer filter_class = SeveralFieldsFilter filter_backends = (filters.DjangoFilterBackend,) @@ -46,12 +52,14 @@ if django_filters: fields = ['text'] class IncorrectlyConfiguredRootView(generics.ListCreateAPIView): - model = FilterableItem + queryset = FilterableItem.objects.all() + serializer_class = FilterableItemSerializer filter_class = MisconfiguredFilter filter_backends = (filters.DjangoFilterBackend,) class FilterClassDetailView(generics.RetrieveAPIView): - model = FilterableItem + queryset = FilterableItem.objects.all() + serializer_class = FilterableItemSerializer filter_class = SeveralFieldsFilter filter_backends = (filters.DjangoFilterBackend,) @@ -63,15 +71,12 @@ if django_filters: model = BaseFilterableItem class BaseFilterableItemFilterRootView(generics.ListCreateAPIView): - model = FilterableItem + queryset = FilterableItem.objects.all() + serializer_class = FilterableItemSerializer filter_class = BaseFilterableItemFilter filter_backends = (filters.DjangoFilterBackend,) # Regression test for #814 - class FilterableItemSerializer(serializers.ModelSerializer): - class Meta: - model = FilterableItem - class FilterFieldsQuerysetView(generics.ListCreateAPIView): queryset = FilterableItem.objects.all() serializer_class = FilterableItemSerializer @@ -323,6 +328,11 @@ class SearchFilterModel(models.Model): text = models.CharField(max_length=100) +class SearchFilterSerializer(serializers.ModelSerializer): + class Meta: + model = SearchFilterModel + + class SearchFilterTests(TestCase): def setUp(self): # Sequence of title/text is: @@ -342,7 +352,8 @@ class SearchFilterTests(TestCase): def test_search(self): class SearchListView(generics.ListAPIView): - model = SearchFilterModel + queryset = SearchFilterModel.objects.all() + serializer_class = SearchFilterSerializer filter_backends = (filters.SearchFilter,) search_fields = ('title', 'text') @@ -359,7 +370,8 @@ class SearchFilterTests(TestCase): def test_exact_search(self): class SearchListView(generics.ListAPIView): - model = SearchFilterModel + queryset = SearchFilterModel.objects.all() + serializer_class = SearchFilterSerializer filter_backends = (filters.SearchFilter,) search_fields = ('=title', 'text') @@ -375,7 +387,8 @@ class SearchFilterTests(TestCase): def test_startswith_search(self): class SearchListView(generics.ListAPIView): - model = SearchFilterModel + queryset = SearchFilterModel.objects.all() + serializer_class = SearchFilterSerializer filter_backends = (filters.SearchFilter,) search_fields = ('title', '^text') @@ -392,7 +405,8 @@ class SearchFilterTests(TestCase): def test_search_with_nonstandard_search_param(self): with temporary_setting('SEARCH_PARAM', 'query', module=filters): class SearchListView(generics.ListAPIView): - model = SearchFilterModel + queryset = SearchFilterModel.objects.all() + serializer_class = SearchFilterSerializer filter_backends = (filters.SearchFilter,) search_fields = ('title', 'text') @@ -418,6 +432,11 @@ class OrderingFilterRelatedModel(models.Model): related_name="relateds") +class OrderingFilterSerializer(serializers.ModelSerializer): + class Meta: + model = OrdringFilterModel + + class OrderingFilterTests(TestCase): def setUp(self): # Sequence of title/text is: @@ -440,7 +459,8 @@ class OrderingFilterTests(TestCase): def test_ordering(self): class OrderingListView(generics.ListAPIView): - model = OrdringFilterModel + queryset = OrdringFilterModel.objects.all() + serializer_class = OrderingFilterSerializer filter_backends = (filters.OrderingFilter,) ordering = ('title',) ordering_fields = ('text',) @@ -459,7 +479,8 @@ class OrderingFilterTests(TestCase): def test_reverse_ordering(self): class OrderingListView(generics.ListAPIView): - model = OrdringFilterModel + queryset = OrdringFilterModel.objects.all() + serializer_class = OrderingFilterSerializer filter_backends = (filters.OrderingFilter,) ordering = ('title',) ordering_fields = ('text',) @@ -478,7 +499,8 @@ class OrderingFilterTests(TestCase): def test_incorrectfield_ordering(self): class OrderingListView(generics.ListAPIView): - model = OrdringFilterModel + queryset = OrdringFilterModel.objects.all() + serializer_class = OrderingFilterSerializer filter_backends = (filters.OrderingFilter,) ordering = ('title',) ordering_fields = ('text',) @@ -497,7 +519,8 @@ class OrderingFilterTests(TestCase): def test_default_ordering(self): class OrderingListView(generics.ListAPIView): - model = OrdringFilterModel + queryset = OrdringFilterModel.objects.all() + serializer_class = OrderingFilterSerializer filter_backends = (filters.OrderingFilter,) ordering = ('title',) oredering_fields = ('text',) @@ -516,7 +539,8 @@ class OrderingFilterTests(TestCase): def test_default_ordering_using_string(self): class OrderingListView(generics.ListAPIView): - model = OrdringFilterModel + queryset = OrdringFilterModel.objects.all() + serializer_class = OrderingFilterSerializer filter_backends = (filters.OrderingFilter,) ordering = 'title' ordering_fields = ('text',) @@ -545,7 +569,7 @@ class OrderingFilterTests(TestCase): new_related.save() class OrderingListView(generics.ListAPIView): - model = OrdringFilterModel + serializer_class = OrderingFilterSerializer filter_backends = (filters.OrderingFilter,) ordering = 'title' ordering_fields = '__all__' @@ -567,7 +591,8 @@ class OrderingFilterTests(TestCase): def test_ordering_with_nonstandard_ordering_param(self): with temporary_setting('ORDERING_PARAM', 'order', filters): class OrderingListView(generics.ListAPIView): - model = OrdringFilterModel + queryset = OrdringFilterModel.objects.all() + serializer_class = OrderingFilterSerializer filter_backends = (filters.OrderingFilter,) ordering = ('title',) ordering_fields = ('text',) diff --git a/tests/test_generics.py b/tests/test_generics.py index e9f5bebdd..f50d53e99 100644 --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -11,18 +11,30 @@ from tests.models import ForeignKeySource, ForeignKeyTarget factory = APIRequestFactory() +class BasicSerializer(serializers.ModelSerializer): + class Meta: + model = BasicModel + + +class ForeignKeySerializer(serializers.ModelSerializer): + class Meta: + model = ForeignKeySource + + class RootView(generics.ListCreateAPIView): """ Example description for OPTIONS. """ - model = BasicModel + queryset = BasicModel.objects.all() + serializer_class = BasicSerializer class InstanceView(generics.RetrieveUpdateDestroyAPIView): """ Example description for OPTIONS. """ - model = BasicModel + queryset = BasicModel.objects.all() + serializer_class = BasicSerializer def get_queryset(self): queryset = super(InstanceView, self).get_queryset() @@ -33,7 +45,8 @@ class FKInstanceView(generics.RetrieveUpdateDestroyAPIView): """ FK: example description for OPTIONS. """ - model = ForeignKeySource + queryset = ForeignKeySource.objects.all() + serializer_class = ForeignKeySerializer class SlugSerializer(serializers.ModelSerializer): @@ -48,7 +61,7 @@ class SlugBasedInstanceView(InstanceView): """ A model with a slug-field. """ - model = SlugBasedModel + queryset = SlugBasedModel.objects.all() serializer_class = SlugSerializer lookup_field = 'slug' @@ -503,7 +516,7 @@ class TestOverriddenGetObject(TestCase): """ Example detail view for override of get_object(). """ - model = BasicModel + serializer_class = BasicSerializer def get_object(self): pk = int(self.kwargs['pk']) @@ -573,7 +586,7 @@ class ClassASerializer(serializers.ModelSerializer): class ExampleView(generics.ListCreateAPIView): serializer_class = ClassASerializer - model = ClassA + queryset = ClassA.objects.all() class TestM2MBrowseableAPI(TestCase): @@ -603,7 +616,7 @@ class TwoFieldModel(models.Model): class DynamicSerializerView(generics.ListCreateAPIView): - model = TwoFieldModel + queryset = TwoFieldModel.objects.all() renderer_classes = (renderers.BrowsableAPIRenderer, renderers.JSONRenderer) def get_serializer_class(self): @@ -612,8 +625,11 @@ class DynamicSerializerView(generics.ListCreateAPIView): class Meta: model = TwoFieldModel fields = ('field_b',) - return DynamicSerializer - return super(DynamicSerializerView, self).get_serializer_class() + else: + class DynamicSerializer(serializers.ModelSerializer): + class Meta: + model = TwoFieldModel + return DynamicSerializer class TestFilterBackendAppliedToViews(TestCase): diff --git a/tests/test_hyperlinkedserializers.py b/tests/test_hyperlinkedserializers.py index d45485391..0e8c1ed46 100644 --- a/tests/test_hyperlinkedserializers.py +++ b/tests/test_hyperlinkedserializers.py @@ -39,59 +39,85 @@ class AlbumSerializer(serializers.ModelSerializer): fields = ('title', 'url') +class BasicSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = BasicModel + + +class AnchorSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = Anchor + + +class ManyToManySerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = ManyToManyModel + + +class BlogPostSerializer(serializers.ModelSerializer): + class Meta: + model = BlogPost + + +class OptionalRelationSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = OptionalRelationModel + + class BasicList(generics.ListCreateAPIView): - model = BasicModel - model_serializer_class = serializers.HyperlinkedModelSerializer + queryset = BasicModel.objects.all() + serializer_class = BasicSerializer class BasicDetail(generics.RetrieveUpdateDestroyAPIView): - model = BasicModel - model_serializer_class = serializers.HyperlinkedModelSerializer + queryset = BasicModel.objects.all() + serializer_class = BasicSerializer class AnchorDetail(generics.RetrieveAPIView): - model = Anchor - model_serializer_class = serializers.HyperlinkedModelSerializer + queryset = Anchor.objects.all() + serializer_class = AnchorSerializer class ManyToManyList(generics.ListAPIView): - model = ManyToManyModel - model_serializer_class = serializers.HyperlinkedModelSerializer + queryset = ManyToManyModel.objects.all() + serializer_class = ManyToManySerializer class ManyToManyDetail(generics.RetrieveAPIView): - model = ManyToManyModel - model_serializer_class = serializers.HyperlinkedModelSerializer + queryset = ManyToManyModel.objects.all() + serializer_class = ManyToManySerializer class BlogPostCommentListCreate(generics.ListCreateAPIView): - model = BlogPostComment + queryset = BlogPostComment.objects.all() serializer_class = BlogPostCommentSerializer class BlogPostCommentDetail(generics.RetrieveAPIView): - model = BlogPostComment + queryset = BlogPostComment.objects.all() serializer_class = BlogPostCommentSerializer class BlogPostDetail(generics.RetrieveAPIView): - model = BlogPost + queryset = BlogPost.objects.all() + serializer_class = BlogPostSerializer class PhotoListCreate(generics.ListCreateAPIView): - model = Photo - model_serializer_class = PhotoSerializer + queryset = Photo.objects.all() + serializer_class = PhotoSerializer class AlbumDetail(generics.RetrieveAPIView): - model = Album + queryset = Album.objects.all() serializer_class = AlbumSerializer lookup_field = 'title' class OptionalRelationDetail(generics.RetrieveUpdateDestroyAPIView): - model = OptionalRelationModel - model_serializer_class = serializers.HyperlinkedModelSerializer + queryset = OptionalRelationModel.objects.all() + serializer_class = OptionalRelationSerializer urlpatterns = patterns( diff --git a/tests/test_nullable_fields.py b/tests/test_nullable_fields.py index 0c133fc2c..8d0c84bb0 100644 --- a/tests/test_nullable_fields.py +++ b/tests/test_nullable_fields.py @@ -1,10 +1,19 @@ from django.core.urlresolvers import reverse from django.conf.urls import patterns, url +from rest_framework import serializers, generics from rest_framework.test import APITestCase from tests.models import NullableForeignKeySource -from tests.serializers import NullableFKSourceSerializer -from tests.views import NullableFKSourceDetail + + +class NullableFKSourceSerializer(serializers.ModelSerializer): + class Meta: + model = NullableForeignKeySource + + +class NullableFKSourceDetail(generics.RetrieveUpdateDestroyAPIView): + queryset = NullableForeignKeySource.objects.all() + serializer_class = NullableFKSourceSerializer urlpatterns = patterns( diff --git a/tests/test_pagination.py b/tests/test_pagination.py index 80c33e2eb..8f9e0005e 100644 --- a/tests/test_pagination.py +++ b/tests/test_pagination.py @@ -4,7 +4,7 @@ from decimal import Decimal from django.core.paginator import Paginator from django.test import TestCase from django.utils import unittest -from rest_framework import generics, status, pagination, filters, serializers +from rest_framework import generics, serializers, status, pagination, filters from rest_framework.compat import django_filters from rest_framework.test import APIRequestFactory from .models import BasicModel, FilterableItem @@ -22,11 +22,22 @@ def split_arguments_from_url(url): return path, args +class BasicSerializer(serializers.ModelSerializer): + class Meta: + model = BasicModel + + +class FilterableItemSerializer(serializers.ModelSerializer): + class Meta: + model = FilterableItem + + class RootView(generics.ListCreateAPIView): """ Example description for OPTIONS. """ - model = BasicModel + queryset = BasicModel.objects.all() + serializer_class = BasicSerializer paginate_by = 10 @@ -34,14 +45,16 @@ class DefaultPageSizeKwargView(generics.ListAPIView): """ View for testing default paginate_by_param usage """ - model = BasicModel + queryset = BasicModel.objects.all() + serializer_class = BasicSerializer class PaginateByParamView(generics.ListAPIView): """ View for testing custom paginate_by_param usage """ - model = BasicModel + queryset = BasicModel.objects.all() + serializer_class = BasicSerializer paginate_by_param = 'page_size' @@ -49,7 +62,8 @@ class MaxPaginateByView(generics.ListAPIView): """ View for testing custom max_paginate_by usage """ - model = BasicModel + queryset = BasicModel.objects.all() + serializer_class = BasicSerializer paginate_by = 3 max_paginate_by = 5 paginate_by_param = 'page_size' @@ -140,7 +154,8 @@ class IntegrationTestPaginationAndFiltering(TestCase): fields = ['text', 'decimal', 'date'] class FilterFieldsRootView(generics.ListCreateAPIView): - model = FilterableItem + queryset = FilterableItem.objects.all() + serializer_class = FilterableItemSerializer paginate_by = 10 filter_class = DecimalFilter filter_backends = (filters.DjangoFilterBackend,) @@ -188,7 +203,8 @@ class IntegrationTestPaginationAndFiltering(TestCase): return queryset.filter(decimal__lt=Decimal(request.GET['decimal'])) class BasicFilterFieldsRootView(generics.ListCreateAPIView): - model = FilterableItem + queryset = FilterableItem.objects.all() + serializer_class = FilterableItemSerializer paginate_by = 10 filter_backends = (DecimalFilterBackend,) @@ -387,7 +403,7 @@ class TestContextPassedToCustomField(TestCase): def test_with_pagination(self): class ListView(generics.ListCreateAPIView): - model = BasicModel + queryset = BasicModel.objects.all() serializer_class = BasicModelSerializer paginate_by = 1 diff --git a/tests/test_permissions.py b/tests/test_permissions.py index 93f8020f3..b90ba4f19 100644 --- a/tests/test_permissions.py +++ b/tests/test_permissions.py @@ -3,7 +3,7 @@ from django.contrib.auth.models import User, Permission, Group from django.db import models from django.test import TestCase from django.utils import unittest -from rest_framework import generics, status, permissions, authentication, HTTP_HEADER_ENCODING +from rest_framework import generics, serializers, status, permissions, authentication, HTTP_HEADER_ENCODING from rest_framework.compat import guardian, get_model_name from rest_framework.filters import DjangoObjectPermissionsFilter from rest_framework.test import APIRequestFactory @@ -13,14 +13,21 @@ import base64 factory = APIRequestFactory() +class BasicSerializer(serializers.ModelSerializer): + class Meta: + model = BasicModel + + class RootView(generics.ListCreateAPIView): - model = BasicModel + queryset = BasicModel.objects.all() + serializer_class = BasicSerializer authentication_classes = [authentication.BasicAuthentication] permission_classes = [permissions.DjangoModelPermissions] class InstanceView(generics.RetrieveUpdateDestroyAPIView): - model = BasicModel + queryset = BasicModel.objects.all() + serializer_class = BasicSerializer authentication_classes = [authentication.BasicAuthentication] permission_classes = [permissions.DjangoModelPermissions] @@ -167,6 +174,11 @@ class BasicPermModel(models.Model): ) +class BasicPermSerializer(serializers.ModelSerializer): + class Meta: + model = BasicPermModel + + # Custom object-level permission, that includes 'view' permissions class ViewObjectPermissions(permissions.DjangoObjectPermissions): perms_map = { @@ -181,7 +193,8 @@ class ViewObjectPermissions(permissions.DjangoObjectPermissions): class ObjectPermissionInstanceView(generics.RetrieveUpdateDestroyAPIView): - model = BasicPermModel + queryset = BasicPermModel.objects.all() + serializer_class = BasicPermSerializer authentication_classes = [authentication.BasicAuthentication] permission_classes = [ViewObjectPermissions] @@ -189,7 +202,8 @@ object_permissions_view = ObjectPermissionInstanceView.as_view() class ObjectPermissionListView(generics.ListAPIView): - model = BasicPermModel + queryset = BasicPermModel.objects.all() + serializer_class = BasicPermSerializer authentication_classes = [authentication.BasicAuthentication] permission_classes = [ViewObjectPermissions] diff --git a/tests/test_response.py b/tests/test_response.py index 2eff83d3d..004c565c9 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -86,14 +86,15 @@ class HTMLView1(APIView): class HTMLNewModelViewSet(viewsets.ModelViewSet): - model = BasicModel + serializer_class = BasicModelSerializer + queryset = BasicModel.objects.all() class HTMLNewModelView(generics.ListCreateAPIView): renderer_classes = (BrowsableAPIRenderer,) permission_classes = [] serializer_class = BasicModelSerializer - model = BasicModel + queryset = BasicModel.objects.all() new_model_viewset_router = routers.DefaultRouter() diff --git a/tests/test_validation.py b/tests/test_validation.py index e13e4078c..f62d9068b 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -22,7 +22,7 @@ class ValidationModelSerializer(serializers.ModelSerializer): class UpdateValidationModel(generics.RetrieveUpdateDestroyAPIView): - model = ValidationModel + queryset = ValidationModel.objects.all() serializer_class = ValidationModelSerializer @@ -117,7 +117,7 @@ class ValidationMaxValueValidatorModelSerializer(serializers.ModelSerializer): class UpdateMaxValueValidationModel(generics.RetrieveUpdateDestroyAPIView): - model = ValidationMaxValueValidatorModel + queryset = ValidationMaxValueValidatorModel.objects.all() serializer_class = ValidationMaxValueValidatorModelSerializer diff --git a/tests/views.py b/tests/views.py deleted file mode 100644 index 55935e924..000000000 --- a/tests/views.py +++ /dev/null @@ -1,8 +0,0 @@ -from rest_framework import generics -from .models import NullableForeignKeySource -from .serializers import NullableFKSourceSerializer - - -class NullableFKSourceDetail(generics.RetrieveUpdateDestroyAPIView): - model = NullableForeignKeySource - model_serializer_class = NullableFKSourceSerializer From 72c0811576feb89decf6fc6dc4ee5e25eca0aece Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 12:48:04 +0100 Subject: [PATCH 009/249] Minor tidy up. --- rest_framework/generics.py | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 68222864f..d0adeaec0 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -3,7 +3,7 @@ Generic views that provide commonly needed behaviour. """ from __future__ import unicode_literals -from django.core.exceptions import ImproperlyConfigured, PermissionDenied +from django.core.exceptions import PermissionDenied from django.core.paginator import Paginator, InvalidPage from django.http import Http404 from django.shortcuts import get_object_or_404 as _get_object_or_404 @@ -235,19 +235,16 @@ class GenericAPIView(views.APIView): queryset = self.filter_queryset(self.get_queryset()) # Perform the lookup filtering. - # Note that `pk` and `slug` are deprecated styles of lookup filtering. lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field - lookup = self.kwargs.get(lookup_url_kwarg, None) - if lookup is None: - raise ImproperlyConfigured( - 'Expected view %s to be called with a URL keyword argument ' - 'named "%s". Fix your URL conf, or set the `.lookup_field` ' - 'attribute on the view correctly.' % - (self.__class__.__name__, self.lookup_field) - ) + assert lookup_url_kwarg in self.kwargs, ( + 'Expected view %s to be called with a URL keyword argument ' + 'named "%s". Fix your URL conf, or set the `.lookup_field` ' + 'attribute on the view correctly.' % + (self.__class__.__name__, lookup_url_kwarg) + ) - filter_kwargs = {self.lookup_field: lookup} + filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]} obj = get_object_or_404(queryset, **filter_kwargs) # May raise a permission denied From ce7b2cded94abc12ae1be076642de96684d0927b Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 12:48:49 +0100 Subject: [PATCH 010/249] Remove deprecated generic views. `MultipleObjectAPIView` and `SingleObjectAPIView` are no longer required. --- rest_framework/generics.py | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/rest_framework/generics.py b/rest_framework/generics.py index d0adeaec0..e6cbfca90 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -442,25 +442,3 @@ class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin, def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) - - -# Deprecated classes - -class MultipleObjectAPIView(GenericAPIView): - def __init__(self, *args, **kwargs): - warnings.warn( - 'Subclassing `MultipleObjectAPIView` is deprecated. ' - 'You should simply subclass `GenericAPIView` instead.', - DeprecationWarning, stacklevel=2 - ) - super(MultipleObjectAPIView, self).__init__(*args, **kwargs) - - -class SingleObjectAPIView(GenericAPIView): - def __init__(self, *args, **kwargs): - warnings.warn( - 'Subclassing `SingleObjectAPIView` is deprecated. ' - 'You should simply subclass `GenericAPIView` instead.', - DeprecationWarning, stacklevel=2 - ) - super(SingleObjectAPIView, self).__init__(*args, **kwargs) From f87d32558eb3b36f14a798ec48e4943d25380b92 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 12:53:45 +0100 Subject: [PATCH 011/249] Remove `.link()` and `.action()` decorators. --- rest_framework/decorators.py | 34 ---------------------------------- 1 file changed, 34 deletions(-) diff --git a/rest_framework/decorators.py b/rest_framework/decorators.py index 449ba0a29..cc5d92c2e 100644 --- a/rest_framework/decorators.py +++ b/rest_framework/decorators.py @@ -130,37 +130,3 @@ def list_route(methods=['get'], **kwargs): func.kwargs = kwargs return func return decorator - - -# These are now pending deprecation, in favor of `detail_route` and `list_route`. - -def link(**kwargs): - """ - Used to mark a method on a ViewSet that should be routed for detail GET requests. - """ - msg = 'link is pending deprecation. Use detail_route instead.' - warnings.warn(msg, PendingDeprecationWarning, stacklevel=2) - - def decorator(func): - func.bind_to_methods = ['get'] - func.detail = True - func.kwargs = kwargs - return func - - return decorator - - -def action(methods=['post'], **kwargs): - """ - Used to mark a method on a ViewSet that should be routed for detail POST requests. - """ - msg = 'action is pending deprecation. Use detail_route instead.' - warnings.warn(msg, PendingDeprecationWarning, stacklevel=2) - - def decorator(func): - func.bind_to_methods = methods - func.detail = True - func.kwargs = kwargs - return func - - return decorator From b552b62540e5144272c9c13c28f120ffe5fcbe45 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 12:54:03 +0100 Subject: [PATCH 012/249] `get_paginate_by` no longer takes optional `.queryset` --- rest_framework/generics.py | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/rest_framework/generics.py b/rest_framework/generics.py index e6cbfca90..40c498440 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -158,7 +158,7 @@ class GenericAPIView(views.APIView): # The following methods provide default implementations # that you may want to override for more complex cases. - def get_paginate_by(self, queryset=None): + def get_paginate_by(self): """ Return the size of pages to use with pagination. @@ -167,11 +167,6 @@ class GenericAPIView(views.APIView): Otherwise defaults to using `self.paginate_by`. """ - if queryset is not None: - warnings.warn('The `queryset` parameter to `get_paginate_by()` ' - 'is deprecated.', - DeprecationWarning, stacklevel=2) - if self.paginate_by_param: try: return strict_positive_int( From 371d30aa8737c4b3aaf28ee10cc2b77a9c4d1fd9 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 12:54:52 +0100 Subject: [PATCH 013/249] Remove unused imports. --- rest_framework/decorators.py | 1 - rest_framework/generics.py | 1 - 2 files changed, 2 deletions(-) diff --git a/rest_framework/decorators.py b/rest_framework/decorators.py index cc5d92c2e..d28d6e22a 100644 --- a/rest_framework/decorators.py +++ b/rest_framework/decorators.py @@ -10,7 +10,6 @@ from __future__ import unicode_literals from django.utils import six from rest_framework.views import APIView import types -import warnings def api_view(http_method_names): diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 40c498440..b3bd6ce92 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -11,7 +11,6 @@ from django.utils.translation import ugettext as _ from rest_framework import views, mixins, exceptions from rest_framework.request import clone_request from rest_framework.settings import api_settings -import warnings def strict_positive_int(integer_string, cutoff=None): From 4ac4676a40b121d27cfd1173ff548d96b8d3de2f Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 29 Aug 2014 16:46:26 +0100 Subject: [PATCH 014/249] First pass --- rest_framework/fields.py | 1226 ++++++------------------------ rest_framework/generics.py | 10 +- rest_framework/mixins.py | 24 +- rest_framework/pagination.py | 22 +- rest_framework/relations.py | 486 ------------ rest_framework/renderers.py | 10 +- rest_framework/serializers.py | 1200 +++++++++-------------------- rest_framework/utils/encoders.py | 18 +- rest_framework/utils/html.py | 86 +++ 9 files changed, 714 insertions(+), 2368 deletions(-) create mode 100644 rest_framework/utils/html.py diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 9d707c9b5..a83bf94c4 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1,1038 +1,308 @@ -""" -Serializer fields perform validation on incoming data. - -They are very similar to Django's form fields. -""" -from __future__ import unicode_literals - -import copy -import datetime -import inspect -import re -import warnings -from decimal import Decimal, DecimalException -from django import forms -from django.core import validators -from django.core.exceptions import ValidationError -from django.conf import settings -from django.db.models.fields import BLANK_CHOICE_DASH -from django.http import QueryDict -from django.forms import widgets -from django.utils import six, timezone -from django.utils.encoding import is_protected_type -from django.utils.translation import ugettext_lazy as _ -from django.utils.datastructures import SortedDict -from django.utils.dateparse import parse_date, parse_datetime, parse_time -from rest_framework import ISO_8601 -from rest_framework.compat import ( - BytesIO, smart_text, - force_text, is_non_str_iterable -) -from rest_framework.settings import api_settings +from rest_framework.utils import html -def is_simple_callable(obj): +class empty: """ - True if the object is a callable that takes no arguments. + This class is used to represent no data being provided for a given input + or output value. + + It is required because `None` may be a valid input or output value. """ - function = inspect.isfunction(obj) - method = inspect.ismethod(obj) - - if not (function or method): - return False - - args, _, _, defaults = inspect.getargspec(obj) - len_args = len(args) if function else len(args) - 1 - len_defaults = len(defaults) if defaults else 0 - return len_args <= len_defaults + pass -def get_component(obj, attr_name): +def get_attribute(instance, attrs): """ - Given an object, and an attribute name, - return that attribute on the object. + Similar to Python's built in `getattr(instance, attr)`, + but takes a list of nested attributes, instead of a single attribute. """ - if isinstance(obj, dict): - val = obj.get(attr_name) - else: - val = getattr(obj, attr_name) - - if is_simple_callable(val): - return val() - return val + for attr in attrs: + instance = getattr(instance, attr) + return instance -def readable_datetime_formats(formats): - format = ', '.join(formats).replace( - ISO_8601, - 'YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]' - ) - return humanize_strptime(format) - - -def readable_date_formats(formats): - format = ', '.join(formats).replace(ISO_8601, 'YYYY[-MM[-DD]]') - return humanize_strptime(format) - - -def readable_time_formats(formats): - format = ', '.join(formats).replace(ISO_8601, 'hh:mm[:ss[.uuuuuu]]') - return humanize_strptime(format) - - -def humanize_strptime(format_string): - # Note that we're missing some of the locale specific mappings that - # don't really make sense. - mapping = { - "%Y": "YYYY", - "%y": "YY", - "%m": "MM", - "%b": "[Jan-Dec]", - "%B": "[January-December]", - "%d": "DD", - "%H": "hh", - "%I": "hh", # Requires '%p' to differentiate from '%H'. - "%M": "mm", - "%S": "ss", - "%f": "uuuuuu", - "%a": "[Mon-Sun]", - "%A": "[Monday-Sunday]", - "%p": "[AM|PM]", - "%z": "[+HHMM|-HHMM]" - } - for key, val in mapping.items(): - format_string = format_string.replace(key, val) - return format_string - - -def strip_multiple_choice_msg(help_text): +def set_value(dictionary, keys, value): """ - Remove the 'Hold down "control" ...' message that is Django enforces in - select multiple fields on ModelForms. (Required for 1.5 and earlier) + Similar to Python's built in `dictionary[key] = value`, + but takes a list of nested keys instead of a single key. - See https://code.djangoproject.com/ticket/9321 + set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2} + set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2} + set_value({'a': 1}, ['x', 'y'], 2) -> {'a': 1, 'x': {'y': 2}} """ - multiple_choice_msg = _(' Hold down "Control", or "Command" on a Mac, to select more than one.') - multiple_choice_msg = force_text(multiple_choice_msg) + if not keys: + dictionary.update(value) + return - return help_text.replace(multiple_choice_msg, '') + for key in keys[:-1]: + if key not in dictionary: + dictionary[key] = {} + dictionary = dictionary[key] + + dictionary[keys[-1]] = value + + +class ValidationError(Exception): + pass + + +class SkipField(Exception): + pass class Field(object): - read_only = True - creation_counter = 0 - empty = '' - type_name = None - partial = False - use_files = False - form_field_class = forms.CharField - type_label = 'field' - widget = None + _creation_counter = 0 - def __init__(self, source=None, label=None, help_text=None): - self.parent = None - - self.creation_counter = Field.creation_counter - Field.creation_counter += 1 - - self.source = source - - if label is not None: - self.label = smart_text(label) - else: - self.label = None - - if help_text is not None: - self.help_text = strip_multiple_choice_msg(smart_text(help_text)) - else: - self.help_text = None - - self._errors = [] - self._value = None - self._name = None - - @property - def errors(self): - return self._errors - - def widget_html(self): - if not self.widget: - return '' - - attrs = {} - if 'id' not in self.widget.attrs: - attrs['id'] = self._name - - return self.widget.render(self._name, self._value, attrs=attrs) - - def label_tag(self): - return '' % (self._name, self.label) - - def initialize(self, parent, field_name): - """ - Called to set up a field prior to field_to_native or field_from_native. - - parent - The parent serializer. - field_name - The name of the field being initialized. - """ - self.parent = parent - self.root = parent.root or parent - self.context = self.root.context - self.partial = self.root.partial - if self.partial: - self.required = False - - def field_from_native(self, data, files, field_name, into): - """ - Given a dictionary and a field name, updates the dictionary `into`, - with the field and it's deserialized value. - """ - return - - def field_to_native(self, obj, field_name): - """ - Given an object and a field name, returns the value that should be - serialized for that field. - """ - if obj is None: - return self.empty - - if self.source == '*': - return self.to_native(obj) - - source = self.source or field_name - value = obj - - for component in source.split('.'): - value = get_component(value, component) - if value is None: - break - - return self.to_native(value) - - def to_native(self, value): - """ - Converts the field's value into it's simple representation. - """ - if is_simple_callable(value): - value = value() - - if is_protected_type(value): - return value - elif (is_non_str_iterable(value) and - not isinstance(value, (dict, six.string_types))): - return [self.to_native(item) for item in value] - elif isinstance(value, dict): - # Make sure we preserve field ordering, if it exists - ret = SortedDict() - for key, val in value.items(): - ret[key] = self.to_native(val) - return ret - return force_text(value) - - def attributes(self): - """ - Returns a dictionary of attributes to be used when serializing to xml. - """ - if self.type_name: - return {'type': self.type_name} - return {} - - def metadata(self): - metadata = SortedDict() - metadata['type'] = self.type_label - metadata['required'] = getattr(self, 'required', False) - optional_attrs = ['read_only', 'label', 'help_text', - 'min_length', 'max_length'] - for attr in optional_attrs: - value = getattr(self, attr, None) - if value is not None and value != '': - metadata[attr] = force_text(value, strings_only=True) - return metadata - - -class WritableField(Field): - """ - Base for read/write fields. - """ - write_only = False - default_validators = [] - default_error_messages = { - 'required': _('This field is required.'), - 'invalid': _('Invalid value.'), + MESSAGES = { + 'required': 'This field is required.' } - widget = widgets.TextInput - default = None - def __init__(self, source=None, label=None, help_text=None, - read_only=False, write_only=False, required=None, - validators=[], error_messages=None, widget=None, - default=None, blank=None): + _NOT_READ_ONLY_WRITE_ONLY = 'May not set both `read_only` and `write_only`' + _NOT_READ_ONLY_REQUIRED = 'May not set both `read_only` and `required`' + _NOT_READ_ONLY_DEFAULT = 'May not set both `read_only` and `default`' + _NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`' + _MISSING_ERROR_MESSAGE = ( + 'ValidationError raised by `{class_name}`, but error key `{key}` does ' + 'not exist in the `MESSAGES` dictionary.' + ) - super(WritableField, self).__init__(source=source, label=label, help_text=help_text) + def __init__(self, read_only=False, write_only=False, + required=None, default=empty, initial=None, source=None, + label=None, style=None): + self._creation_counter = Field._creation_counter + Field._creation_counter += 1 + + # If `required` is unset, then use `True` unless a default is provided. + if required is None: + required = default is empty and not read_only + + # Some combinations of keyword arguments do not make sense. + assert not (read_only and write_only), self._NOT_READ_ONLY_WRITE_ONLY + assert not (read_only and required), self._NOT_READ_ONLY_REQUIRED + assert not (read_only and default is not empty), self._NOT_READ_ONLY_DEFAULT + assert not (required and default is not empty), self._NOT_REQUIRED_DEFAULT self.read_only = read_only self.write_only = write_only + self.required = required + self.default = default + self.source = source + self.initial = initial + self.label = label + self.style = {} if style is None else style - assert not (read_only and write_only), "Cannot set read_only=True and write_only=True" + def bind(self, field_name, parent, root): + """ + Setup the context for the field instance. + """ + self.field_name = field_name + self.parent = parent + self.root = root - if required is None: - self.required = not(read_only) + # `self.label` should deafult to being based on the field name. + if self.label is None: + self.label = self.field_name.replace('_', ' ').capitalize() + + # self.source should default to being the same as the field name. + if self.source is None: + self.source = field_name + + # self.source_attrs is a list of attributes that need to be looked up + # when serializing the instance, or populating the validated data. + if self.source == '*': + self.source_attrs = [] else: - assert not (read_only and required), "Cannot set required=True and read_only=True" - self.required = required + self.source_attrs = self.source.split('.') - messages = {} - for c in reversed(self.__class__.__mro__): - messages.update(getattr(c, 'default_error_messages', {})) - messages.update(error_messages or {}) - self.error_messages = messages + def get_initial(self): + """ + Return a value to use when the field is being returned as a primative + value, without any object instance. + """ + return self.initial - self.validators = self.default_validators + validators - self.default = default if default is not None else self.default + def get_value(self, dictionary): + """ + Given the *incoming* primative data, return the value for this field + that should be validated and transformed to a native value. + """ + return dictionary.get(self.field_name, empty) - # Widgets are only used for HTML forms. - widget = widget or self.widget - if isinstance(widget, type): - widget = widget() - self.widget = widget + def get_attribute(self, instance): + """ + Given the *outgoing* object instance, return the value for this field + that should be returned as a primative value. + """ + return get_attribute(instance, self.source_attrs) - def __deepcopy__(self, memo): - result = copy.copy(self) - memo[id(self)] = result - result.validators = self.validators[:] - return result + def get_default(self): + """ + Return the default value to use when validating data if no input + is provided for this field. - def get_default_value(self): - if is_simple_callable(self.default): - return self.default() + If a default has not been set for this field then this will simply + return `empty`, indicating that no value should be set in the + validated data for this field. + """ + if self.default is empty: + raise SkipField() return self.default - def validate(self, value): - if value in validators.EMPTY_VALUES and self.required: - raise ValidationError(self.error_messages['required']) - - def run_validators(self, value): - if value in validators.EMPTY_VALUES: - return - errors = [] - for v in self.validators: - try: - v(value) - except ValidationError as e: - if hasattr(e, 'code') and e.code in self.error_messages: - message = self.error_messages[e.code] - if e.params: - message = message % e.params - errors.append(message) - else: - errors.extend(e.messages) - if errors: - raise ValidationError(errors) - - def field_to_native(self, obj, field_name): - if self.write_only: - return None - return super(WritableField, self).field_to_native(obj, field_name) - - def field_from_native(self, data, files, field_name, into): + def validate(self, data=empty): """ - Given a dictionary and a field name, updates the dictionary `into`, - with the field and it's deserialized value. + Validate a simple representation and return the internal value. + + The provided data may be `empty` if no representation was included. + May return `empty` if the field should not be included in the + validated data. """ - if self.read_only: - return + if data is empty: + if self.required: + self.fail('required') + return self.get_default() - try: - data = data or {} - if self.use_files: - files = files or {} - try: - native = files[field_name] - except KeyError: - native = data[field_name] - else: - native = data[field_name] - except KeyError: - if self.default is not None and not self.partial: - # Note: partial updates shouldn't set defaults - native = self.get_default_value() - else: - if self.required: - raise ValidationError(self.error_messages['required']) - return + return self.to_native(data) - value = self.from_native(native) - if self.source == '*': - if value: - into.update(value) - else: - self.validate(value) - self.run_validators(value) - into[self.source or field_name] = value - - def from_native(self, value): + def to_native(self, data): """ - Reverts a simple representation back to the field's value. + Transform the *incoming* primative data into a native value. + """ + return data + + def to_primative(self, value): + """ + Transform the *outgoing* native value into primative data. """ return value - -class ModelField(WritableField): - """ - A generic field that can be used against an arbitrary model field. - """ - def __init__(self, *args, **kwargs): + def fail(self, key, **kwargs): + """ + A helper method that simply raises a validation error. + """ try: - self.model_field = kwargs.pop('model_field') + raise ValidationError(self.MESSAGES[key].format(**kwargs)) except KeyError: - raise ValueError("ModelField requires 'model_field' kwarg") + class_name = self.__class__.__name__ + msg = self._MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key) + raise AssertionError(msg) - self.min_length = kwargs.pop('min_length', - getattr(self.model_field, 'min_length', None)) - self.max_length = kwargs.pop('max_length', - getattr(self.model_field, 'max_length', None)) - self.min_value = kwargs.pop('min_value', - getattr(self.model_field, 'min_value', None)) - self.max_value = kwargs.pop('max_value', - getattr(self.model_field, 'max_value', None)) - super(ModelField, self).__init__(*args, **kwargs) +class BooleanField(Field): + MESSAGES = { + 'required': 'This field is required.', + 'invalid_value': '`{input}` is not a valid boolean.' + } + TRUE_VALUES = {'t', 'T', 'true', 'True', 'TRUE', '1', 1, True} + FALSE_VALUES = {'f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False} - if self.min_length is not None: - self.validators.append(validators.MinLengthValidator(self.min_length)) - if self.max_length is not None: - self.validators.append(validators.MaxLengthValidator(self.max_length)) - if self.min_value is not None: - self.validators.append(validators.MinValueValidator(self.min_value)) - if self.max_value is not None: - self.validators.append(validators.MaxValueValidator(self.max_value)) + def get_value(self, dictionary): + if html.is_html_input(dictionary): + # HTML forms do not send a `False` value on an empty checkbox, + # so we override the default empty value to be False. + return dictionary.get(self.field_name, False) + return dictionary.get(self.field_name, empty) - def from_native(self, value): - rel = getattr(self.model_field, "rel", None) - if rel is not None: - return rel.to._meta.get_field(rel.field_name).to_python(value) + def to_native(self, data): + if data in self.TRUE_VALUES: + return True + elif data in self.FALSE_VALUES: + return False + self.fail('invalid_value', input=data) + + +class CharField(Field): + MESSAGES = { + 'required': 'This field is required.', + 'blank': 'This field may not be blank.' + } + + def __init__(self, *args, **kwargs): + self.allow_blank = kwargs.pop('allow_blank', False) + super(CharField, self).__init__(*args, **kwargs) + + def to_native(self, data): + if data == '' and not self.allow_blank: + self.fail('blank') + return str(data) + + +class ChoiceField(Field): + MESSAGES = { + 'required': 'This field is required.', + 'invalid_choice': '`{input}` is not a valid choice.' + } + coerce_to_type = str + + def __init__(self, *args, **kwargs): + choices = kwargs.pop('choices') + + assert choices, '`choices` argument is required and may not be empty' + + # 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 = {key: val for key, val in choices} else: - return self.model_field.to_python(value) + self.choices = {item: item for item in choices} - def field_to_native(self, obj, field_name): - value = self.model_field._get_val_from_obj(obj) - if is_protected_type(value): - return value - return self.model_field.value_to_string(obj) - - def attributes(self): - return { - "type": self.model_field.get_internal_type() + # Map the string representation of choices to the underlying value. + # Allows us to deal with eg. integer choices while supporting either + # integer or string input, but still get the correct datatype out. + self.choice_strings_to_values = { + str(key): key for key in self.choices.keys() } - -# Typed Fields - -class BooleanField(WritableField): - type_name = 'BooleanField' - type_label = 'boolean' - form_field_class = forms.BooleanField - widget = widgets.CheckboxInput - default_error_messages = { - 'invalid': _("'%s' value must be either True or False."), - } - empty = False - - def field_from_native(self, data, files, field_name, into): - # HTML checkboxes do not explicitly represent unchecked as `False` - # we deal with that here... - if isinstance(data, QueryDict) and self.default is None: - self.default = False - - return super(BooleanField, self).field_from_native( - data, files, field_name, into - ) - - def from_native(self, value): - if value in ('true', 't', 'True', '1'): - return True - if value in ('false', 'f', 'False', '0'): - return False - return bool(value) - - -class CharField(WritableField): - type_name = 'CharField' - type_label = 'string' - form_field_class = forms.CharField - - def __init__(self, max_length=None, min_length=None, allow_none=False, *args, **kwargs): - self.max_length, self.min_length = max_length, min_length - self.allow_none = allow_none - super(CharField, self).__init__(*args, **kwargs) - if min_length is not None: - self.validators.append(validators.MinLengthValidator(min_length)) - if max_length is not None: - self.validators.append(validators.MaxLengthValidator(max_length)) - - def from_native(self, value): - if isinstance(value, six.string_types): - return value - - if value is None and not self.allow_none: - return '' - - return smart_text(value) - - -class URLField(CharField): - type_name = 'URLField' - type_label = 'url' - - def __init__(self, **kwargs): - if 'validators' not in kwargs: - kwargs['validators'] = [validators.URLValidator()] - super(URLField, self).__init__(**kwargs) - - -class SlugField(CharField): - type_name = 'SlugField' - type_label = 'slug' - form_field_class = forms.SlugField - - default_error_messages = { - 'invalid': _("Enter a valid 'slug' consisting of letters, numbers," - " underscores or hyphens."), - } - default_validators = [validators.validate_slug] - - def __init__(self, *args, **kwargs): - super(SlugField, self).__init__(*args, **kwargs) - - -class ChoiceField(WritableField): - type_name = 'ChoiceField' - type_label = 'choice' - form_field_class = forms.ChoiceField - widget = widgets.Select - default_error_messages = { - 'invalid_choice': _('Select a valid choice. %(value)s is not one of ' - 'the available choices.'), - } - - def __init__(self, choices=(), blank_display_value=None, *args, **kwargs): - self.empty = kwargs.pop('empty', '') super(ChoiceField, self).__init__(*args, **kwargs) - self.choices = choices - if not self.required: - if blank_display_value is None: - blank_choice = BLANK_CHOICE_DASH - else: - blank_choice = [('', blank_display_value)] - self.choices = blank_choice + self.choices - - def _get_choices(self): - return self._choices - - def _set_choices(self, value): - # Setting choices also sets the choices on the widget. - # choices can be any iterable, but we call list() on it because - # it will be consumed more than once. - self._choices = self.widget.choices = list(value) - - choices = property(_get_choices, _set_choices) - - def metadata(self): - data = super(ChoiceField, self).metadata() - data['choices'] = [{'value': v, 'display_name': n} for v, n in self.choices] - return data - - def validate(self, value): - """ - Validates that the input is in self.choices. - """ - super(ChoiceField, self).validate(value) - if value and not self.valid_value(value): - raise ValidationError(self.error_messages['invalid_choice'] % {'value': value}) - - 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 - - def from_native(self, value): - value = super(ChoiceField, self).from_native(value) - if value == self.empty or value in validators.EMPTY_VALUES: - return self.empty - return value - - -class EmailField(CharField): - type_name = 'EmailField' - type_label = 'email' - form_field_class = forms.EmailField - - default_error_messages = { - 'invalid': _('Enter a valid email address.'), - } - default_validators = [validators.validate_email] - - def from_native(self, value): - ret = super(EmailField, self).from_native(value) - if ret is None: - return None - return ret.strip() - - -class RegexField(CharField): - type_name = 'RegexField' - type_label = 'regex' - form_field_class = forms.RegexField - - def __init__(self, regex, max_length=None, min_length=None, *args, **kwargs): - super(RegexField, self).__init__(max_length, min_length, *args, **kwargs) - self.regex = regex - - def _get_regex(self): - return self._regex - - def _set_regex(self, regex): - if isinstance(regex, six.string_types): - regex = re.compile(regex) - self._regex = regex - if hasattr(self, '_regex_validator') and self._regex_validator in self.validators: - self.validators.remove(self._regex_validator) - self._regex_validator = validators.RegexValidator(regex=regex) - self.validators.append(self._regex_validator) - - regex = property(_get_regex, _set_regex) - - -class DateField(WritableField): - type_name = 'DateField' - type_label = 'date' - widget = widgets.DateInput - form_field_class = forms.DateField - - default_error_messages = { - 'invalid': _("Date has wrong format. Use one of these formats instead: %s"), - } - empty = None - input_formats = api_settings.DATE_INPUT_FORMATS - format = api_settings.DATE_FORMAT - - def __init__(self, input_formats=None, format=None, *args, **kwargs): - self.input_formats = input_formats if input_formats is not None else self.input_formats - self.format = format if format is not None else self.format - super(DateField, self).__init__(*args, **kwargs) - - def from_native(self, value): - if value in validators.EMPTY_VALUES: - return None - - if isinstance(value, datetime.datetime): - if timezone and settings.USE_TZ and timezone.is_aware(value): - # Convert aware datetimes to the default time zone - # before casting them to dates (#17742). - default_timezone = timezone.get_default_timezone() - value = timezone.make_naive(value, default_timezone) - return value.date() - if isinstance(value, datetime.date): - return value - - for format in self.input_formats: - if format.lower() == ISO_8601: - try: - parsed = parse_date(value) - except (ValueError, TypeError): - pass - else: - if parsed is not None: - return parsed - else: - try: - parsed = datetime.datetime.strptime(value, format) - except (ValueError, TypeError): - pass - else: - return parsed.date() - - msg = self.error_messages['invalid'] % readable_date_formats(self.input_formats) - raise ValidationError(msg) - - def to_native(self, value): - if value is None or self.format is None: - return value - - if isinstance(value, datetime.datetime): - value = value.date() - - if self.format.lower() == ISO_8601: - return value.isoformat() - return value.strftime(self.format) - - -class DateTimeField(WritableField): - type_name = 'DateTimeField' - type_label = 'datetime' - widget = widgets.DateTimeInput - form_field_class = forms.DateTimeField - - default_error_messages = { - 'invalid': _("Datetime has wrong format. Use one of these formats instead: %s"), - } - empty = None - input_formats = api_settings.DATETIME_INPUT_FORMATS - format = api_settings.DATETIME_FORMAT - - def __init__(self, input_formats=None, format=None, *args, **kwargs): - self.input_formats = input_formats if input_formats is not None else self.input_formats - self.format = format if format is not None else self.format - super(DateTimeField, self).__init__(*args, **kwargs) - - def from_native(self, value): - if value in validators.EMPTY_VALUES: - return None - - if isinstance(value, datetime.datetime): - return value - if isinstance(value, datetime.date): - value = datetime.datetime(value.year, value.month, value.day) - if settings.USE_TZ: - # For backwards compatibility, interpret naive datetimes in - # local time. This won't work during DST change, but we can't - # do much about it, so we let the exceptions percolate up the - # call stack. - warnings.warn("DateTimeField received a naive datetime (%s)" - " while time zone support is active." % value, - RuntimeWarning) - default_timezone = timezone.get_default_timezone() - value = timezone.make_aware(value, default_timezone) - return value - - for format in self.input_formats: - if format.lower() == ISO_8601: - try: - parsed = parse_datetime(value) - except (ValueError, TypeError): - pass - else: - if parsed is not None: - return parsed - else: - try: - parsed = datetime.datetime.strptime(value, format) - except (ValueError, TypeError): - pass - else: - return parsed - - msg = self.error_messages['invalid'] % readable_datetime_formats(self.input_formats) - raise ValidationError(msg) - - def to_native(self, value): - if value is None or self.format is None: - return value - - if self.format.lower() == ISO_8601: - ret = value.isoformat() - if ret.endswith('+00:00'): - ret = ret[:-6] + 'Z' - return ret - return value.strftime(self.format) - - -class TimeField(WritableField): - type_name = 'TimeField' - type_label = 'time' - widget = widgets.TimeInput - form_field_class = forms.TimeField - - default_error_messages = { - 'invalid': _("Time has wrong format. Use one of these formats instead: %s"), - } - empty = None - input_formats = api_settings.TIME_INPUT_FORMATS - format = api_settings.TIME_FORMAT - - def __init__(self, input_formats=None, format=None, *args, **kwargs): - self.input_formats = input_formats if input_formats is not None else self.input_formats - self.format = format if format is not None else self.format - super(TimeField, self).__init__(*args, **kwargs) - - def from_native(self, value): - if value in validators.EMPTY_VALUES: - return None - - if isinstance(value, datetime.time): - return value - - for format in self.input_formats: - if format.lower() == ISO_8601: - try: - parsed = parse_time(value) - except (ValueError, TypeError): - pass - else: - if parsed is not None: - return parsed - else: - try: - parsed = datetime.datetime.strptime(value, format) - except (ValueError, TypeError): - pass - else: - return parsed.time() - - msg = self.error_messages['invalid'] % readable_time_formats(self.input_formats) - raise ValidationError(msg) - - def to_native(self, value): - if value is None or self.format is None: - return value - - if isinstance(value, datetime.datetime): - value = value.time() - - if self.format.lower() == ISO_8601: - return value.isoformat() - return value.strftime(self.format) - - -class IntegerField(WritableField): - type_name = 'IntegerField' - type_label = 'integer' - form_field_class = forms.IntegerField - empty = 0 - - default_error_messages = { - 'invalid': _('Enter a whole number.'), - 'max_value': _('Ensure this value is less than or equal to %(limit_value)s.'), - 'min_value': _('Ensure this value is greater than or equal to %(limit_value)s.'), - } - - def __init__(self, max_value=None, min_value=None, *args, **kwargs): - self.max_value, self.min_value = max_value, min_value - super(IntegerField, self).__init__(*args, **kwargs) - - if max_value is not None: - self.validators.append(validators.MaxValueValidator(max_value)) - if min_value is not None: - self.validators.append(validators.MinValueValidator(min_value)) - - def from_native(self, value): - if value in validators.EMPTY_VALUES: - return None + def to_native(self, data): try: - value = int(str(value)) + return self.choice_strings_to_values[str(data)] + except KeyError: + self.fail('invalid_choice', input=data) + + +class MultipleChoiceField(ChoiceField): + MESSAGES = { + 'required': 'This field is required.', + 'invalid_choice': '`{input}` is not a valid choice.', + 'not_a_list': 'Expected a list of items but got type `{input_type}`' + } + + def to_native(self, data): + if not hasattr(data, '__iter__'): + self.fail('not_a_list', input_type=type(data).__name__) + return set([ + super(MultipleChoiceField, self).to_native(item) + for item in data + ]) + + +class IntegerField(Field): + MESSAGES = { + 'required': 'This field is required.', + 'invalid_integer': 'A valid integer is required.' + } + + def to_native(self, data): + try: + data = int(str(data)) except (ValueError, TypeError): - raise ValidationError(self.error_messages['invalid']) - return value - - -class FloatField(WritableField): - type_name = 'FloatField' - type_label = 'float' - form_field_class = forms.FloatField - empty = 0 - - default_error_messages = { - 'invalid': _("'%s' value must be a float."), - } - - def from_native(self, value): - if value in validators.EMPTY_VALUES: - return None - - try: - return float(value) - except (TypeError, ValueError): - msg = self.error_messages['invalid'] % value - raise ValidationError(msg) - - -class DecimalField(WritableField): - type_name = 'DecimalField' - type_label = 'decimal' - form_field_class = forms.DecimalField - empty = Decimal('0') - - default_error_messages = { - 'invalid': _('Enter a number.'), - 'max_value': _('Ensure this value is less than or equal to %(limit_value)s.'), - 'min_value': _('Ensure this value is greater than or equal to %(limit_value)s.'), - 'max_digits': _('Ensure that there are no more than %s digits in total.'), - 'max_decimal_places': _('Ensure that there are no more than %s decimal places.'), - 'max_whole_digits': _('Ensure that there are no more than %s digits before the decimal point.') - } - - def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs): - self.max_value, self.min_value = max_value, min_value - self.max_digits, self.decimal_places = max_digits, decimal_places - super(DecimalField, self).__init__(*args, **kwargs) - - if max_value is not None: - self.validators.append(validators.MaxValueValidator(max_value)) - if min_value is not None: - self.validators.append(validators.MinValueValidator(min_value)) - - def from_native(self, value): - """ - Validates that the input is a decimal number. Returns a Decimal - instance. Returns None for empty values. Ensures that there are no more - than max_digits in the number, and no more than decimal_places digits - after the decimal point. - """ - if value in validators.EMPTY_VALUES: - return None - value = smart_text(value).strip() - try: - value = Decimal(value) - except DecimalException: - raise ValidationError(self.error_messages['invalid']) - return value - - def validate(self, value): - super(DecimalField, self).validate(value) - if value in validators.EMPTY_VALUES: - return - # Check for NaN, Inf and -Inf values. We can't compare directly for NaN, - # since it is never equal to itself. However, NaN is the only value that - # isn't equal to itself, so we can use this to identify NaN - if value != value or value == Decimal("Inf") or value == Decimal("-Inf"): - raise ValidationError(self.error_messages['invalid']) - sign, digittuple, exponent = value.as_tuple() - decimals = abs(exponent) - # digittuple doesn't include any leading zeros. - digits = len(digittuple) - if decimals > digits: - # We have leading zeros up to or past the decimal point. Count - # everything past the decimal point as a digit. We do not count - # 0 before the decimal point as a digit since that would mean - # we would not allow max_digits = decimal_places. - digits = decimals - whole_digits = digits - decimals - - if self.max_digits is not None and digits > self.max_digits: - raise ValidationError(self.error_messages['max_digits'] % self.max_digits) - if self.decimal_places is not None and decimals > self.decimal_places: - raise ValidationError(self.error_messages['max_decimal_places'] % self.decimal_places) - if self.max_digits is not None and self.decimal_places is not None and whole_digits > (self.max_digits - self.decimal_places): - raise ValidationError(self.error_messages['max_whole_digits'] % (self.max_digits - self.decimal_places)) - return value - - -class FileField(WritableField): - use_files = True - type_name = 'FileField' - type_label = 'file upload' - form_field_class = forms.FileField - widget = widgets.FileInput - - default_error_messages = { - 'invalid': _("No file was submitted. Check the encoding type on the form."), - 'missing': _("No file was submitted."), - 'empty': _("The submitted file is empty."), - 'max_length': _('Ensure this filename has at most %(max)d characters (it has %(length)d).'), - 'contradiction': _('Please either submit a file or check the clear checkbox, not both.') - } - - def __init__(self, *args, **kwargs): - self.max_length = kwargs.pop('max_length', None) - self.allow_empty_file = kwargs.pop('allow_empty_file', False) - super(FileField, self).__init__(*args, **kwargs) - - def from_native(self, data): - if data in validators.EMPTY_VALUES: - return None - - # UploadedFile objects should have name and size attributes. - try: - file_name = data.name - file_size = data.size - except AttributeError: - raise ValidationError(self.error_messages['invalid']) - - if self.max_length is not None and len(file_name) > self.max_length: - error_values = {'max': self.max_length, 'length': len(file_name)} - raise ValidationError(self.error_messages['max_length'] % error_values) - if not file_name: - raise ValidationError(self.error_messages['invalid']) - if not self.allow_empty_file and not file_size: - raise ValidationError(self.error_messages['empty']) - + self.fail('invalid_integer') return data - def to_native(self, value): - return value.name +class MethodField(Field): + def __init__(self, **kwargs): + kwargs['source'] = '*' + kwargs['read_only'] = True + super(MethodField, self).__init__(**kwargs) -class ImageField(FileField): - use_files = True - type_name = 'ImageField' - type_label = 'image upload' - form_field_class = forms.ImageField - - default_error_messages = { - 'invalid_image': _("Upload a valid image. The file you uploaded was " - "either not an image or a corrupted image."), - } - - def from_native(self, data): - """ - Checks that the file-upload field data contains a valid image (GIF, JPG, - PNG, possibly others -- whatever the Python Imaging Library supports). - """ - f = super(ImageField, self).from_native(data) - if f is None: - return None - - from rest_framework.compat import Image - assert Image is not None, 'Either Pillow or PIL must be installed for ImageField support.' - - # We need to get a file object for PIL. We might have a path or we might - # have to read the data into memory. - if hasattr(data, 'temporary_file_path'): - file = data.temporary_file_path() - else: - if hasattr(data, 'read'): - file = BytesIO(data.read()) - else: - file = BytesIO(data['content']) - - try: - # load() could spot a truncated JPEG, but it loads the entire - # image in memory, which is a DoS vector. See #3848 and #18520. - # verify() must be called immediately after the constructor. - Image.open(file).verify() - except ImportError: - # Under PyPy, it is possible to import PIL. However, the underlying - # _imaging C module isn't available, so an ImportError will be - # raised. Catch and re-raise. - raise - except Exception: # Python Imaging Library doesn't recognize it as an image - raise ValidationError(self.error_messages['invalid_image']) - if hasattr(f, 'seek') and callable(f.seek): - f.seek(0) - return f - - -class SerializerMethodField(Field): - """ - A field that gets its value by calling a method on the serializer it's attached to. - """ - - def __init__(self, method_name, *args, **kwargs): - self.method_name = method_name - super(SerializerMethodField, self).__init__(*args, **kwargs) - - def field_to_native(self, obj, field_name): - value = getattr(self.parent, self.method_name)(obj) - return self.to_native(value) + def to_primative(self, value): + attr = 'get_{field_name}'.format(field_name=self.field_name) + method = getattr(self.parent, attr) + return method(value) diff --git a/rest_framework/generics.py b/rest_framework/generics.py index b3bd6ce92..6705cbb2f 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -79,18 +79,16 @@ class GenericAPIView(views.APIView): 'view': self } - def get_serializer(self, instance=None, data=None, files=None, many=False, - partial=False, allow_add_remove=False): + def get_serializer(self, instance=None, data=None, many=False, partial=False): """ 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, files=files, - many=many, partial=partial, - allow_add_remove=allow_add_remove, - context=context) + return serializer_class( + instance, data=data, many=many, partial=partial, context=context + ) def get_pagination_serializer(self, page): """ diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index ac59d9795..ee01cabc7 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -36,12 +36,10 @@ class CreateModelMixin(object): Create a model instance. """ def create(self, request, *args, **kwargs): - serializer = self.get_serializer(data=request.DATA, files=request.FILES) + serializer = self.get_serializer(data=request.DATA) if serializer.is_valid(): - self.pre_save(serializer.object) - self.object = serializer.save(force_insert=True) - self.post_save(self.object, created=True) + self.object = serializer.save() headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) @@ -90,26 +88,20 @@ class UpdateModelMixin(object): partial = kwargs.pop('partial', False) self.object = self.get_object_or_none() - serializer = self.get_serializer(self.object, data=request.DATA, - files=request.FILES, partial=partial) + serializer = self.get_serializer(self.object, data=request.DATA, partial=partial) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - try: - self.pre_save(serializer.object) - except ValidationError as err: - # full_clean on model instance may be called in pre_save, - # so we have to handle eventual errors. - return Response(err.message_dict, status=status.HTTP_400_BAD_REQUEST) + lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field + lookup_value = self.kwargs[lookup_url_kwarg] + extras = {self.lookup_field: lookup_value} if self.object is None: - self.object = serializer.save(force_insert=True) - self.post_save(self.object, created=True) + self.object = serializer.save(extras=extras) return Response(serializer.data, status=status.HTTP_201_CREATED) - self.object = serializer.save(force_update=True) - self.post_save(self.object, created=False) + self.object = serializer.save(extras=extras) return Response(serializer.data, status=status.HTTP_200_OK) def partial_update(self, request, *args, **kwargs): diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index d51ea929b..83ef97c5c 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -48,17 +48,17 @@ class DefaultObjectSerializer(serializers.Field): super(DefaultObjectSerializer, self).__init__(source=source) -class PaginationSerializerOptions(serializers.SerializerOptions): - """ - An object that stores the options that may be provided to a - pagination serializer by using the inner `Meta` class. +# class PaginationSerializerOptions(serializers.SerializerOptions): +# """ +# An object that stores the options that may be provided to a +# pagination serializer by using the inner `Meta` class. - Accessible on the instance as `serializer.opts`. - """ - def __init__(self, meta): - super(PaginationSerializerOptions, self).__init__(meta) - self.object_serializer_class = getattr(meta, 'object_serializer_class', - DefaultObjectSerializer) +# Accessible on the instance as `serializer.opts`. +# """ +# def __init__(self, meta): +# super(PaginationSerializerOptions, self).__init__(meta) +# self.object_serializer_class = getattr(meta, 'object_serializer_class', +# DefaultObjectSerializer) class BasePaginationSerializer(serializers.Serializer): @@ -66,7 +66,7 @@ class BasePaginationSerializer(serializers.Serializer): A base class for pagination serializers to inherit from, to make implementing custom serializers more easy. """ - _options_class = PaginationSerializerOptions + # _options_class = PaginationSerializerOptions results_field = 'results' def __init__(self, *args, **kwargs): diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 56870b408..e69de29bb 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -1,486 +0,0 @@ -""" -Serializer fields that deal with relationships. - -These fields allow you to specify the style that should be used to represent -model relationships, including hyperlinks, primary keys, or slugs. -""" -from __future__ import unicode_literals -from django.core.exceptions import ObjectDoesNotExist, ValidationError -from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch -from django import forms -from django.db.models.fields import BLANK_CHOICE_DASH -from django.forms import widgets -from django.forms.models import ModelChoiceIterator -from django.utils.translation import ugettext_lazy as _ -from rest_framework.fields import Field, WritableField, get_component, is_simple_callable -from rest_framework.reverse import reverse -from rest_framework.compat import urlparse -from rest_framework.compat import smart_text - - -# Relational fields - -# Not actually Writable, but subclasses may need to be. -class RelatedField(WritableField): - """ - Base class for related model fields. - - This represents a relationship using the unicode representation of the target. - """ - widget = widgets.Select - many_widget = widgets.SelectMultiple - form_field_class = forms.ChoiceField - many_form_field_class = forms.MultipleChoiceField - null_values = (None, '', 'None') - - cache_choices = False - empty_label = None - read_only = True - many = False - - def __init__(self, *args, **kwargs): - queryset = kwargs.pop('queryset', None) - self.many = kwargs.pop('many', self.many) - if self.many: - self.widget = self.many_widget - self.form_field_class = self.many_form_field_class - - kwargs['read_only'] = kwargs.pop('read_only', self.read_only) - super(RelatedField, self).__init__(*args, **kwargs) - - if not self.required: - # Accessed in ModelChoiceIterator django/forms/models.py:1034 - # If set adds empty choice. - self.empty_label = BLANK_CHOICE_DASH[0][1] - - self.queryset = queryset - - def initialize(self, parent, field_name): - super(RelatedField, self).initialize(parent, field_name) - if self.queryset is None and not self.read_only: - manager = getattr(self.parent.opts.model, self.source or field_name) - if hasattr(manager, 'related'): # Forward - self.queryset = manager.related.model._default_manager.all() - else: # Reverse - self.queryset = manager.field.rel.to._default_manager.all() - - # We need this stuff to make form choices work... - - def prepare_value(self, obj): - return self.to_native(obj) - - def label_from_instance(self, obj): - """ - Return a readable representation for use with eg. select widgets. - """ - desc = smart_text(obj) - ident = smart_text(self.to_native(obj)) - if desc == ident: - return desc - return "%s - %s" % (desc, ident) - - def _get_queryset(self): - return self._queryset - - def _set_queryset(self, queryset): - self._queryset = queryset - self.widget.choices = self.choices - - queryset = property(_get_queryset, _set_queryset) - - def _get_choices(self): - # If self._choices is set, then somebody must have manually set - # the property self.choices. In this case, just return self._choices. - if hasattr(self, '_choices'): - return self._choices - - # Otherwise, execute the QuerySet in self.queryset to determine the - # choices dynamically. Return a fresh ModelChoiceIterator that has not been - # consumed. Note that we're instantiating a new ModelChoiceIterator *each* - # time _get_choices() is called (and, thus, each time self.choices is - # accessed) so that we can ensure the QuerySet has not been consumed. This - # construct might look complicated but it allows for lazy evaluation of - # the queryset. - return ModelChoiceIterator(self) - - def _set_choices(self, value): - # Setting choices also sets the choices on the widget. - # choices can be any iterable, but we call list() on it because - # it will be consumed more than once. - self._choices = self.widget.choices = list(value) - - choices = property(_get_choices, _set_choices) - - # Default value handling - - def get_default_value(self): - default = super(RelatedField, self).get_default_value() - if self.many and default is None: - return [] - return default - - # Regular serializer stuff... - - def field_to_native(self, obj, field_name): - try: - if self.source == '*': - return self.to_native(obj) - - source = self.source or field_name - value = obj - - for component in source.split('.'): - if value is None: - break - value = get_component(value, component) - except ObjectDoesNotExist: - return None - - if value is None: - return None - - if self.many: - if is_simple_callable(getattr(value, 'all', None)): - return [self.to_native(item) for item in value.all()] - else: - # Also support non-queryset iterables. - # This allows us to also support plain lists of related items. - return [self.to_native(item) for item in value] - return self.to_native(value) - - def field_from_native(self, data, files, field_name, into): - if self.read_only: - return - - try: - if self.many: - try: - # Form data - value = data.getlist(field_name) - if value == [''] or value == []: - raise KeyError - except AttributeError: - # Non-form data - value = data[field_name] - else: - value = data[field_name] - except KeyError: - if self.partial: - return - value = self.get_default_value() - - if value in self.null_values: - if self.required: - raise ValidationError(self.error_messages['required']) - into[(self.source or field_name)] = None - elif self.many: - into[(self.source or field_name)] = [self.from_native(item) for item in value] - else: - into[(self.source or field_name)] = self.from_native(value) - - -# PrimaryKey relationships - -class PrimaryKeyRelatedField(RelatedField): - """ - Represents a relationship as a pk value. - """ - read_only = False - - default_error_messages = { - 'does_not_exist': _("Invalid pk '%s' - object does not exist."), - 'incorrect_type': _('Incorrect type. Expected pk value, received %s.'), - } - - # TODO: Remove these field hacks... - def prepare_value(self, obj): - return self.to_native(obj.pk) - - def label_from_instance(self, obj): - """ - Return a readable representation for use with eg. select widgets. - """ - desc = smart_text(obj) - ident = smart_text(self.to_native(obj.pk)) - if desc == ident: - return desc - return "%s - %s" % (desc, ident) - - # TODO: Possibly change this to just take `obj`, through prob less performant - def to_native(self, pk): - return pk - - def from_native(self, data): - if self.queryset is None: - raise Exception('Writable related fields must include a `queryset` argument') - - try: - return self.queryset.get(pk=data) - except ObjectDoesNotExist: - msg = self.error_messages['does_not_exist'] % smart_text(data) - raise ValidationError(msg) - except (TypeError, ValueError): - received = type(data).__name__ - msg = self.error_messages['incorrect_type'] % received - raise ValidationError(msg) - - def field_to_native(self, obj, field_name): - if self.many: - # To-many relationship - - queryset = None - if not self.source: - # Prefer obj.serializable_value for performance reasons - try: - queryset = obj.serializable_value(field_name) - except AttributeError: - pass - if queryset is None: - # RelatedManager (reverse relationship) - source = self.source or field_name - queryset = obj - for component in source.split('.'): - if queryset is None: - return [] - queryset = get_component(queryset, component) - - # Forward relationship - if is_simple_callable(getattr(queryset, 'all', None)): - return [self.to_native(item.pk) for item in queryset.all()] - else: - # Also support non-queryset iterables. - # This allows us to also support plain lists of related items. - return [self.to_native(item.pk) for item in queryset] - - # To-one relationship - try: - # Prefer obj.serializable_value for performance reasons - pk = obj.serializable_value(self.source or field_name) - except AttributeError: - # RelatedObject (reverse relationship) - try: - pk = getattr(obj, self.source or field_name).pk - except (ObjectDoesNotExist, AttributeError): - return None - - # Forward relationship - return self.to_native(pk) - - -# Slug relationships - -class SlugRelatedField(RelatedField): - """ - Represents a relationship using a unique field on the target. - """ - read_only = False - - default_error_messages = { - 'does_not_exist': _("Object with %s=%s does not exist."), - 'invalid': _('Invalid value.'), - } - - def __init__(self, *args, **kwargs): - self.slug_field = kwargs.pop('slug_field', None) - assert self.slug_field, 'slug_field is required' - super(SlugRelatedField, self).__init__(*args, **kwargs) - - def to_native(self, obj): - return getattr(obj, self.slug_field) - - def from_native(self, data): - if self.queryset is None: - raise Exception('Writable related fields must include a `queryset` argument') - - try: - return self.queryset.get(**{self.slug_field: data}) - except ObjectDoesNotExist: - raise ValidationError(self.error_messages['does_not_exist'] % - (self.slug_field, smart_text(data))) - except (TypeError, ValueError): - msg = self.error_messages['invalid'] - raise ValidationError(msg) - - -# Hyperlinked relationships - -class HyperlinkedRelatedField(RelatedField): - """ - Represents a relationship using hyperlinking. - """ - read_only = False - lookup_field = 'pk' - - default_error_messages = { - 'no_match': _('Invalid hyperlink - No URL match'), - 'incorrect_match': _('Invalid hyperlink - Incorrect URL match'), - 'configuration_error': _('Invalid hyperlink due to configuration error'), - 'does_not_exist': _("Invalid hyperlink - object does not exist."), - 'incorrect_type': _('Incorrect type. Expected url string, received %s.'), - } - - def __init__(self, *args, **kwargs): - try: - self.view_name = kwargs.pop('view_name') - except KeyError: - raise ValueError("Hyperlinked field requires 'view_name' kwarg") - - self.lookup_field = kwargs.pop('lookup_field', self.lookup_field) - self.format = kwargs.pop('format', None) - - super(HyperlinkedRelatedField, self).__init__(*args, **kwargs) - - def get_url(self, obj, view_name, request, format): - """ - Given an object, return the URL that hyperlinks to the object. - - May raise a `NoReverseMatch` if the `view_name` and `lookup_field` - attributes are not configured to correctly match the URL conf. - """ - lookup_field = getattr(obj, self.lookup_field) - kwargs = {self.lookup_field: lookup_field} - return reverse(view_name, kwargs=kwargs, request=request, format=format) - - def get_object(self, queryset, view_name, view_args, view_kwargs): - """ - Return the object corresponding to a matched URL. - - Takes the matched URL conf arguments, and the queryset, and should - return an object instance, or raise an `ObjectDoesNotExist` exception. - """ - lookup_value = view_kwargs[self.lookup_field] - filter_kwargs = {self.lookup_field: lookup_value} - return queryset.get(**filter_kwargs) - - def to_native(self, obj): - view_name = self.view_name - request = self.context.get('request', None) - format = self.format or self.context.get('format', None) - - assert request is not None, ( - "`HyperlinkedRelatedField` requires the request in the serializer " - "context. Add `context={'request': request}` when instantiating " - "the serializer." - ) - - # If the object has not yet been saved then we cannot hyperlink to it. - if getattr(obj, 'pk', None) is None: - return - - # Return the hyperlink, or error if incorrectly configured. - try: - return self.get_url(obj, view_name, request, format) - except NoReverseMatch: - msg = ( - 'Could not resolve URL for hyperlinked relationship using ' - 'view name "%s". You may have failed to include the related ' - 'model in your API, or incorrectly configured the ' - '`lookup_field` attribute on this field.' - ) - raise Exception(msg % view_name) - - def from_native(self, value): - # Convert URL -> model instance pk - # TODO: Use values_list - queryset = self.queryset - if queryset is None: - raise Exception('Writable related fields must include a `queryset` argument') - - try: - http_prefix = value.startswith(('http:', 'https:')) - except AttributeError: - msg = self.error_messages['incorrect_type'] - raise ValidationError(msg % type(value).__name__) - - if http_prefix: - # If needed convert absolute URLs to relative path - value = urlparse.urlparse(value).path - prefix = get_script_prefix() - if value.startswith(prefix): - value = '/' + value[len(prefix):] - - try: - match = resolve(value) - except Exception: - raise ValidationError(self.error_messages['no_match']) - - if match.view_name != self.view_name: - raise ValidationError(self.error_messages['incorrect_match']) - - try: - return self.get_object(queryset, match.view_name, - match.args, match.kwargs) - except (ObjectDoesNotExist, TypeError, ValueError): - raise ValidationError(self.error_messages['does_not_exist']) - - -class HyperlinkedIdentityField(Field): - """ - Represents the instance, or a property on the instance, using hyperlinking. - """ - lookup_field = 'pk' - read_only = True - - def __init__(self, *args, **kwargs): - try: - self.view_name = kwargs.pop('view_name') - except KeyError: - msg = "HyperlinkedIdentityField requires 'view_name' argument" - raise ValueError(msg) - - self.format = kwargs.pop('format', None) - lookup_field = kwargs.pop('lookup_field', None) - self.lookup_field = lookup_field or self.lookup_field - - super(HyperlinkedIdentityField, self).__init__(*args, **kwargs) - - def field_to_native(self, obj, field_name): - request = self.context.get('request', None) - format = self.context.get('format', None) - view_name = self.view_name - - assert request is not None, ( - "`HyperlinkedIdentityField` requires the request in the serializer" - " context. Add `context={'request': request}` when instantiating " - "the serializer." - ) - - # By default use whatever format is given for the current context - # unless the target is a different type to the source. - # - # Eg. Consider a HyperlinkedIdentityField pointing from a json - # representation to an html property of that representation... - # - # '/snippets/1/' should link to '/snippets/1/highlight/' - # ...but... - # '/snippets/1/.json' should link to '/snippets/1/highlight/.html' - if format and self.format and self.format != format: - format = self.format - - # Return the hyperlink, or error if incorrectly configured. - try: - return self.get_url(obj, view_name, request, format) - except NoReverseMatch: - msg = ( - 'Could not resolve URL for hyperlinked relationship using ' - 'view name "%s". You may have failed to include the related ' - 'model in your API, or incorrectly configured the ' - '`lookup_field` attribute on this field.' - ) - raise Exception(msg % view_name) - - def get_url(self, obj, view_name, request, format): - """ - Given an object, return the URL that hyperlinks to the object. - - May raise a `NoReverseMatch` if the `view_name` and `lookup_field` - attributes are not configured to correctly match the URL conf. - """ - lookup_field = getattr(obj, self.lookup_field, None) - kwargs = {self.lookup_field: lookup_field} - - # Handle unsaved object case - if lookup_field is None: - return None - - return reverse(view_name, kwargs=kwargs, request=request, format=format) diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 748ebac94..e8935b012 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -458,7 +458,7 @@ class BrowsableAPIRenderer(BaseRenderer): ): return - serializer = view.get_serializer(instance=obj, data=data, files=files) + serializer = view.get_serializer(instance=obj, data=data) serializer.is_valid() data = serializer.data @@ -579,10 +579,10 @@ class BrowsableAPIRenderer(BaseRenderer): 'available_formats': [renderer_cls.format for renderer_cls in view.renderer_classes], 'response_headers': response_headers, - 'put_form': self.get_rendered_html_form(view, 'PUT', request), - 'post_form': self.get_rendered_html_form(view, 'POST', request), - 'delete_form': self.get_rendered_html_form(view, 'DELETE', request), - 'options_form': self.get_rendered_html_form(view, 'OPTIONS', request), + #'put_form': self.get_rendered_html_form(view, 'PUT', request), + #'post_form': self.get_rendered_html_form(view, 'POST', request), + #'delete_form': self.get_rendered_html_form(view, 'DELETE', request), + #'options_form': self.get_rendered_html_form(view, 'OPTIONS', request), 'raw_data_put_form': raw_data_put_form, 'raw_data_post_form': raw_data_post_form, diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index be8ad3f24..d121812d6 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -10,21 +10,14 @@ python primitives. 2. The process of marshalling between python primitives and request and response content is handled by parsers and renderers. """ -from __future__ import unicode_literals -import copy -import datetime -import inspect -import types -from decimal import Decimal -from django.contrib.contenttypes.generic import GenericForeignKey -from django.core.paginator import Page from django.db import models -from django.forms import widgets from django.utils import six -from django.utils.datastructures import SortedDict -from django.core.exceptions import ObjectDoesNotExist +from collections import namedtuple, OrderedDict +from rest_framework.fields import empty, set_value, Field, SkipField, ValidationError from rest_framework.settings import api_settings - +from rest_framework.utils import html +import copy +import inspect # Note: We do the following so that users of the framework can use this style: # @@ -37,6 +30,253 @@ from rest_framework.relations import * # NOQA from rest_framework.fields import * # NOQA +FieldResult = namedtuple('FieldResult', ['field', 'value', 'error']) + + +class BaseSerializer(Field): + def __init__(self, instance=None, data=None, **kwargs): + super(BaseSerializer, self).__init__(**kwargs) + self.instance = instance + self._initial_data = data + + def to_native(self, data): + raise NotImplementedError() + + def to_primative(self, instance): + raise NotImplementedError() + + def update(self, instance): + raise NotImplementedError() + + def create(self): + raise NotImplementedError() + + def save(self, extras=None): + if extras is not None: + self._validated_data.update(extras) + + if self.instance is not None: + self.update(self.instance) + else: + self.instance = self.create() + + return self.instance + + def is_valid(self): + try: + self._validated_data = self.to_native(self._initial_data) + except ValidationError as exc: + self._validated_data = {} + self._errors = exc.args[0] + return False + self._errors = {} + return True + + @property + def data(self): + if not hasattr(self, '_data'): + if self.instance is not None: + self._data = self.to_primative(self.instance) + elif self._initial_data is not None: + self._data = { + field_name: field.get_value(self._initial_data) + for field_name, field in self.fields.items() + } + else: + self._data = self.get_initial() + return self._data + + @property + def errors(self): + if not hasattr(self, '_errors'): + msg = 'You must call `.is_valid()` before accessing `.errors`.' + raise AssertionError(msg) + return self._errors + + @property + def validated_data(self): + if not hasattr(self, '_validated_data'): + msg = 'You must call `.is_valid()` before accessing `.validated_data`.' + raise AssertionError(msg) + return self._validated_data + + +class SerializerMetaclass(type): + """ + This metaclass sets a dictionary named `base_fields` on the class. + + Any fields included as attributes on either the class or it's superclasses + will be include in the `base_fields` dictionary. + """ + + @classmethod + def _get_fields(cls, bases, attrs): + fields = [(field_name, attrs.pop(field_name)) + for field_name, obj in list(attrs.items()) + if isinstance(obj, Field)] + fields.sort(key=lambda x: x[1]._creation_counter) + + # If this class is subclassing another Serializer, add that Serializer's + # fields. Note that we loop over the bases in *reverse*. This is necessary + # in order to maintain the correct order of fields. + for base in bases[::-1]: + if hasattr(base, 'base_fields'): + fields = list(base.base_fields.items()) + fields + + return OrderedDict(fields) + + def __new__(cls, name, bases, attrs): + attrs['base_fields'] = cls._get_fields(bases, attrs) + return super(SerializerMetaclass, cls).__new__(cls, name, bases, attrs) + + +@six.add_metaclass(SerializerMetaclass) +class Serializer(BaseSerializer): + + def __new__(cls, *args, **kwargs): + many = kwargs.pop('many', False) + if many: + class DynamicListSerializer(ListSerializer): + child = cls() + return DynamicListSerializer(*args, **kwargs) + return super(Serializer, cls).__new__(cls) + + def __init__(self, *args, **kwargs): + kwargs.pop('context', None) + kwargs.pop('partial', None) + kwargs.pop('many', False) + + super(Serializer, self).__init__(*args, **kwargs) + + # Every new serializer is created with a clone of the field instances. + # This allows users to dynamically modify the fields on a serializer + # instance without affecting every other serializer class. + self.fields = self.get_fields() + + # Setup all the child fields, to provide them with the current context. + for field_name, field in self.fields.items(): + field.bind(field_name, self, self) + + def get_fields(self): + return copy.deepcopy(self.base_fields) + + def bind(self, field_name, parent, root): + # If the serializer is used as a field then when it becomes bound + # it also needs to bind all its child fields. + super(Serializer, self).bind(field_name, parent, root) + for field_name, field in self.fields.items(): + field.bind(field_name, self, root) + + def get_initial(self): + return { + field.field_name: field.get_initial() + for field in self.fields.values() + } + + def get_value(self, dictionary): + # We override the default field access in order to support + # nested HTML forms. + if html.is_html_input(dictionary): + return html.parse_html_dict(dictionary, prefix=self.field_name) + return dictionary.get(self.field_name, empty) + + def to_native(self, data): + """ + Dict of native values <- Dict of primitive datatypes. + """ + ret = {} + errors = {} + fields = [field for field in self.fields.values() if not field.read_only] + + for field in fields: + primitive_value = field.get_value(data) + try: + validated_value = field.validate(primitive_value) + except ValidationError as exc: + errors[field.field_name] = str(exc) + except SkipField: + pass + else: + set_value(ret, field.source_attrs, validated_value) + + if errors: + raise ValidationError(errors) + + return ret + + def to_primative(self, instance): + """ + Object instance -> Dict of primitive datatypes. + """ + ret = OrderedDict() + fields = [field for field in self.fields.values() if not field.write_only] + + for field in fields: + native_value = field.get_attribute(instance) + ret[field.field_name] = field.to_primative(native_value) + + return ret + + def __iter__(self): + errors = self.errors if hasattr(self, '_errors') else {} + for field in self.fields.values(): + value = self.data.get(field.field_name) if self.data else None + error = errors.get(field.field_name) + yield FieldResult(field, value, error) + + +class ListSerializer(BaseSerializer): + child = None + initial = [] + + 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.' + + kwargs.pop('context', None) + kwargs.pop('partial', None) + + super(ListSerializer, self).__init__(*args, **kwargs) + self.child.bind('', self, self) + + def bind(self, field_name, parent, root): + # If the list is used as a field then it needs to provide + # the current context to the child serializer. + super(ListSerializer, self).bind(field_name, parent, root) + self.child.bind(field_name, self, root) + + def get_value(self, dictionary): + # We override the default field access in order to support + # lists in HTML forms. + if is_html_input(dictionary): + return html.parse_html_list(dictionary, prefix=self.field_name) + return dictionary.get(self.field_name, empty) + + def to_native(self, data): + """ + List of dicts of native values <- List of dicts of primitive datatypes. + """ + if html.is_html_input(data): + data = html.parse_html_list(data) + + return [self.child.validate(item) for item in data] + + def to_primative(self, data): + """ + List of object instances -> List of dicts of primitive datatypes. + """ + return [self.child.to_primative(item) for item in data] + + def create(self, attrs_list): + return [self.child.create(attrs) for attrs in attrs_list] + + def save(self): + if self.instance is not None: + self.update(self.instance, self.validated_data) + self.instance = self.create(self.validated_data) + return self.instance + + def _resolve_model(obj): """ Resolve supplied `obj` to a Django model class. @@ -58,614 +298,71 @@ def _resolve_model(obj): raise ValueError("{0} is not a Django model".format(obj)) -def pretty_name(name): - """Converts 'first_name' to 'First name'""" - if not name: - return '' - return name.replace('_', ' ').capitalize() - - -class RelationsList(list): - _deleted = [] - - -class NestedValidationError(ValidationError): - """ - The default ValidationError behavior is to stringify each item in the list - if the messages are a list of error messages. - - In the case of nested serializers, where the parent has many children, - then the child's `serializer.errors` will be a list of dicts. In the case - of a single child, the `serializer.errors` will be a dict. - - We need to override the default behavior to get properly nested error dicts. - """ - - def __init__(self, message): - if isinstance(message, dict): - self._messages = [message] - else: - self._messages = message - - @property - def messages(self): - return self._messages - - -class DictWithMetadata(dict): - """ - A dict-like object, that can have additional properties attached. - """ - def __getstate__(self): - """ - Used by pickle (e.g., caching). - Overridden to remove the metadata from the dict, since it shouldn't be - pickled and may in some instances be unpickleable. - """ - return dict(self) - - -class SortedDictWithMetadata(SortedDict): - """ - A sorted dict-like object, that can have additional properties attached. - """ - def __getstate__(self): - """ - Used by pickle (e.g., caching). - Overriden to remove the metadata from the dict, since it shouldn't be - pickle and may in some instances be unpickleable. - """ - return SortedDict(self).__dict__ - - -def _is_protected_type(obj): - """ - True if the object is a native datatype that does not need to - be serialized further. - """ - return isinstance(obj, ( - types.NoneType, - int, long, - datetime.datetime, datetime.date, datetime.time, - float, Decimal, - basestring) - ) - - -def _get_declared_fields(bases, attrs): - """ - Create a list of serializer field instances from the passed in 'attrs', - plus any fields on the base classes (in 'bases'). - - Note that all fields from the base classes are used. - """ - fields = [(field_name, attrs.pop(field_name)) - for field_name, obj in list(six.iteritems(attrs)) - if isinstance(obj, Field)] - fields.sort(key=lambda x: x[1].creation_counter) - - # If this class is subclassing another Serializer, add that Serializer's - # fields. Note that we loop over the bases in *reverse*. This is necessary - # in order to maintain the correct order of fields. - for base in bases[::-1]: - if hasattr(base, 'base_fields'): - fields = list(base.base_fields.items()) + fields - - return SortedDict(fields) - - -class SerializerMetaclass(type): - def __new__(cls, name, bases, attrs): - attrs['base_fields'] = _get_declared_fields(bases, attrs) - return super(SerializerMetaclass, cls).__new__(cls, name, bases, attrs) - - -class SerializerOptions(object): - """ - Meta class options for Serializer - """ - def __init__(self, meta): - self.depth = getattr(meta, 'depth', 0) - self.fields = getattr(meta, 'fields', ()) - self.exclude = getattr(meta, 'exclude', ()) - - -class BaseSerializer(WritableField): - """ - This is the Serializer implementation. - We need to implement it as `BaseSerializer` due to metaclass magicks. - """ - class Meta(object): - pass - - _options_class = SerializerOptions - _dict_class = SortedDictWithMetadata - - def __init__(self, instance=None, data=None, files=None, - context=None, partial=False, many=False, - allow_add_remove=False, **kwargs): - super(BaseSerializer, self).__init__(**kwargs) - self.opts = self._options_class(self.Meta) - self.parent = None - self.root = None - self.partial = partial - self.many = many - self.allow_add_remove = allow_add_remove - - self.context = context or {} - - self.init_data = data - self.init_files = files - self.object = instance - self.fields = self.get_fields() - - self._data = None - self._files = None - self._errors = None - - if many and instance is not None and not hasattr(instance, '__iter__'): - raise ValueError('instance should be a queryset or other iterable with many=True') - - if allow_add_remove and not many: - raise ValueError('allow_add_remove should only be used for bulk updates, but you have not set many=True') - - ##### - # Methods to determine which fields to use when (de)serializing objects. - - def get_default_fields(self): - """ - Return the complete set of default fields for the object, as a dict. - """ - return {} - - def get_fields(self): - """ - Returns the complete set of fields for the object as a dict. - - This will be the set of any explicitly declared fields, - plus the set of fields returned by get_default_fields(). - """ - ret = SortedDict() - - # Get the explicitly declared fields - base_fields = copy.deepcopy(self.base_fields) - for key, field in base_fields.items(): - ret[key] = field - - # Add in the default fields - default_fields = self.get_default_fields() - for key, val in default_fields.items(): - if key not in ret: - ret[key] = val - - # If 'fields' is specified, use those fields, in that order. - if self.opts.fields: - assert isinstance(self.opts.fields, (list, tuple)), '`fields` must be a list or tuple' - new = SortedDict() - for key in self.opts.fields: - new[key] = ret[key] - ret = new - - # Remove anything in 'exclude' - if self.opts.exclude: - assert isinstance(self.opts.exclude, (list, tuple)), '`exclude` must be a list or tuple' - for key in self.opts.exclude: - ret.pop(key, None) - - for key, field in ret.items(): - field.initialize(parent=self, field_name=key) - - return ret - - ##### - # Methods to convert or revert from objects <--> primitive representations. - - def get_field_key(self, field_name): - """ - Return the key that should be used for a given field. - """ - return field_name - - def restore_fields(self, data, files): - """ - Core of deserialization, together with `restore_object`. - Converts a dictionary of data into a dictionary of deserialized fields. - """ - reverted_data = {} - - if data is not None and not isinstance(data, dict): - self._errors['non_field_errors'] = ['Invalid data'] - return None - - for field_name, field in self.fields.items(): - field.initialize(parent=self, field_name=field_name) - try: - field.field_from_native(data, files, field_name, reverted_data) - except ValidationError as err: - self._errors[field_name] = list(err.messages) - - return reverted_data - - def perform_validation(self, attrs): - """ - Run `validate_()` and `validate()` methods on the serializer - """ - for field_name, field in self.fields.items(): - if field_name in self._errors: - continue - - source = field.source or field_name - if self.partial and source not in attrs: - continue - try: - validate_method = getattr(self, 'validate_%s' % field_name, None) - if validate_method: - attrs = validate_method(attrs, source) - except ValidationError as err: - self._errors[field_name] = self._errors.get(field_name, []) + list(err.messages) - - # If there are already errors, we don't run .validate() because - # field-validation failed and thus `attrs` may not be complete. - # which in turn can cause inconsistent validation errors. - if not self._errors: - try: - attrs = self.validate(attrs) - except ValidationError as err: - if hasattr(err, 'message_dict'): - for field_name, error_messages in err.message_dict.items(): - self._errors[field_name] = self._errors.get(field_name, []) + list(error_messages) - elif hasattr(err, 'messages'): - self._errors['non_field_errors'] = err.messages - - return attrs - - def validate(self, attrs): - """ - Stub method, to be overridden in Serializer subclasses - """ - return attrs - - def restore_object(self, attrs, instance=None): - """ - Deserialize a dictionary of attributes into an object instance. - You should override this method to control how deserialized objects - are instantiated. - """ - if instance is not None: - instance.update(attrs) - return instance - return attrs - - def to_native(self, obj): - """ - Serialize objects -> primitives. - """ - ret = self._dict_class() - ret.fields = self._dict_class() - - for field_name, field in self.fields.items(): - if field.read_only and obj is None: - continue - field.initialize(parent=self, field_name=field_name) - key = self.get_field_key(field_name) - value = field.field_to_native(obj, field_name) - method = getattr(self, 'transform_%s' % field_name, None) - if callable(method): - value = method(obj, value) - if not getattr(field, 'write_only', False): - ret[key] = value - ret.fields[key] = self.augment_field(field, field_name, key, value) - - return ret - - def from_native(self, data, files=None): - """ - Deserialize primitives -> objects. - """ - self._errors = {} - - if data is not None or files is not None: - attrs = self.restore_fields(data, files) - if attrs is not None: - attrs = self.perform_validation(attrs) - else: - self._errors['non_field_errors'] = ['No input provided'] - - if not self._errors: - return self.restore_object(attrs, instance=getattr(self, 'object', None)) - - def augment_field(self, field, field_name, key, value): - # This horrible stuff is to manage serializers rendering to HTML - field._errors = self._errors.get(key) if self._errors else None - field._name = field_name - field._value = self.init_data.get(key) if self._errors and self.init_data else value - if not field.label: - field.label = pretty_name(key) - return field - - def field_to_native(self, obj, field_name): - """ - Override default so that the serializer can be used as a nested field - across relationships. - """ - if self.write_only: - return None - - if self.source == '*': - return self.to_native(obj) - - # Get the raw field value - try: - source = self.source or field_name - value = obj - - for component in source.split('.'): - if value is None: - break - value = get_component(value, component) - except ObjectDoesNotExist: - return None - - if is_simple_callable(getattr(value, 'all', None)): - return [self.to_native(item) for item in value.all()] - - if value is None: - return None - - if self.many: - return [self.to_native(item) for item in value] - return self.to_native(value) - - def field_from_native(self, data, files, field_name, into): - """ - Override default so that the serializer can be used as a writable - nested field across relationships. - """ - if self.read_only: - return - - try: - value = data[field_name] - except KeyError: - if self.default is not None and not self.partial: - # Note: partial updates shouldn't set defaults - value = copy.deepcopy(self.default) - else: - if self.required: - raise ValidationError(self.error_messages['required']) - return - - if self.source == '*': - if value: - reverted_data = self.restore_fields(value, {}) - if not self._errors: - into.update(reverted_data) - else: - if value in (None, ''): - into[(self.source or field_name)] = None - else: - # Set the serializer object if it exists - obj = get_component(self.parent.object, self.source or field_name) if self.parent.object else None - - # If we have a model manager or similar object then we need - # to iterate through each instance. - if ( - self.many and - not hasattr(obj, '__iter__') and - is_simple_callable(getattr(obj, 'all', None)) - ): - obj = obj.all() - - kwargs = { - 'instance': obj, - 'data': value, - 'context': self.context, - 'partial': self.partial, - 'many': self.many, - 'allow_add_remove': self.allow_add_remove - } - serializer = self.__class__(**kwargs) - - if serializer.is_valid(): - into[self.source or field_name] = serializer.object - else: - # Propagate errors up to our parent - raise NestedValidationError(serializer.errors) - - def get_identity(self, data): - """ - This hook is required for bulk update. - It is used to determine the canonical identity of a given object. - - Note that the data has not been validated at this point, so we need - to make sure that we catch any cases of incorrect datatypes being - passed to this method. - """ - try: - return data.get('id', None) - except AttributeError: - return None - - @property - def errors(self): - """ - Run deserialization and return error data, - setting self.object if no errors occurred. - """ - if self._errors is None: - data, files = self.init_data, self.init_files - - if self.many is not None: - many = self.many - else: - many = hasattr(data, '__iter__') and not isinstance(data, (Page, dict, six.text_type)) - if many: - warnings.warn('Implicit list/queryset serialization is deprecated. ' - 'Use the `many=True` flag when instantiating the serializer.', - DeprecationWarning, stacklevel=3) - - if many: - ret = RelationsList() - errors = [] - update = self.object is not None - - if update: - # If this is a bulk update we need to map all the objects - # to a canonical identity so we can determine which - # individual object is being updated for each item in the - # incoming data - objects = self.object - identities = [self.get_identity(self.to_native(obj)) for obj in objects] - identity_to_objects = dict(zip(identities, objects)) - - if hasattr(data, '__iter__') and not isinstance(data, (dict, six.text_type)): - for item in data: - if update: - # Determine which object we're updating - identity = self.get_identity(item) - self.object = identity_to_objects.pop(identity, None) - if self.object is None and not self.allow_add_remove: - ret.append(None) - errors.append({'non_field_errors': ['Cannot create a new item, only existing items may be updated.']}) - continue - - ret.append(self.from_native(item, None)) - errors.append(self._errors) - - if update and self.allow_add_remove: - ret._deleted = identity_to_objects.values() - - self._errors = any(errors) and errors or [] - else: - self._errors = {'non_field_errors': ['Expected a list of items.']} - else: - ret = self.from_native(data, files) - - if not self._errors: - self.object = ret - - return self._errors - - def is_valid(self): - return not self.errors - - @property - def data(self): - """ - Returns the serialized data on the serializer. - """ - if self._data is None: - obj = self.object - - if self.many is not None: - many = self.many - else: - many = hasattr(obj, '__iter__') and not isinstance(obj, (Page, dict)) - if many: - warnings.warn('Implicit list/queryset serialization is deprecated. ' - 'Use the `many=True` flag when instantiating the serializer.', - DeprecationWarning, stacklevel=2) - - if many: - self._data = [self.to_native(item) for item in obj] - else: - self._data = self.to_native(obj) - - return self._data - - def save_object(self, obj, **kwargs): - obj.save(**kwargs) - - def delete_object(self, obj): - obj.delete() - - def save(self, **kwargs): - """ - Save the deserialized object and return it. - """ - # Clear cached _data, which may be invalidated by `save()` - self._data = None - - if isinstance(self.object, list): - [self.save_object(item, **kwargs) for item in self.object] - - if self.object._deleted: - [self.delete_object(item) for item in self.object._deleted] - else: - self.save_object(self.object, **kwargs) - - return self.object - - def metadata(self): - """ - Return a dictionary of metadata about the fields on the serializer. - Useful for things like responding to OPTIONS requests, or generating - API schemas for auto-documentation. - """ - return SortedDict( - [ - (field_name, field.metadata()) - for field_name, field in six.iteritems(self.fields) - ] - ) - - -class Serializer(six.with_metaclass(SerializerMetaclass, BaseSerializer)): - pass - - -class ModelSerializerOptions(SerializerOptions): +class ModelSerializerOptions(object): """ Meta class options for ModelSerializer """ def __init__(self, meta): - super(ModelSerializerOptions, self).__init__(meta) - self.model = getattr(meta, 'model', None) - self.read_only_fields = getattr(meta, 'read_only_fields', ()) - self.write_only_fields = getattr(meta, 'write_only_fields', ()) + self.model = getattr(meta, 'model') + self.fields = getattr(meta, 'fields', ()) + self.depth = getattr(meta, 'depth', 0) class ModelSerializer(Serializer): - """ - A serializer that deals with model instances and querysets. - """ - _options_class = ModelSerializerOptions - field_mapping = { models.AutoField: IntegerField, - models.FloatField: FloatField, + # models.FloatField: FloatField, models.IntegerField: IntegerField, models.PositiveIntegerField: IntegerField, models.SmallIntegerField: IntegerField, models.PositiveSmallIntegerField: IntegerField, - models.DateTimeField: DateTimeField, - models.DateField: DateField, - models.TimeField: TimeField, - models.DecimalField: DecimalField, - models.EmailField: EmailField, + # models.DateTimeField: DateTimeField, + # models.DateField: DateField, + # models.TimeField: TimeField, + # models.DecimalField: DecimalField, + # models.EmailField: EmailField, models.CharField: CharField, - models.URLField: URLField, - models.SlugField: SlugField, + # models.URLField: URLField, + # models.SlugField: SlugField, models.TextField: CharField, models.CommaSeparatedIntegerField: CharField, models.BooleanField: BooleanField, models.NullBooleanField: BooleanField, - models.FileField: FileField, - models.ImageField: ImageField, + # models.FileField: FileField, + # models.ImageField: ImageField, } + _options_class = ModelSerializerOptions + + def __init__(self, *args, **kwargs): + self.opts = self._options_class(self.Meta) + super(ModelSerializer, self).__init__(*args, **kwargs) + + def get_fields(self): + # Get the explicitly declared fields. + fields = copy.deepcopy(self.base_fields) + + # Add in the default fields. + for key, val in self.get_default_fields().items(): + if key not in fields: + fields[key] = val + + # If `fields` is set on the `Meta` class, + # then use only those fields, and in that order. + if self.opts.fields: + fields = OrderedDict([ + (key, fields[key]) for key in self.opts.fields + ]) + + return fields + def get_default_fields(self): """ Return all the fields that should be serialized for the model. """ - cls = self.opts.model - assert cls is not None, ( - "Serializer class '%s' is missing 'model' Meta option" % - self.__class__.__name__ - ) opts = cls._meta.concrete_model._meta - ret = SortedDict() + ret = OrderedDict() nested = bool(self.opts.depth) # Deal with adding the primary key field @@ -694,29 +391,9 @@ class ModelSerializer(Serializer): has_through_model = True if model_field.rel and nested: - if len(inspect.getargspec(self.get_nested_field).args) == 2: - warnings.warn( - 'The `get_nested_field(model_field)` call signature ' - 'is deprecated. ' - 'Use `get_nested_field(model_field, related_model, ' - 'to_many) instead', - DeprecationWarning - ) - field = self.get_nested_field(model_field) - else: - field = self.get_nested_field(model_field, related_model, to_many) + field = self.get_nested_field(model_field, related_model, to_many) elif model_field.rel: - if len(inspect.getargspec(self.get_nested_field).args) == 3: - warnings.warn( - 'The `get_related_field(model_field, to_many)` call ' - 'signature is deprecated. ' - 'Use `get_related_field(model_field, related_model, ' - 'to_many) instead', - DeprecationWarning - ) - field = self.get_related_field(model_field, to_many=to_many) - else: - field = self.get_related_field(model_field, related_model, to_many) + field = self.get_related_field(model_field, related_model, to_many) else: field = self.get_field(model_field) @@ -763,38 +440,6 @@ class ModelSerializer(Serializer): ret[accessor_name] = field - # Ensure that 'read_only_fields' is an iterable - assert isinstance(self.opts.read_only_fields, (list, tuple)), '`read_only_fields` must be a list or tuple' - - # Add the `read_only` flag to any fields that have been specified - # in the `read_only_fields` option - for field_name in self.opts.read_only_fields: - assert field_name not in self.base_fields.keys(), ( - "field '%s' on serializer '%s' specified in " - "`read_only_fields`, but also added " - "as an explicit field. Remove it from `read_only_fields`." % - (field_name, self.__class__.__name__)) - assert field_name in ret, ( - "Non-existant field '%s' specified in `read_only_fields` " - "on serializer '%s'." % - (field_name, self.__class__.__name__)) - ret[field_name].read_only = True - - # Ensure that 'write_only_fields' is an iterable - assert isinstance(self.opts.write_only_fields, (list, tuple)), '`write_only_fields` must be a list or tuple' - - for field_name in self.opts.write_only_fields: - assert field_name not in self.base_fields.keys(), ( - "field '%s' on serializer '%s' specified in " - "`write_only_fields`, but also added " - "as an explicit field. Remove it from `write_only_fields`." % - (field_name, self.__class__.__name__)) - assert field_name in ret, ( - "Non-existant field '%s' specified in `write_only_fields` " - "on serializer '%s'." % - (field_name, self.__class__.__name__)) - ret[field_name].write_only = True - return ret def get_pk_field(self, model_field): @@ -825,28 +470,24 @@ class ModelSerializer(Serializer): # TODO: filter queryset using: # .using(db).complex_filter(self.rel.limit_choices_to) - kwargs = { - 'queryset': related_model._default_manager, - 'many': to_many - } + kwargs = {} + # 'queryset': related_model._default_manager, + # 'many': to_many + # } if model_field: kwargs['required'] = not(model_field.null or model_field.blank) - if model_field.help_text is not None: - kwargs['help_text'] = model_field.help_text + # if model_field.help_text is not None: + # kwargs['help_text'] = model_field.help_text if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name - if not model_field.editable: kwargs['read_only'] = True - if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name - if model_field.help_text is not None: - kwargs['help_text'] = model_field.help_text - - return PrimaryKeyRelatedField(**kwargs) + return IntegerField(**kwargs) + # TODO: return PrimaryKeyRelatedField(**kwargs) def get_field(self, model_field): """ @@ -869,8 +510,8 @@ class ModelSerializer(Serializer): if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name - if model_field.help_text is not None: - kwargs['help_text'] = model_field.help_text + # if model_field.help_text is not None: + # kwargs['help_text'] = model_field.help_text # TODO: TypedChoiceField? if model_field.flatchoices: # This ModelField contains choices @@ -880,7 +521,7 @@ class ModelSerializer(Serializer): return ChoiceField(**kwargs) # put this below the ChoiceField because min_value isn't a valid initializer - if issubclass(model_field.__class__, models.PositiveIntegerField) or\ + if issubclass(model_field.__class__, models.PositiveIntegerField) or \ issubclass(model_field.__class__, models.PositiveSmallIntegerField): kwargs['min_value'] = 0 @@ -888,170 +529,27 @@ class ModelSerializer(Serializer): issubclass(model_field.__class__, (models.CharField, models.TextField)): kwargs['allow_none'] = True - attribute_dict = { - models.CharField: ['max_length'], - models.CommaSeparatedIntegerField: ['max_length'], - models.DecimalField: ['max_digits', 'decimal_places'], - models.EmailField: ['max_length'], - models.FileField: ['max_length'], - models.ImageField: ['max_length'], - models.SlugField: ['max_length'], - models.URLField: ['max_length'], - } + # attribute_dict = { + # models.CharField: ['max_length'], + # models.CommaSeparatedIntegerField: ['max_length'], + # models.DecimalField: ['max_digits', 'decimal_places'], + # models.EmailField: ['max_length'], + # models.FileField: ['max_length'], + # models.ImageField: ['max_length'], + # models.SlugField: ['max_length'], + # models.URLField: ['max_length'], + # } - if model_field.__class__ in attribute_dict: - attributes = attribute_dict[model_field.__class__] - for attribute in attributes: - kwargs.update({attribute: getattr(model_field, attribute)}) + # if model_field.__class__ in attribute_dict: + # attributes = attribute_dict[model_field.__class__] + # for attribute in attributes: + # kwargs.update({attribute: getattr(model_field, attribute)}) try: return self.field_mapping[model_field.__class__](**kwargs) except KeyError: - return ModelField(model_field=model_field, **kwargs) - - def get_validation_exclusions(self, instance=None): - """ - Return a list of field names to exclude from model validation. - """ - cls = self.opts.model - opts = cls._meta.concrete_model._meta - exclusions = [field.name for field in opts.fields + opts.many_to_many] - - for field_name, field in self.fields.items(): - field_name = field.source or field_name - if ( - field_name in exclusions - and not field.read_only - and (field.required or hasattr(instance, field_name)) - and not isinstance(field, Serializer) - ): - exclusions.remove(field_name) - return exclusions - - def full_clean(self, instance): - """ - Perform Django's full_clean, and populate the `errors` dictionary - if any validation errors occur. - - Note that we don't perform this inside the `.restore_object()` method, - so that subclasses can override `.restore_object()`, and still get - the full_clean validation checking. - """ - try: - instance.full_clean(exclude=self.get_validation_exclusions(instance)) - except ValidationError as err: - self._errors = err.message_dict - return None - return instance - - def restore_object(self, attrs, instance=None): - """ - Restore the model instance. - """ - m2m_data = {} - related_data = {} - nested_forward_relations = {} - meta = self.opts.model._meta - - # Reverse fk or one-to-one relations - for (obj, model) in meta.get_all_related_objects_with_model(): - field_name = obj.get_accessor_name() - if field_name in attrs: - related_data[field_name] = attrs.pop(field_name) - - # Reverse m2m relations - for (obj, model) in meta.get_all_related_m2m_objects_with_model(): - field_name = obj.get_accessor_name() - if field_name in attrs: - m2m_data[field_name] = attrs.pop(field_name) - - # Forward m2m relations - for field in meta.many_to_many + meta.virtual_fields: - if isinstance(field, GenericForeignKey): - continue - if field.name in attrs: - m2m_data[field.name] = attrs.pop(field.name) - - # Nested forward relations - These need to be marked so we can save - # them before saving the parent model instance. - for field_name in attrs.keys(): - if isinstance(self.fields.get(field_name, None), Serializer): - nested_forward_relations[field_name] = attrs[field_name] - - # Create an empty instance of the model - if instance is None: - instance = self.opts.model() - - for key, val in attrs.items(): - try: - setattr(instance, key, val) - except ValueError: - self._errors[key] = [self.error_messages['required']] - - # Any relations that cannot be set until we've - # saved the model get hidden away on these - # private attributes, so we can deal with them - # at the point of save. - instance._related_data = related_data - instance._m2m_data = m2m_data - instance._nested_forward_relations = nested_forward_relations - - return instance - - def from_native(self, data, files): - """ - Override the default method to also include model field validation. - """ - instance = super(ModelSerializer, self).from_native(data, files) - if not self._errors: - return self.full_clean(instance) - - def save_object(self, obj, **kwargs): - """ - Save the deserialized object. - """ - if getattr(obj, '_nested_forward_relations', None): - # Nested relationships need to be saved before we can save the - # parent instance. - for field_name, sub_object in obj._nested_forward_relations.items(): - if sub_object: - self.save_object(sub_object) - setattr(obj, field_name, sub_object) - - obj.save(**kwargs) - - if getattr(obj, '_m2m_data', None): - for accessor_name, object_list in obj._m2m_data.items(): - setattr(obj, accessor_name, object_list) - del(obj._m2m_data) - - if getattr(obj, '_related_data', None): - related_fields = dict([ - (field.get_accessor_name(), field) - for field, model - in obj._meta.get_all_related_objects_with_model() - ]) - for accessor_name, related in obj._related_data.items(): - if isinstance(related, RelationsList): - # Nested reverse fk relationship - for related_item in related: - fk_field = related_fields[accessor_name].field.name - setattr(related_item, fk_field, obj) - self.save_object(related_item) - - # Delete any removed objects - if related._deleted: - [self.delete_object(item) for item in related._deleted] - - elif isinstance(related, models.Model): - # Nested reverse one-one relationship - fk_field = obj._meta.get_field_by_name(accessor_name)[0].field.name - setattr(related, fk_field, obj) - self.save_object(related) - else: - # Reverse FK or reverse one-one - setattr(obj, accessor_name, related) - del(obj._related_data) + # TODO: Change this to `return ModelField(model_field=model_field, **kwargs)` + return CharField(**kwargs) class HyperlinkedModelSerializerOptions(ModelSerializerOptions): @@ -1066,14 +564,10 @@ class HyperlinkedModelSerializerOptions(ModelSerializerOptions): class HyperlinkedModelSerializer(ModelSerializer): - """ - A subclass of ModelSerializer that uses hyperlinked relationships, - instead of primary key relationships. - """ _options_class = HyperlinkedModelSerializerOptions _default_view_name = '%(model_name)s-detail' - _hyperlink_field_class = HyperlinkedRelatedField - _hyperlink_identify_field_class = HyperlinkedIdentityField + #_hyperlink_field_class = HyperlinkedRelatedField + #_hyperlink_identify_field_class = HyperlinkedIdentityField def get_default_fields(self): fields = super(HyperlinkedModelSerializer, self).get_default_fields() @@ -1081,15 +575,15 @@ class HyperlinkedModelSerializer(ModelSerializer): if self.opts.view_name is None: self.opts.view_name = self._get_default_view_name(self.opts.model) - if self.opts.url_field_name not in fields: - url_field = self._hyperlink_identify_field_class( - view_name=self.opts.view_name, - lookup_field=self.opts.lookup_field - ) - ret = self._dict_class() - ret[self.opts.url_field_name] = url_field - ret.update(fields) - fields = ret + # if self.opts.url_field_name not in fields: + # url_field = self._hyperlink_identify_field_class( + # view_name=self.opts.view_name, + # lookup_field=self.opts.lookup_field + # ) + # ret = self._dict_class() + # ret[self.opts.url_field_name] = url_field + # ret.update(fields) + # fields = ret return fields @@ -1103,33 +597,25 @@ class HyperlinkedModelSerializer(ModelSerializer): """ # TODO: filter queryset using: # .using(db).complex_filter(self.rel.limit_choices_to) - kwargs = { - 'queryset': related_model._default_manager, - 'view_name': self._get_default_view_name(related_model), - 'many': to_many - } + # kwargs = { + # 'queryset': related_model._default_manager, + # 'view_name': self._get_default_view_name(related_model), + # 'many': to_many + # } + kwargs = {} if model_field: kwargs['required'] = not(model_field.null or model_field.blank) - if model_field.help_text is not None: - kwargs['help_text'] = model_field.help_text + # if model_field.help_text is not None: + # kwargs['help_text'] = model_field.help_text if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name - if self.opts.lookup_field: - kwargs['lookup_field'] = self.opts.lookup_field + return IntegerField(**kwargs) + # if self.opts.lookup_field: + # kwargs['lookup_field'] = self.opts.lookup_field - return self._hyperlink_field_class(**kwargs) - - def get_identity(self, data): - """ - This hook is required for bulk update. - We need to override the default, to use the url as the identity. - """ - try: - return data.get(self.opts.url_field_name, None) - except AttributeError: - return None + # return self._hyperlink_field_class(**kwargs) def _get_default_view_name(self, model): """ diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py index 00ffdfbae..6a2f61266 100644 --- a/rest_framework/utils/encoders.py +++ b/rest_framework/utils/encoders.py @@ -7,7 +7,7 @@ from django.db.models.query import QuerySet from django.utils.datastructures import SortedDict from django.utils.functional import Promise from rest_framework.compat import force_text -from rest_framework.serializers import DictWithMetadata, SortedDictWithMetadata +# from rest_framework.serializers import DictWithMetadata, SortedDictWithMetadata import datetime import decimal import types @@ -106,14 +106,14 @@ else: SortedDict, yaml.representer.SafeRepresenter.represent_dict ) - SafeDumper.add_representer( - DictWithMetadata, - yaml.representer.SafeRepresenter.represent_dict - ) - SafeDumper.add_representer( - SortedDictWithMetadata, - yaml.representer.SafeRepresenter.represent_dict - ) + # SafeDumper.add_representer( + # DictWithMetadata, + # yaml.representer.SafeRepresenter.represent_dict + # ) + # SafeDumper.add_representer( + # SortedDictWithMetadata, + # yaml.representer.SafeRepresenter.represent_dict + # ) SafeDumper.add_representer( types.GeneratorType, yaml.representer.SafeRepresenter.represent_list diff --git a/rest_framework/utils/html.py b/rest_framework/utils/html.py new file mode 100644 index 000000000..bf17050df --- /dev/null +++ b/rest_framework/utils/html.py @@ -0,0 +1,86 @@ +""" +Helpers for dealing with HTML input. +""" + +def is_html_input(dictionary): + # MultiDict type datastructures are used to represent HTML form input, + # which may have more than one value for each key. + return hasattr(dictionary, 'getlist') + + +def parse_html_list(dictionary, prefix=''): + """ + Used to suport list values in HTML forms. + Supports lists of primitives and/or dictionaries. + + * List of primitives. + + { + '[0]': 'abc', + '[1]': 'def', + '[2]': 'hij' + } + --> + [ + 'abc', + 'def', + 'hij' + ] + + * List of dictionaries. + + { + '[0]foo': 'abc', + '[0]bar': 'def', + '[1]foo': 'hij', + '[2]bar': 'klm', + } + --> + [ + {'foo': 'abc', 'bar': 'def'}, + {'foo': 'hij', 'bar': 'klm'} + ] + """ + Dict = type(dictionary) + ret = {} + regex = re.compile(r'^%s\[([0-9]+)\](.*)$' % re.escape(prefix)) + for field, value in dictionary.items(): + match = regex.match(field) + if not match: + continue + index, key = match.groups() + index = int(index) + if not key: + ret[index] = value + elif isinstance(ret.get(index), dict): + ret[index][key] = value + else: + ret[index] = Dict({key: value}) + return [ret[item] for item in sorted(ret.keys())] + + +def parse_html_dict(dictionary, prefix): + """ + Used to support dictionary values in HTML forms. + + { + 'profile.username': 'example', + 'profile.email': 'example@example.com', + } + --> + { + 'profile': { + 'username': 'example, + 'email': 'example@example.com' + } + } + """ + ret = {} + regex = re.compile(r'^%s\.(.+)$' % re.escape(prefix)) + for field, value in dictionary.items(): + match = regex.match(field) + if not match: + continue + key = match.groups()[0] + ret[key] = value + return ret From ec096a1caceff6a4f5c75a152dd1c7bea9ed281d Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 2 Sep 2014 15:07:56 +0100 Subject: [PATCH 015/249] Add relations and get tests running --- rest_framework/fields.py | 30 +++++++-- rest_framework/mixins.py | 1 - rest_framework/relations.py | 111 ++++++++++++++++++++++++++++++++++ rest_framework/renderers.py | 14 ++--- rest_framework/serializers.py | 8 +-- rest_framework/utils/html.py | 2 + tests/test_serializer.py | 4 +- 7 files changed, 151 insertions(+), 19 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index a83bf94c4..3e0f7ca47 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -68,7 +68,7 @@ class Field(object): def __init__(self, read_only=False, write_only=False, required=None, default=empty, initial=None, source=None, - label=None, style=None): + label=None, style=None, error_messages=None): self._creation_counter = Field._creation_counter Field._creation_counter += 1 @@ -216,9 +216,11 @@ class CharField(Field): 'blank': 'This field may not be blank.' } - def __init__(self, *args, **kwargs): + def __init__(self, **kwargs): self.allow_blank = kwargs.pop('allow_blank', False) - super(CharField, self).__init__(*args, **kwargs) + self.max_length = kwargs.pop('max_length', None) + self.min_length = kwargs.pop('min_length', None) + super(CharField, self).__init__(**kwargs) def to_native(self, data): if data == '' and not self.allow_blank: @@ -233,7 +235,7 @@ class ChoiceField(Field): } coerce_to_type = str - def __init__(self, *args, **kwargs): + def __init__(self, **kwargs): choices = kwargs.pop('choices') assert choices, '`choices` argument is required and may not be empty' @@ -257,7 +259,7 @@ class ChoiceField(Field): str(key): key for key in self.choices.keys() } - super(ChoiceField, self).__init__(*args, **kwargs) + super(ChoiceField, self).__init__(**kwargs) def to_native(self, data): try: @@ -296,6 +298,24 @@ class IntegerField(Field): return data +class EmailField(CharField): + pass # TODO + + +class RegexField(CharField): + def __init__(self, **kwargs): + self.regex = kwargs.pop('regex') + super(CharField, self).__init__(**kwargs) + + +class DateTimeField(CharField): + pass # TODO + + +class FileField(Field): + pass # TODO + + class MethodField(Field): def __init__(self, **kwargs): kwargs['source'] = '*' diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index ee01cabc7..3e9c9bb33 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -6,7 +6,6 @@ which allows mixin classes to be composed in interesting ways. """ from __future__ import unicode_literals -from django.core.exceptions import ValidationError from django.http import Http404 from rest_framework import status from rest_framework.response import Response diff --git a/rest_framework/relations.py b/rest_framework/relations.py index e69de29bb..42d2c121a 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -0,0 +1,111 @@ +from rest_framework.fields import Field +from django.core.exceptions import ObjectDoesNotExist +from django.core.urlresolvers import resolve, get_script_prefix +from rest_framework.compat import urlparse + + +def get_default_queryset(serializer_class, field_name): + manager = getattr(serializer_class.opts.model, field_name) + if hasattr(manager, 'related'): + # Forward relationships + return manager.related.model._default_manager.all() + # Reverse relationships + return manager.field.rel.to._default_manager.all() + + +class RelatedField(Field): + def __init__(self, **kwargs): + self.queryset = kwargs.pop('queryset', None) + self.many = kwargs.pop('many', False) + super(RelatedField, self).__init__(**kwargs) + + def bind(self, field_name, parent, root): + super(RelatedField, self).bind(field_name, parent, root) + if self.queryset is None and not self.read_only: + self.queryset = get_default_queryset(parent, self.source) + + +class PrimaryKeyRelatedField(RelatedField): + MESSAGES = { + 'required': 'This field is required.', + 'does_not_exist': "Invalid pk '{pk_value}' - object does not exist.", + 'incorrect_type': 'Incorrect type. Expected pk value, received {data_type}.', + } + + def from_native(self, data): + try: + return self.queryset.get(pk=data) + except ObjectDoesNotExist: + self.fail('does_not_exist', pk_value=data) + except (TypeError, ValueError): + self.fail('incorrect_type', data_type=type(data).__name__) + + +class HyperlinkedRelatedField(RelatedField): + lookup_field = 'pk' + + MESSAGES = { + 'required': 'This field is required.', + 'no_match': 'Invalid hyperlink - No URL match', + 'incorrect_match': 'Invalid hyperlink - Incorrect URL match.', + 'does_not_exist': "Invalid hyperlink - Object does not exist.", + 'incorrect_type': 'Incorrect type. Expected URL string, received {data_type}.', + } + + def __init__(self, **kwargs): + self.view_name = kwargs.pop('view_name') + self.lookup_field = kwargs.pop('lookup_field', self.lookup_field) + self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field) + super(HyperlinkedRelatedField, self).__init__(**kwargs) + + def get_object(self, view_name, view_args, view_kwargs): + """ + Return the object corresponding to a matched URL. + + Takes the matched URL conf arguments, and should return an + object instance, or raise an `ObjectDoesNotExist` exception. + """ + lookup_value = view_kwargs[self.lookup_url_kwarg] + lookup_kwargs = {self.lookup_field: lookup_value} + return self.queryset.get(**lookup_kwargs) + + def from_native(self, value): + try: + http_prefix = value.startswith(('http:', 'https:')) + except AttributeError: + self.fail('incorrect_type', type(value).__name__) + + if http_prefix: + # If needed convert absolute URLs to relative path + value = urlparse.urlparse(value).path + prefix = get_script_prefix() + if value.startswith(prefix): + value = '/' + value[len(prefix):] + + try: + match = resolve(value) + except Exception: + self.fail('no_match') + + if match.view_name != self.view_name: + self.fail('incorrect_match') + + try: + return self.get_object(match.view_name, match.args, match.kwargs) + except (ObjectDoesNotExist, TypeError, ValueError): + self.fail('does_not_exist') + + +class HyperlinkedIdentityField(RelatedField): + lookup_field = 'pk' + + def __init__(self, **kwargs): + self.view_name = kwargs.pop('view_name') + self.lookup_field = kwargs.pop('lookup_field', self.lookup_field) + self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field) + super(HyperlinkedIdentityField, self).__init__(**kwargs) + + +class SlugRelatedField(RelatedField): + def __init__(self, **kwargs): + self.slug_field = kwargs.pop('slug_field', None) diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index e8935b012..dfc5a39f6 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -436,13 +436,13 @@ class BrowsableAPIRenderer(BaseRenderer): if request.method == method: try: data = request.DATA - files = request.FILES + # files = request.FILES except ParseError: data = None - files = None + # files = None else: data = None - files = None + # files = None with override_method(view, request, method) as request: obj = getattr(view, 'object', None) @@ -579,10 +579,10 @@ class BrowsableAPIRenderer(BaseRenderer): 'available_formats': [renderer_cls.format for renderer_cls in view.renderer_classes], 'response_headers': response_headers, - #'put_form': self.get_rendered_html_form(view, 'PUT', request), - #'post_form': self.get_rendered_html_form(view, 'POST', request), - #'delete_form': self.get_rendered_html_form(view, 'DELETE', request), - #'options_form': self.get_rendered_html_form(view, 'OPTIONS', request), + # 'put_form': self.get_rendered_html_form(view, 'PUT', request), + # 'post_form': self.get_rendered_html_form(view, 'POST', request), + # 'delete_form': self.get_rendered_html_form(view, 'DELETE', request), + # 'options_form': self.get_rendered_html_form(view, 'OPTIONS', request), 'raw_data_put_form': raw_data_put_form, 'raw_data_post_form': raw_data_post_form, diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index d121812d6..2f23b4d9a 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -477,8 +477,8 @@ class ModelSerializer(Serializer): if model_field: kwargs['required'] = not(model_field.null or model_field.blank) - # if model_field.help_text is not None: - # kwargs['help_text'] = model_field.help_text + # if model_field.help_text is not None: + # kwargs['help_text'] = model_field.help_text if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name if not model_field.editable: @@ -566,8 +566,8 @@ class HyperlinkedModelSerializerOptions(ModelSerializerOptions): class HyperlinkedModelSerializer(ModelSerializer): _options_class = HyperlinkedModelSerializerOptions _default_view_name = '%(model_name)s-detail' - #_hyperlink_field_class = HyperlinkedRelatedField - #_hyperlink_identify_field_class = HyperlinkedIdentityField + # _hyperlink_field_class = HyperlinkedRelatedField + # _hyperlink_identify_field_class = HyperlinkedIdentityField def get_default_fields(self): fields = super(HyperlinkedModelSerializer, self).get_default_fields() diff --git a/rest_framework/utils/html.py b/rest_framework/utils/html.py index bf17050df..edc591e9c 100644 --- a/rest_framework/utils/html.py +++ b/rest_framework/utils/html.py @@ -1,6 +1,8 @@ """ Helpers for dealing with HTML input. """ +import re + def is_html_input(dictionary): # MultiDict type datastructures are used to represent HTML form input, diff --git a/tests/test_serializer.py b/tests/test_serializer.py index 90f37cf2e..fa5cafcfb 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -1795,8 +1795,8 @@ class DefaultValuesOnAutogeneratedFieldsTests(TestCase): class MetadataSerializer(serializers.Serializer): - field1 = serializers.CharField(3, required=True) - field2 = serializers.CharField(10, required=False) + field1 = serializers.CharField(max_length=3, required=True) + field2 = serializers.CharField(max_length=10, required=False) class MetadataSerializerTestCase(TestCase): From f2852811f93863f2eed04d51eeb7ef27716b2409 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 2 Sep 2014 17:41:23 +0100 Subject: [PATCH 016/249] Getting tests passing --- rest_framework/authtoken/serializers.py | 5 +- rest_framework/authtoken/views.py | 3 +- rest_framework/fields.py | 50 +- rest_framework/mixins.py | 41 +- rest_framework/pagination.py | 34 +- rest_framework/relations.py | 2 +- rest_framework/serializers.py | 53 +- tests/test_fields.py | 1920 +++++++++++------------ tests/test_files.py | 150 +- tests/test_genericrelations.py | 244 +-- tests/test_generics.py | 356 +++-- tests/test_hyperlinkedserializers.py | 724 ++++----- tests/test_nullable_fields.py | 54 +- tests/test_pagination.py | 8 +- tests/test_permissions.py | 96 +- tests/test_relations.py | 234 +-- tests/test_relations_hyperlink.py | 1050 ++++++------- tests/test_relations_nested.py | 548 +++---- tests/test_relations_pk.py | 1102 ++++++------- tests/test_relations_slug.py | 444 +++--- 20 files changed, 3565 insertions(+), 3553 deletions(-) diff --git a/rest_framework/authtoken/serializers.py b/rest_framework/authtoken/serializers.py index 99e99ae3d..edeae857b 100644 --- a/rest_framework/authtoken/serializers.py +++ b/rest_framework/authtoken/serializers.py @@ -19,11 +19,12 @@ class AuthTokenSerializer(serializers.Serializer): if not user.is_active: msg = _('User account is disabled.') raise serializers.ValidationError(msg) - attrs['user'] = user - return attrs else: msg = _('Unable to login with provided credentials.') raise serializers.ValidationError(msg) else: msg = _('Must include "username" and "password"') raise serializers.ValidationError(msg) + + attrs['user'] = user + return attrs diff --git a/rest_framework/authtoken/views.py b/rest_framework/authtoken/views.py index 7c03cb766..94e6f061f 100644 --- a/rest_framework/authtoken/views.py +++ b/rest_framework/authtoken/views.py @@ -18,7 +18,8 @@ class ObtainAuthToken(APIView): def post(self, request): serializer = self.serializer_class(data=request.DATA) if serializer.is_valid(): - token, created = Token.objects.get_or_create(user=serializer.object['user']) + 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) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 3e0f7ca47..838aa3b0c 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1,4 +1,5 @@ from rest_framework.utils import html +import inspect class empty: @@ -11,6 +12,22 @@ class empty: pass +def is_simple_callable(obj): + """ + True if the object is a callable that takes no arguments. + """ + function = inspect.isfunction(obj) + method = inspect.ismethod(obj) + + if not (function or method): + return False + + args, _, _, defaults = inspect.getargspec(obj) + len_args = len(args) if function else len(args) - 1 + len_defaults = len(defaults) if defaults else 0 + return len_args <= len_defaults + + def get_attribute(instance, attrs): """ Similar to Python's built in `getattr(instance, attr)`, @@ -98,6 +115,7 @@ class Field(object): self.field_name = field_name self.parent = parent self.root = root + self.context = parent.context # `self.label` should deafult to being based on the field name. if self.label is None: @@ -297,25 +315,55 @@ class IntegerField(Field): self.fail('invalid_integer') return data + def to_primative(self, value): + if value is None: + return None + return int(value) + class EmailField(CharField): pass # TODO +class URLField(CharField): + pass # TODO + + class RegexField(CharField): def __init__(self, **kwargs): self.regex = kwargs.pop('regex') super(CharField, self).__init__(**kwargs) +class DateField(CharField): + def __init__(self, **kwargs): + self.input_formats = kwargs.pop('input_formats', None) + super(DateField, self).__init__(**kwargs) + + +class TimeField(CharField): + def __init__(self, **kwargs): + self.input_formats = kwargs.pop('input_formats', None) + super(TimeField, self).__init__(**kwargs) + + class DateTimeField(CharField): - pass # TODO + def __init__(self, **kwargs): + self.input_formats = kwargs.pop('input_formats', None) + super(DateTimeField, self).__init__(**kwargs) class FileField(Field): pass # TODO +class ReadOnlyField(Field): + def to_primative(self, value): + if is_simple_callable(value): + return value() + return value + + class MethodField(Field): def __init__(self, **kwargs): kwargs['source'] = '*' diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index 3e9c9bb33..359740cee 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -13,23 +13,6 @@ from rest_framework.request import clone_request from rest_framework.settings import api_settings -def _get_validation_exclusions(obj, lookup_field=None): - """ - Given a model instance, and an optional pk and slug field, - return the full list of all other field names on that model. - - For use when performing full_clean on a model instance, - so we only clean the required fields. - """ - if lookup_field == 'pk': - pk_field = obj._meta.pk - while pk_field.rel: - pk_field = pk_field.rel.to._meta.pk - lookup_field = pk_field.name - - return [field.name for field in obj._meta.fields if field.name != lookup_field] - - class CreateModelMixin(object): """ Create a model instance. @@ -92,15 +75,14 @@ class UpdateModelMixin(object): if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field - lookup_value = self.kwargs[lookup_url_kwarg] - extras = {self.lookup_field: lookup_value} - if self.object is None: + lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field + lookup_value = self.kwargs[lookup_url_kwarg] + extras = {self.lookup_field: lookup_value} self.object = serializer.save(extras=extras) return Response(serializer.data, status=status.HTTP_201_CREATED) - self.object = serializer.save(extras=extras) + self.object = serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) def partial_update(self, request, *args, **kwargs): @@ -122,21 +104,6 @@ class UpdateModelMixin(object): # return a 404 response. raise - def pre_save(self, obj): - """ - Set any attributes on the object that are implicit in the request. - """ - lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field - lookup_value = self.kwargs[lookup_url_kwarg] - - setattr(obj, self.lookup_field, lookup_value) - - # Ensure we clean the attributes so that we don't eg return integer - # pk using a string representation, as provided by the url conf kwarg. - if hasattr(obj, 'full_clean'): - exclude = _get_validation_exclusions(obj, self.lookup_field) - obj.full_clean(exclude) - class DestroyModelMixin(object): """ diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index 83ef97c5c..478d32b49 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -13,7 +13,7 @@ class NextPageField(serializers.Field): """ page_field = 'page' - def to_native(self, value): + def to_primative(self, value): if not value.has_next(): return None page = value.next_page_number() @@ -28,7 +28,7 @@ class PreviousPageField(serializers.Field): """ page_field = 'page' - def to_native(self, value): + def to_primative(self, value): if not value.has_previous(): return None page = value.previous_page_number() @@ -48,25 +48,11 @@ class DefaultObjectSerializer(serializers.Field): super(DefaultObjectSerializer, self).__init__(source=source) -# class PaginationSerializerOptions(serializers.SerializerOptions): -# """ -# An object that stores the options that may be provided to a -# pagination serializer by using the inner `Meta` class. - -# Accessible on the instance as `serializer.opts`. -# """ -# def __init__(self, meta): -# super(PaginationSerializerOptions, self).__init__(meta) -# self.object_serializer_class = getattr(meta, 'object_serializer_class', -# DefaultObjectSerializer) - - class BasePaginationSerializer(serializers.Serializer): """ A base class for pagination serializers to inherit from, to make implementing custom serializers more easy. """ - # _options_class = PaginationSerializerOptions results_field = 'results' def __init__(self, *args, **kwargs): @@ -75,14 +61,16 @@ class BasePaginationSerializer(serializers.Serializer): """ super(BasePaginationSerializer, self).__init__(*args, **kwargs) results_field = self.results_field - object_serializer = self.opts.object_serializer_class + try: + object_serializer = self.Meta.object_serializer_class + except AttributeError: + object_serializer = DefaultObjectSerializer - if 'context' in kwargs: - context_kwarg = {'context': kwargs['context']} - else: - context_kwarg = {} - - self.fields[results_field] = object_serializer(source='object_list', **context_kwarg) + self.fields[results_field] = serializers.ListSerializer( + child=object_serializer(), + source='object_list' + ) + self.fields[results_field].bind(results_field, self, self) # TODO: Support automatic binding class PaginationSerializer(BasePaginationSerializer): diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 42d2c121a..0b01394a8 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -73,7 +73,7 @@ class HyperlinkedRelatedField(RelatedField): try: http_prefix = value.startswith(('http:', 'https:')) except AttributeError: - self.fail('incorrect_type', type(value).__name__) + self.fail('incorrect_type', data_type=type(value).__name__) if http_prefix: # If needed convert absolute URLs to relative path diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 2f23b4d9a..c38d89682 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -142,7 +142,7 @@ class Serializer(BaseSerializer): return super(Serializer, cls).__new__(cls) def __init__(self, *args, **kwargs): - kwargs.pop('context', None) + self.context = kwargs.pop('context', {}) kwargs.pop('partial', None) kwargs.pop('many', False) @@ -202,7 +202,7 @@ class Serializer(BaseSerializer): if errors: raise ValidationError(errors) - return ret + return self.validate(ret) def to_primative(self, instance): """ @@ -217,6 +217,9 @@ class Serializer(BaseSerializer): return ret + def validate(self, attrs): + return attrs + def __iter__(self): errors = self.errors if hasattr(self, '_errors') else {} for field in self.fields.values(): @@ -232,8 +235,7 @@ class ListSerializer(BaseSerializer): 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.' - - kwargs.pop('context', None) + self.context = kwargs.pop('context', {}) kwargs.pop('partial', None) super(ListSerializer, self).__init__(*args, **kwargs) @@ -316,19 +318,19 @@ class ModelSerializer(Serializer): models.PositiveIntegerField: IntegerField, models.SmallIntegerField: IntegerField, models.PositiveSmallIntegerField: IntegerField, - # models.DateTimeField: DateTimeField, - # models.DateField: DateField, - # models.TimeField: TimeField, + models.DateTimeField: DateTimeField, + models.DateField: DateField, + models.TimeField: TimeField, # models.DecimalField: DecimalField, - # models.EmailField: EmailField, + models.EmailField: EmailField, models.CharField: CharField, - # models.URLField: URLField, + models.URLField: URLField, # models.SlugField: SlugField, models.TextField: CharField, models.CommaSeparatedIntegerField: CharField, models.BooleanField: BooleanField, models.NullBooleanField: BooleanField, - # models.FileField: FileField, + models.FileField: FileField, # models.ImageField: ImageField, } @@ -338,6 +340,15 @@ class ModelSerializer(Serializer): self.opts = self._options_class(self.Meta) super(ModelSerializer, self).__init__(*args, **kwargs) + def create(self): + ModelClass = self.opts.model + return ModelClass.objects.create(**self.validated_data) + + def update(self, obj): + for attr, value in self.validated_data.items(): + setattr(obj, attr, value) + obj.save() + def get_fields(self): # Get the explicitly declared fields. fields = copy.deepcopy(self.base_fields) @@ -566,8 +577,8 @@ class HyperlinkedModelSerializerOptions(ModelSerializerOptions): class HyperlinkedModelSerializer(ModelSerializer): _options_class = HyperlinkedModelSerializerOptions _default_view_name = '%(model_name)s-detail' - # _hyperlink_field_class = HyperlinkedRelatedField - # _hyperlink_identify_field_class = HyperlinkedIdentityField + _hyperlink_field_class = HyperlinkedRelatedField + _hyperlink_identify_field_class = HyperlinkedIdentityField def get_default_fields(self): fields = super(HyperlinkedModelSerializer, self).get_default_fields() @@ -575,15 +586,15 @@ class HyperlinkedModelSerializer(ModelSerializer): if self.opts.view_name is None: self.opts.view_name = self._get_default_view_name(self.opts.model) - # if self.opts.url_field_name not in fields: - # url_field = self._hyperlink_identify_field_class( - # view_name=self.opts.view_name, - # lookup_field=self.opts.lookup_field - # ) - # ret = self._dict_class() - # ret[self.opts.url_field_name] = url_field - # ret.update(fields) - # fields = ret + if self.opts.url_field_name not in fields: + url_field = self._hyperlink_identify_field_class( + view_name=self.opts.view_name, + lookup_field=self.opts.lookup_field + ) + ret = fields.__class__() + ret[self.opts.url_field_name] = url_field + ret.update(fields) + fields = ret return fields diff --git a/tests/test_fields.py b/tests/test_fields.py index 094ac1eb0..53c605382 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1,1022 +1,1022 @@ -""" -General serializer field tests. -""" -from __future__ import unicode_literals +# """ +# General serializer field tests. +# """ +# from __future__ import unicode_literals -import datetime -import re -from decimal import Decimal -from uuid import uuid4 -from django.core import validators -from django.db import models -from django.test import TestCase -from django.utils.datastructures import SortedDict -from rest_framework import serializers -from tests.models import RESTFrameworkModel +# import datetime +# import re +# from decimal import Decimal +# from uuid import uuid4 +# from django.core import validators +# from django.db import models +# from django.test import TestCase +# from django.utils.datastructures import SortedDict +# from rest_framework import serializers +# from tests.models import RESTFrameworkModel -class TimestampedModel(models.Model): - added = models.DateTimeField(auto_now_add=True) - updated = models.DateTimeField(auto_now=True) +# class TimestampedModel(models.Model): +# added = models.DateTimeField(auto_now_add=True) +# updated = models.DateTimeField(auto_now=True) -class CharPrimaryKeyModel(models.Model): - id = models.CharField(max_length=20, primary_key=True) +# class CharPrimaryKeyModel(models.Model): +# id = models.CharField(max_length=20, primary_key=True) -class TimestampedModelSerializer(serializers.ModelSerializer): - class Meta: - model = TimestampedModel +# class TimestampedModelSerializer(serializers.ModelSerializer): +# class Meta: +# model = TimestampedModel -class CharPrimaryKeyModelSerializer(serializers.ModelSerializer): - class Meta: - model = CharPrimaryKeyModel +# class CharPrimaryKeyModelSerializer(serializers.ModelSerializer): +# class Meta: +# model = CharPrimaryKeyModel -class TimeFieldModel(models.Model): - clock = models.TimeField() +# class TimeFieldModel(models.Model): +# clock = models.TimeField() -class TimeFieldModelSerializer(serializers.ModelSerializer): - class Meta: - model = TimeFieldModel +# class TimeFieldModelSerializer(serializers.ModelSerializer): +# class Meta: +# model = TimeFieldModel -SAMPLE_CHOICES = [ - ('red', 'Red'), - ('green', 'Green'), - ('blue', 'Blue'), -] +# SAMPLE_CHOICES = [ +# ('red', 'Red'), +# ('green', 'Green'), +# ('blue', 'Blue'), +# ] -class ChoiceFieldModel(models.Model): - choice = models.CharField(choices=SAMPLE_CHOICES, blank=True, max_length=255) +# class ChoiceFieldModel(models.Model): +# choice = models.CharField(choices=SAMPLE_CHOICES, blank=True, max_length=255) -class ChoiceFieldModelSerializer(serializers.ModelSerializer): - class Meta: - model = ChoiceFieldModel - - -class ChoiceFieldModelWithNull(models.Model): - choice = models.CharField(choices=SAMPLE_CHOICES, blank=True, null=True, max_length=255) - - -class ChoiceFieldModelWithNullSerializer(serializers.ModelSerializer): - class Meta: - model = ChoiceFieldModelWithNull - - -class BasicFieldTests(TestCase): - def test_auto_now_fields_read_only(self): - """ - auto_now and auto_now_add fields should be read_only by default. - """ - serializer = TimestampedModelSerializer() - self.assertEqual(serializer.fields['added'].read_only, True) - - def test_auto_pk_fields_read_only(self): - """ - AutoField fields should be read_only by default. - """ - serializer = TimestampedModelSerializer() - self.assertEqual(serializer.fields['id'].read_only, True) - - def test_non_auto_pk_fields_not_read_only(self): - """ - PK fields other than AutoField fields should not be read_only by default. - """ - serializer = CharPrimaryKeyModelSerializer() - self.assertEqual(serializer.fields['id'].read_only, False) - - def test_dict_field_ordering(self): - """ - Field should preserve dictionary ordering, if it exists. - See: https://github.com/tomchristie/django-rest-framework/issues/832 - """ - ret = SortedDict() - ret['c'] = 1 - ret['b'] = 1 - ret['a'] = 1 - ret['z'] = 1 - field = serializers.Field() - keys = list(field.to_native(ret).keys()) - self.assertEqual(keys, ['c', 'b', 'a', 'z']) - - def test_widget_html_attributes(self): - """ - Make sure widget_html() renders the correct attributes - """ - r = re.compile('(\S+)=["\']?((?:.(?!["\']?\s+(?:\S+)=|[>"\']))+.)["\']?') - form = TimeFieldModelSerializer().data - attributes = r.findall(form.fields['clock'].widget_html()) - self.assertIn(('name', 'clock'), attributes) - self.assertIn(('id', 'clock'), attributes) +# class ChoiceFieldModelSerializer(serializers.ModelSerializer): +# class Meta: +# model = ChoiceFieldModel + + +# class ChoiceFieldModelWithNull(models.Model): +# choice = models.CharField(choices=SAMPLE_CHOICES, blank=True, null=True, max_length=255) + + +# class ChoiceFieldModelWithNullSerializer(serializers.ModelSerializer): +# class Meta: +# model = ChoiceFieldModelWithNull + + +# class BasicFieldTests(TestCase): +# def test_auto_now_fields_read_only(self): +# """ +# auto_now and auto_now_add fields should be read_only by default. +# """ +# serializer = TimestampedModelSerializer() +# self.assertEqual(serializer.fields['added'].read_only, True) + +# def test_auto_pk_fields_read_only(self): +# """ +# AutoField fields should be read_only by default. +# """ +# serializer = TimestampedModelSerializer() +# self.assertEqual(serializer.fields['id'].read_only, True) + +# def test_non_auto_pk_fields_not_read_only(self): +# """ +# PK fields other than AutoField fields should not be read_only by default. +# """ +# serializer = CharPrimaryKeyModelSerializer() +# self.assertEqual(serializer.fields['id'].read_only, False) + +# def test_dict_field_ordering(self): +# """ +# Field should preserve dictionary ordering, if it exists. +# See: https://github.com/tomchristie/django-rest-framework/issues/832 +# """ +# ret = SortedDict() +# ret['c'] = 1 +# ret['b'] = 1 +# ret['a'] = 1 +# ret['z'] = 1 +# field = serializers.Field() +# keys = list(field.to_native(ret).keys()) +# self.assertEqual(keys, ['c', 'b', 'a', 'z']) + +# def test_widget_html_attributes(self): +# """ +# Make sure widget_html() renders the correct attributes +# """ +# r = re.compile('(\S+)=["\']?((?:.(?!["\']?\s+(?:\S+)=|[>"\']))+.)["\']?') +# form = TimeFieldModelSerializer().data +# attributes = r.findall(form.fields['clock'].widget_html()) +# self.assertIn(('name', 'clock'), attributes) +# self.assertIn(('id', 'clock'), attributes) -class DateFieldTest(TestCase): - """ - Tests for the DateFieldTest from_native() and to_native() behavior - """ - - def test_from_native_string(self): - """ - Make sure from_native() accepts default iso input formats. - """ - f = serializers.DateField() - result_1 = f.from_native('1984-07-31') - - self.assertEqual(datetime.date(1984, 7, 31), result_1) - - def test_from_native_datetime_date(self): - """ - Make sure from_native() accepts a datetime.date instance. - """ - f = serializers.DateField() - result_1 = f.from_native(datetime.date(1984, 7, 31)) - - self.assertEqual(result_1, datetime.date(1984, 7, 31)) - - def test_from_native_custom_format(self): - """ - Make sure from_native() accepts custom input formats. - """ - f = serializers.DateField(input_formats=['%Y -- %d']) - result = f.from_native('1984 -- 31') - - self.assertEqual(datetime.date(1984, 1, 31), result) - - def test_from_native_invalid_default_on_custom_format(self): - """ - Make sure from_native() don't accept default formats if custom format is preset - """ - f = serializers.DateField(input_formats=['%Y -- %d']) - - try: - f.from_native('1984-07-31') - except validators.ValidationError as e: - self.assertEqual(e.messages, ["Date has wrong format. Use one of these formats instead: YYYY -- DD"]) - else: - self.fail("ValidationError was not properly raised") - - def test_from_native_empty(self): - """ - Make sure from_native() returns None on empty param. - """ - f = serializers.DateField() - result = f.from_native('') - - self.assertEqual(result, None) - - def test_from_native_none(self): - """ - Make sure from_native() returns None on None param. - """ - f = serializers.DateField() - result = f.from_native(None) - - self.assertEqual(result, None) - - def test_from_native_invalid_date(self): - """ - Make sure from_native() raises a ValidationError on passing an invalid date. - """ - f = serializers.DateField() - - try: - f.from_native('1984-13-31') - except validators.ValidationError as e: - self.assertEqual(e.messages, ["Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]"]) - else: - self.fail("ValidationError was not properly raised") - - def test_from_native_invalid_format(self): - """ - Make sure from_native() raises a ValidationError on passing an invalid format. - """ - f = serializers.DateField() - - try: - f.from_native('1984 -- 31') - except validators.ValidationError as e: - self.assertEqual(e.messages, ["Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]"]) - else: - self.fail("ValidationError was not properly raised") - - def test_to_native(self): - """ - Make sure to_native() returns datetime as default. - """ - f = serializers.DateField() - - result_1 = f.to_native(datetime.date(1984, 7, 31)) - - self.assertEqual(datetime.date(1984, 7, 31), result_1) - - def test_to_native_iso(self): - """ - Make sure to_native() with 'iso-8601' returns iso formated date. - """ - f = serializers.DateField(format='iso-8601') - - result_1 = f.to_native(datetime.date(1984, 7, 31)) - - self.assertEqual('1984-07-31', result_1) - - def test_to_native_custom_format(self): - """ - Make sure to_native() returns correct custom format. - """ - f = serializers.DateField(format="%Y - %m.%d") - - result_1 = f.to_native(datetime.date(1984, 7, 31)) - - self.assertEqual('1984 - 07.31', result_1) - - def test_to_native_none(self): - """ - Make sure from_native() returns None on None param. - """ - f = serializers.DateField(required=False) - self.assertEqual(None, f.to_native(None)) - - -class DateTimeFieldTest(TestCase): - """ - Tests for the DateTimeField from_native() and to_native() behavior - """ - - def test_from_native_string(self): - """ - Make sure from_native() accepts default iso input formats. - """ - f = serializers.DateTimeField() - result_1 = f.from_native('1984-07-31 04:31') - result_2 = f.from_native('1984-07-31 04:31:59') - result_3 = f.from_native('1984-07-31 04:31:59.000200') - - self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31), result_1) - self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59), result_2) - self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59, 200), result_3) - - def test_from_native_datetime_datetime(self): - """ - Make sure from_native() accepts a datetime.datetime instance. - """ - f = serializers.DateTimeField() - result_1 = f.from_native(datetime.datetime(1984, 7, 31, 4, 31)) - result_2 = f.from_native(datetime.datetime(1984, 7, 31, 4, 31, 59)) - result_3 = f.from_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) - - self.assertEqual(result_1, datetime.datetime(1984, 7, 31, 4, 31)) - self.assertEqual(result_2, datetime.datetime(1984, 7, 31, 4, 31, 59)) - self.assertEqual(result_3, datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) - - def test_from_native_custom_format(self): - """ - Make sure from_native() accepts custom input formats. - """ - f = serializers.DateTimeField(input_formats=['%Y -- %H:%M']) - result = f.from_native('1984 -- 04:59') - - self.assertEqual(datetime.datetime(1984, 1, 1, 4, 59), result) - - def test_from_native_invalid_default_on_custom_format(self): - """ - Make sure from_native() don't accept default formats if custom format is preset - """ - f = serializers.DateTimeField(input_formats=['%Y -- %H:%M']) - - try: - f.from_native('1984-07-31 04:31:59') - except validators.ValidationError as e: - self.assertEqual(e.messages, ["Datetime has wrong format. Use one of these formats instead: YYYY -- hh:mm"]) - else: - self.fail("ValidationError was not properly raised") - - def test_from_native_empty(self): - """ - Make sure from_native() returns None on empty param. - """ - f = serializers.DateTimeField() - result = f.from_native('') - - self.assertEqual(result, None) - - def test_from_native_none(self): - """ - Make sure from_native() returns None on None param. - """ - f = serializers.DateTimeField() - result = f.from_native(None) - - self.assertEqual(result, None) - - def test_from_native_invalid_datetime(self): - """ - Make sure from_native() raises a ValidationError on passing an invalid datetime. - """ - f = serializers.DateTimeField() - - try: - f.from_native('04:61:59') - except validators.ValidationError as e: - self.assertEqual(e.messages, ["Datetime has wrong format. Use one of these formats instead: " - "YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]"]) - else: - self.fail("ValidationError was not properly raised") - - def test_from_native_invalid_format(self): - """ - Make sure from_native() raises a ValidationError on passing an invalid format. - """ - f = serializers.DateTimeField() - - try: - f.from_native('04 -- 31') - except validators.ValidationError as e: - self.assertEqual(e.messages, ["Datetime has wrong format. Use one of these formats instead: " - "YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]"]) - else: - self.fail("ValidationError was not properly raised") - - def test_to_native(self): - """ - Make sure to_native() returns isoformat as default. - """ - f = serializers.DateTimeField() - - result_1 = f.to_native(datetime.datetime(1984, 7, 31)) - result_2 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31)) - result_3 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59)) - result_4 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) - - self.assertEqual(datetime.datetime(1984, 7, 31), result_1) - self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31), result_2) - self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59), result_3) - self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59, 200), result_4) - - def test_to_native_iso(self): - """ - Make sure to_native() with format=iso-8601 returns iso formatted datetime. - """ - f = serializers.DateTimeField(format='iso-8601') - - result_1 = f.to_native(datetime.datetime(1984, 7, 31)) - result_2 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31)) - result_3 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59)) - result_4 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) - - self.assertEqual('1984-07-31T00:00:00', result_1) - self.assertEqual('1984-07-31T04:31:00', result_2) - self.assertEqual('1984-07-31T04:31:59', result_3) - self.assertEqual('1984-07-31T04:31:59.000200', result_4) - - def test_to_native_custom_format(self): - """ - Make sure to_native() returns correct custom format. - """ - f = serializers.DateTimeField(format="%Y - %H:%M") - - result_1 = f.to_native(datetime.datetime(1984, 7, 31)) - result_2 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31)) - result_3 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59)) - result_4 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) - - self.assertEqual('1984 - 00:00', result_1) - self.assertEqual('1984 - 04:31', result_2) - self.assertEqual('1984 - 04:31', result_3) - self.assertEqual('1984 - 04:31', result_4) - - def test_to_native_none(self): - """ - Make sure from_native() returns None on None param. - """ - f = serializers.DateTimeField(required=False) - self.assertEqual(None, f.to_native(None)) - - -class TimeFieldTest(TestCase): - """ - Tests for the TimeField from_native() and to_native() behavior - """ - - def test_from_native_string(self): - """ - Make sure from_native() accepts default iso input formats. - """ - f = serializers.TimeField() - result_1 = f.from_native('04:31') - result_2 = f.from_native('04:31:59') - result_3 = f.from_native('04:31:59.000200') - - self.assertEqual(datetime.time(4, 31), result_1) - self.assertEqual(datetime.time(4, 31, 59), result_2) - self.assertEqual(datetime.time(4, 31, 59, 200), result_3) - - def test_from_native_datetime_time(self): - """ - Make sure from_native() accepts a datetime.time instance. - """ - f = serializers.TimeField() - result_1 = f.from_native(datetime.time(4, 31)) - result_2 = f.from_native(datetime.time(4, 31, 59)) - result_3 = f.from_native(datetime.time(4, 31, 59, 200)) - - self.assertEqual(result_1, datetime.time(4, 31)) - self.assertEqual(result_2, datetime.time(4, 31, 59)) - self.assertEqual(result_3, datetime.time(4, 31, 59, 200)) - - def test_from_native_custom_format(self): - """ - Make sure from_native() accepts custom input formats. - """ - f = serializers.TimeField(input_formats=['%H -- %M']) - result = f.from_native('04 -- 31') - - self.assertEqual(datetime.time(4, 31), result) - - def test_from_native_invalid_default_on_custom_format(self): - """ - Make sure from_native() don't accept default formats if custom format is preset - """ - f = serializers.TimeField(input_formats=['%H -- %M']) - - try: - f.from_native('04:31:59') - except validators.ValidationError as e: - self.assertEqual(e.messages, ["Time has wrong format. Use one of these formats instead: hh -- mm"]) - else: - self.fail("ValidationError was not properly raised") - - def test_from_native_empty(self): - """ - Make sure from_native() returns None on empty param. - """ - f = serializers.TimeField() - result = f.from_native('') - - self.assertEqual(result, None) - - def test_from_native_none(self): - """ - Make sure from_native() returns None on None param. - """ - f = serializers.TimeField() - result = f.from_native(None) - - self.assertEqual(result, None) - - def test_from_native_invalid_time(self): - """ - Make sure from_native() raises a ValidationError on passing an invalid time. - """ - f = serializers.TimeField() - - try: - f.from_native('04:61:59') - except validators.ValidationError as e: - self.assertEqual(e.messages, ["Time has wrong format. Use one of these formats instead: " - "hh:mm[:ss[.uuuuuu]]"]) - else: - self.fail("ValidationError was not properly raised") - - def test_from_native_invalid_format(self): - """ - Make sure from_native() raises a ValidationError on passing an invalid format. - """ - f = serializers.TimeField() - - try: - f.from_native('04 -- 31') - except validators.ValidationError as e: - self.assertEqual(e.messages, ["Time has wrong format. Use one of these formats instead: " - "hh:mm[:ss[.uuuuuu]]"]) - else: - self.fail("ValidationError was not properly raised") - - def test_to_native(self): - """ - Make sure to_native() returns time object as default. - """ - f = serializers.TimeField() - result_1 = f.to_native(datetime.time(4, 31)) - result_2 = f.to_native(datetime.time(4, 31, 59)) - result_3 = f.to_native(datetime.time(4, 31, 59, 200)) - - self.assertEqual(datetime.time(4, 31), result_1) - self.assertEqual(datetime.time(4, 31, 59), result_2) - self.assertEqual(datetime.time(4, 31, 59, 200), result_3) - - def test_to_native_iso(self): - """ - Make sure to_native() with format='iso-8601' returns iso formatted time. - """ - f = serializers.TimeField(format='iso-8601') - result_1 = f.to_native(datetime.time(4, 31)) - result_2 = f.to_native(datetime.time(4, 31, 59)) - result_3 = f.to_native(datetime.time(4, 31, 59, 200)) - - self.assertEqual('04:31:00', result_1) - self.assertEqual('04:31:59', result_2) - self.assertEqual('04:31:59.000200', result_3) - - def test_to_native_custom_format(self): - """ - Make sure to_native() returns correct custom format. - """ - f = serializers.TimeField(format="%H - %S [%f]") - result_1 = f.to_native(datetime.time(4, 31)) - result_2 = f.to_native(datetime.time(4, 31, 59)) - result_3 = f.to_native(datetime.time(4, 31, 59, 200)) - - self.assertEqual('04 - 00 [000000]', result_1) - self.assertEqual('04 - 59 [000000]', result_2) - self.assertEqual('04 - 59 [000200]', result_3) - - -class DecimalFieldTest(TestCase): - """ - Tests for the DecimalField from_native() and to_native() behavior - """ - - def test_from_native_string(self): - """ - Make sure from_native() accepts string values - """ - f = serializers.DecimalField() - result_1 = f.from_native('9000') - result_2 = f.from_native('1.00000001') - - self.assertEqual(Decimal('9000'), result_1) - self.assertEqual(Decimal('1.00000001'), result_2) - - def test_from_native_invalid_string(self): - """ - Make sure from_native() raises ValidationError on passing invalid string - """ - f = serializers.DecimalField() - - try: - f.from_native('123.45.6') - except validators.ValidationError as e: - self.assertEqual(e.messages, ["Enter a number."]) - else: - self.fail("ValidationError was not properly raised") - - def test_from_native_integer(self): - """ - Make sure from_native() accepts integer values - """ - f = serializers.DecimalField() - result = f.from_native(9000) - - self.assertEqual(Decimal('9000'), result) - - def test_from_native_float(self): - """ - Make sure from_native() accepts float values - """ - f = serializers.DecimalField() - result = f.from_native(1.00000001) - - self.assertEqual(Decimal('1.00000001'), result) - - def test_from_native_empty(self): - """ - Make sure from_native() returns None on empty param. - """ - f = serializers.DecimalField() - result = f.from_native('') - - self.assertEqual(result, None) - - def test_from_native_none(self): - """ - Make sure from_native() returns None on None param. - """ - f = serializers.DecimalField() - result = f.from_native(None) - - self.assertEqual(result, None) - - def test_to_native(self): - """ - Make sure to_native() returns Decimal as string. - """ - f = serializers.DecimalField() - - result_1 = f.to_native(Decimal('9000')) - result_2 = f.to_native(Decimal('1.00000001')) - - self.assertEqual(Decimal('9000'), result_1) - self.assertEqual(Decimal('1.00000001'), result_2) - - def test_to_native_none(self): - """ - Make sure from_native() returns None on None param. - """ - f = serializers.DecimalField(required=False) - self.assertEqual(None, f.to_native(None)) - - def test_valid_serialization(self): - """ - Make sure the serializer works correctly - """ - class DecimalSerializer(serializers.Serializer): - decimal_field = serializers.DecimalField(max_value=9010, - min_value=9000, - max_digits=6, - decimal_places=2) - - self.assertTrue(DecimalSerializer(data={'decimal_field': '9001'}).is_valid()) - self.assertTrue(DecimalSerializer(data={'decimal_field': '9001.2'}).is_valid()) - self.assertTrue(DecimalSerializer(data={'decimal_field': '9001.23'}).is_valid()) - - self.assertFalse(DecimalSerializer(data={'decimal_field': '8000'}).is_valid()) - self.assertFalse(DecimalSerializer(data={'decimal_field': '9900'}).is_valid()) - self.assertFalse(DecimalSerializer(data={'decimal_field': '9001.234'}).is_valid()) - - def test_raise_max_value(self): - """ - Make sure max_value violations raises ValidationError - """ - class DecimalSerializer(serializers.Serializer): - decimal_field = serializers.DecimalField(max_value=100) - - s = DecimalSerializer(data={'decimal_field': '123'}) - - self.assertFalse(s.is_valid()) - self.assertEqual(s.errors, {'decimal_field': ['Ensure this value is less than or equal to 100.']}) - - def test_raise_min_value(self): - """ - Make sure min_value violations raises ValidationError - """ - class DecimalSerializer(serializers.Serializer): - decimal_field = serializers.DecimalField(min_value=100) - - s = DecimalSerializer(data={'decimal_field': '99'}) - - self.assertFalse(s.is_valid()) - self.assertEqual(s.errors, {'decimal_field': ['Ensure this value is greater than or equal to 100.']}) - - def test_raise_max_digits(self): - """ - Make sure max_digits violations raises ValidationError - """ - class DecimalSerializer(serializers.Serializer): - decimal_field = serializers.DecimalField(max_digits=5) - - s = DecimalSerializer(data={'decimal_field': '123.456'}) - - self.assertFalse(s.is_valid()) - self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 5 digits in total.']}) - - def test_raise_max_decimal_places(self): - """ - Make sure max_decimal_places violations raises ValidationError - """ - class DecimalSerializer(serializers.Serializer): - decimal_field = serializers.DecimalField(decimal_places=3) - - s = DecimalSerializer(data={'decimal_field': '123.4567'}) - - self.assertFalse(s.is_valid()) - self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 3 decimal places.']}) - - def test_raise_max_whole_digits(self): - """ - Make sure max_whole_digits violations raises ValidationError - """ - class DecimalSerializer(serializers.Serializer): - decimal_field = serializers.DecimalField(max_digits=4, decimal_places=3) - - s = DecimalSerializer(data={'decimal_field': '12345.6'}) - - self.assertFalse(s.is_valid()) - self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 4 digits in total.']}) - - -class ChoiceFieldTests(TestCase): - """ - Tests for the ChoiceField options generator - """ - def test_choices_required(self): - """ - Make sure proper choices are rendered if field is required - """ - f = serializers.ChoiceField(required=True, choices=SAMPLE_CHOICES) - self.assertEqual(f.choices, SAMPLE_CHOICES) - - def test_choices_not_required(self): - """ - Make sure proper choices (plus blank) are rendered if the field isn't required - """ - f = serializers.ChoiceField(required=False, choices=SAMPLE_CHOICES) - self.assertEqual(f.choices, models.fields.BLANK_CHOICE_DASH + SAMPLE_CHOICES) - - def test_blank_choice_display(self): - blank = 'No Preference' - f = serializers.ChoiceField( - required=False, - choices=SAMPLE_CHOICES, - blank_display_value=blank, - ) - self.assertEqual(f.choices, [('', blank)] + SAMPLE_CHOICES) - - def test_invalid_choice_model(self): - s = ChoiceFieldModelSerializer(data={'choice': 'wrong_value'}) - self.assertFalse(s.is_valid()) - self.assertEqual(s.errors, {'choice': ['Select a valid choice. wrong_value is not one of the available choices.']}) - self.assertEqual(s.data['choice'], '') - - def test_empty_choice_model(self): - """ - Test that the 'empty' value is correctly passed and used depending on - the 'null' property on the model field. - """ - s = ChoiceFieldModelSerializer(data={'choice': ''}) - self.assertTrue(s.is_valid()) - self.assertEqual(s.data['choice'], '') - - s = ChoiceFieldModelWithNullSerializer(data={'choice': ''}) - self.assertTrue(s.is_valid()) - self.assertEqual(s.data['choice'], None) - - def test_from_native_empty(self): - """ - Make sure from_native() returns an empty string on empty param by default. - """ - f = serializers.ChoiceField(choices=SAMPLE_CHOICES) - self.assertEqual(f.from_native(''), '') - self.assertEqual(f.from_native(None), '') - - def test_from_native_empty_override(self): - """ - Make sure you can override from_native() behavior regarding empty values. - """ - f = serializers.ChoiceField(choices=SAMPLE_CHOICES, empty=None) - self.assertEqual(f.from_native(''), None) - self.assertEqual(f.from_native(None), None) - - def test_metadata_choices(self): - """ - Make sure proper choices are included in the field's metadata. - """ - choices = [{'value': v, 'display_name': n} for v, n in SAMPLE_CHOICES] - f = serializers.ChoiceField(choices=SAMPLE_CHOICES) - self.assertEqual(f.metadata()['choices'], choices) - - def test_metadata_choices_not_required(self): - """ - Make sure proper choices are included in the field's metadata. - """ - choices = [{'value': v, 'display_name': n} - for v, n in models.fields.BLANK_CHOICE_DASH + SAMPLE_CHOICES] - f = serializers.ChoiceField(required=False, choices=SAMPLE_CHOICES) - self.assertEqual(f.metadata()['choices'], choices) - - -class EmailFieldTests(TestCase): - """ - Tests for EmailField attribute values - """ - - class EmailFieldModel(RESTFrameworkModel): - email_field = models.EmailField(blank=True) - - class EmailFieldWithGivenMaxLengthModel(RESTFrameworkModel): - email_field = models.EmailField(max_length=150, blank=True) - - def test_default_model_value(self): - class EmailFieldSerializer(serializers.ModelSerializer): - class Meta: - model = self.EmailFieldModel - - serializer = EmailFieldSerializer(data={}) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 75) - - def test_given_model_value(self): - class EmailFieldSerializer(serializers.ModelSerializer): - class Meta: - model = self.EmailFieldWithGivenMaxLengthModel - - serializer = EmailFieldSerializer(data={}) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 150) - - def test_given_serializer_value(self): - class EmailFieldSerializer(serializers.ModelSerializer): - email_field = serializers.EmailField(source='email_field', max_length=20, required=False) - - class Meta: - model = self.EmailFieldModel - - serializer = EmailFieldSerializer(data={}) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 20) - - -class SlugFieldTests(TestCase): - """ - Tests for SlugField attribute values - """ - - class SlugFieldModel(RESTFrameworkModel): - slug_field = models.SlugField(blank=True) - - class SlugFieldWithGivenMaxLengthModel(RESTFrameworkModel): - slug_field = models.SlugField(max_length=84, blank=True) - - def test_default_model_value(self): - class SlugFieldSerializer(serializers.ModelSerializer): - class Meta: - model = self.SlugFieldModel - - serializer = SlugFieldSerializer(data={}) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(getattr(serializer.fields['slug_field'], 'max_length'), 50) - - def test_given_model_value(self): - class SlugFieldSerializer(serializers.ModelSerializer): - class Meta: - model = self.SlugFieldWithGivenMaxLengthModel - - serializer = SlugFieldSerializer(data={}) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(getattr(serializer.fields['slug_field'], 'max_length'), 84) - - def test_given_serializer_value(self): - class SlugFieldSerializer(serializers.ModelSerializer): - slug_field = serializers.SlugField(source='slug_field', - max_length=20, required=False) - - class Meta: - model = self.SlugFieldModel - - serializer = SlugFieldSerializer(data={}) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(getattr(serializer.fields['slug_field'], - 'max_length'), 20) - - def test_invalid_slug(self): - """ - Make sure an invalid slug raises ValidationError - """ - class SlugFieldSerializer(serializers.ModelSerializer): - slug_field = serializers.SlugField(source='slug_field', max_length=20, required=True) +# class DateFieldTest(TestCase): +# """ +# Tests for the DateFieldTest from_native() and to_native() behavior +# """ + +# def test_from_native_string(self): +# """ +# Make sure from_native() accepts default iso input formats. +# """ +# f = serializers.DateField() +# result_1 = f.from_native('1984-07-31') + +# self.assertEqual(datetime.date(1984, 7, 31), result_1) + +# def test_from_native_datetime_date(self): +# """ +# Make sure from_native() accepts a datetime.date instance. +# """ +# f = serializers.DateField() +# result_1 = f.from_native(datetime.date(1984, 7, 31)) + +# self.assertEqual(result_1, datetime.date(1984, 7, 31)) + +# def test_from_native_custom_format(self): +# """ +# Make sure from_native() accepts custom input formats. +# """ +# f = serializers.DateField(input_formats=['%Y -- %d']) +# result = f.from_native('1984 -- 31') + +# self.assertEqual(datetime.date(1984, 1, 31), result) + +# def test_from_native_invalid_default_on_custom_format(self): +# """ +# Make sure from_native() don't accept default formats if custom format is preset +# """ +# f = serializers.DateField(input_formats=['%Y -- %d']) + +# try: +# f.from_native('1984-07-31') +# except validators.ValidationError as e: +# self.assertEqual(e.messages, ["Date has wrong format. Use one of these formats instead: YYYY -- DD"]) +# else: +# self.fail("ValidationError was not properly raised") + +# def test_from_native_empty(self): +# """ +# Make sure from_native() returns None on empty param. +# """ +# f = serializers.DateField() +# result = f.from_native('') + +# self.assertEqual(result, None) + +# def test_from_native_none(self): +# """ +# Make sure from_native() returns None on None param. +# """ +# f = serializers.DateField() +# result = f.from_native(None) + +# self.assertEqual(result, None) + +# def test_from_native_invalid_date(self): +# """ +# Make sure from_native() raises a ValidationError on passing an invalid date. +# """ +# f = serializers.DateField() + +# try: +# f.from_native('1984-13-31') +# except validators.ValidationError as e: +# self.assertEqual(e.messages, ["Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]"]) +# else: +# self.fail("ValidationError was not properly raised") + +# def test_from_native_invalid_format(self): +# """ +# Make sure from_native() raises a ValidationError on passing an invalid format. +# """ +# f = serializers.DateField() + +# try: +# f.from_native('1984 -- 31') +# except validators.ValidationError as e: +# self.assertEqual(e.messages, ["Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]"]) +# else: +# self.fail("ValidationError was not properly raised") + +# def test_to_native(self): +# """ +# Make sure to_native() returns datetime as default. +# """ +# f = serializers.DateField() + +# result_1 = f.to_native(datetime.date(1984, 7, 31)) + +# self.assertEqual(datetime.date(1984, 7, 31), result_1) + +# def test_to_native_iso(self): +# """ +# Make sure to_native() with 'iso-8601' returns iso formated date. +# """ +# f = serializers.DateField(format='iso-8601') + +# result_1 = f.to_native(datetime.date(1984, 7, 31)) + +# self.assertEqual('1984-07-31', result_1) + +# def test_to_native_custom_format(self): +# """ +# Make sure to_native() returns correct custom format. +# """ +# f = serializers.DateField(format="%Y - %m.%d") + +# result_1 = f.to_native(datetime.date(1984, 7, 31)) + +# self.assertEqual('1984 - 07.31', result_1) + +# def test_to_native_none(self): +# """ +# Make sure from_native() returns None on None param. +# """ +# f = serializers.DateField(required=False) +# self.assertEqual(None, f.to_native(None)) + + +# class DateTimeFieldTest(TestCase): +# """ +# Tests for the DateTimeField from_native() and to_native() behavior +# """ + +# def test_from_native_string(self): +# """ +# Make sure from_native() accepts default iso input formats. +# """ +# f = serializers.DateTimeField() +# result_1 = f.from_native('1984-07-31 04:31') +# result_2 = f.from_native('1984-07-31 04:31:59') +# result_3 = f.from_native('1984-07-31 04:31:59.000200') + +# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31), result_1) +# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59), result_2) +# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59, 200), result_3) + +# def test_from_native_datetime_datetime(self): +# """ +# Make sure from_native() accepts a datetime.datetime instance. +# """ +# f = serializers.DateTimeField() +# result_1 = f.from_native(datetime.datetime(1984, 7, 31, 4, 31)) +# result_2 = f.from_native(datetime.datetime(1984, 7, 31, 4, 31, 59)) +# result_3 = f.from_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) + +# self.assertEqual(result_1, datetime.datetime(1984, 7, 31, 4, 31)) +# self.assertEqual(result_2, datetime.datetime(1984, 7, 31, 4, 31, 59)) +# self.assertEqual(result_3, datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) + +# def test_from_native_custom_format(self): +# """ +# Make sure from_native() accepts custom input formats. +# """ +# f = serializers.DateTimeField(input_formats=['%Y -- %H:%M']) +# result = f.from_native('1984 -- 04:59') + +# self.assertEqual(datetime.datetime(1984, 1, 1, 4, 59), result) + +# def test_from_native_invalid_default_on_custom_format(self): +# """ +# Make sure from_native() don't accept default formats if custom format is preset +# """ +# f = serializers.DateTimeField(input_formats=['%Y -- %H:%M']) + +# try: +# f.from_native('1984-07-31 04:31:59') +# except validators.ValidationError as e: +# self.assertEqual(e.messages, ["Datetime has wrong format. Use one of these formats instead: YYYY -- hh:mm"]) +# else: +# self.fail("ValidationError was not properly raised") + +# def test_from_native_empty(self): +# """ +# Make sure from_native() returns None on empty param. +# """ +# f = serializers.DateTimeField() +# result = f.from_native('') + +# self.assertEqual(result, None) + +# def test_from_native_none(self): +# """ +# Make sure from_native() returns None on None param. +# """ +# f = serializers.DateTimeField() +# result = f.from_native(None) + +# self.assertEqual(result, None) + +# def test_from_native_invalid_datetime(self): +# """ +# Make sure from_native() raises a ValidationError on passing an invalid datetime. +# """ +# f = serializers.DateTimeField() + +# try: +# f.from_native('04:61:59') +# except validators.ValidationError as e: +# self.assertEqual(e.messages, ["Datetime has wrong format. Use one of these formats instead: " +# "YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]"]) +# else: +# self.fail("ValidationError was not properly raised") + +# def test_from_native_invalid_format(self): +# """ +# Make sure from_native() raises a ValidationError on passing an invalid format. +# """ +# f = serializers.DateTimeField() + +# try: +# f.from_native('04 -- 31') +# except validators.ValidationError as e: +# self.assertEqual(e.messages, ["Datetime has wrong format. Use one of these formats instead: " +# "YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]"]) +# else: +# self.fail("ValidationError was not properly raised") + +# def test_to_native(self): +# """ +# Make sure to_native() returns isoformat as default. +# """ +# f = serializers.DateTimeField() + +# result_1 = f.to_native(datetime.datetime(1984, 7, 31)) +# result_2 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31)) +# result_3 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59)) +# result_4 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) + +# self.assertEqual(datetime.datetime(1984, 7, 31), result_1) +# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31), result_2) +# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59), result_3) +# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59, 200), result_4) + +# def test_to_native_iso(self): +# """ +# Make sure to_native() with format=iso-8601 returns iso formatted datetime. +# """ +# f = serializers.DateTimeField(format='iso-8601') + +# result_1 = f.to_native(datetime.datetime(1984, 7, 31)) +# result_2 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31)) +# result_3 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59)) +# result_4 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) + +# self.assertEqual('1984-07-31T00:00:00', result_1) +# self.assertEqual('1984-07-31T04:31:00', result_2) +# self.assertEqual('1984-07-31T04:31:59', result_3) +# self.assertEqual('1984-07-31T04:31:59.000200', result_4) + +# def test_to_native_custom_format(self): +# """ +# Make sure to_native() returns correct custom format. +# """ +# f = serializers.DateTimeField(format="%Y - %H:%M") + +# result_1 = f.to_native(datetime.datetime(1984, 7, 31)) +# result_2 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31)) +# result_3 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59)) +# result_4 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) + +# self.assertEqual('1984 - 00:00', result_1) +# self.assertEqual('1984 - 04:31', result_2) +# self.assertEqual('1984 - 04:31', result_3) +# self.assertEqual('1984 - 04:31', result_4) + +# def test_to_native_none(self): +# """ +# Make sure from_native() returns None on None param. +# """ +# f = serializers.DateTimeField(required=False) +# self.assertEqual(None, f.to_native(None)) + + +# class TimeFieldTest(TestCase): +# """ +# Tests for the TimeField from_native() and to_native() behavior +# """ + +# def test_from_native_string(self): +# """ +# Make sure from_native() accepts default iso input formats. +# """ +# f = serializers.TimeField() +# result_1 = f.from_native('04:31') +# result_2 = f.from_native('04:31:59') +# result_3 = f.from_native('04:31:59.000200') + +# self.assertEqual(datetime.time(4, 31), result_1) +# self.assertEqual(datetime.time(4, 31, 59), result_2) +# self.assertEqual(datetime.time(4, 31, 59, 200), result_3) + +# def test_from_native_datetime_time(self): +# """ +# Make sure from_native() accepts a datetime.time instance. +# """ +# f = serializers.TimeField() +# result_1 = f.from_native(datetime.time(4, 31)) +# result_2 = f.from_native(datetime.time(4, 31, 59)) +# result_3 = f.from_native(datetime.time(4, 31, 59, 200)) + +# self.assertEqual(result_1, datetime.time(4, 31)) +# self.assertEqual(result_2, datetime.time(4, 31, 59)) +# self.assertEqual(result_3, datetime.time(4, 31, 59, 200)) + +# def test_from_native_custom_format(self): +# """ +# Make sure from_native() accepts custom input formats. +# """ +# f = serializers.TimeField(input_formats=['%H -- %M']) +# result = f.from_native('04 -- 31') + +# self.assertEqual(datetime.time(4, 31), result) + +# def test_from_native_invalid_default_on_custom_format(self): +# """ +# Make sure from_native() don't accept default formats if custom format is preset +# """ +# f = serializers.TimeField(input_formats=['%H -- %M']) + +# try: +# f.from_native('04:31:59') +# except validators.ValidationError as e: +# self.assertEqual(e.messages, ["Time has wrong format. Use one of these formats instead: hh -- mm"]) +# else: +# self.fail("ValidationError was not properly raised") + +# def test_from_native_empty(self): +# """ +# Make sure from_native() returns None on empty param. +# """ +# f = serializers.TimeField() +# result = f.from_native('') + +# self.assertEqual(result, None) + +# def test_from_native_none(self): +# """ +# Make sure from_native() returns None on None param. +# """ +# f = serializers.TimeField() +# result = f.from_native(None) + +# self.assertEqual(result, None) + +# def test_from_native_invalid_time(self): +# """ +# Make sure from_native() raises a ValidationError on passing an invalid time. +# """ +# f = serializers.TimeField() + +# try: +# f.from_native('04:61:59') +# except validators.ValidationError as e: +# self.assertEqual(e.messages, ["Time has wrong format. Use one of these formats instead: " +# "hh:mm[:ss[.uuuuuu]]"]) +# else: +# self.fail("ValidationError was not properly raised") + +# def test_from_native_invalid_format(self): +# """ +# Make sure from_native() raises a ValidationError on passing an invalid format. +# """ +# f = serializers.TimeField() + +# try: +# f.from_native('04 -- 31') +# except validators.ValidationError as e: +# self.assertEqual(e.messages, ["Time has wrong format. Use one of these formats instead: " +# "hh:mm[:ss[.uuuuuu]]"]) +# else: +# self.fail("ValidationError was not properly raised") + +# def test_to_native(self): +# """ +# Make sure to_native() returns time object as default. +# """ +# f = serializers.TimeField() +# result_1 = f.to_native(datetime.time(4, 31)) +# result_2 = f.to_native(datetime.time(4, 31, 59)) +# result_3 = f.to_native(datetime.time(4, 31, 59, 200)) + +# self.assertEqual(datetime.time(4, 31), result_1) +# self.assertEqual(datetime.time(4, 31, 59), result_2) +# self.assertEqual(datetime.time(4, 31, 59, 200), result_3) + +# def test_to_native_iso(self): +# """ +# Make sure to_native() with format='iso-8601' returns iso formatted time. +# """ +# f = serializers.TimeField(format='iso-8601') +# result_1 = f.to_native(datetime.time(4, 31)) +# result_2 = f.to_native(datetime.time(4, 31, 59)) +# result_3 = f.to_native(datetime.time(4, 31, 59, 200)) + +# self.assertEqual('04:31:00', result_1) +# self.assertEqual('04:31:59', result_2) +# self.assertEqual('04:31:59.000200', result_3) + +# def test_to_native_custom_format(self): +# """ +# Make sure to_native() returns correct custom format. +# """ +# f = serializers.TimeField(format="%H - %S [%f]") +# result_1 = f.to_native(datetime.time(4, 31)) +# result_2 = f.to_native(datetime.time(4, 31, 59)) +# result_3 = f.to_native(datetime.time(4, 31, 59, 200)) + +# self.assertEqual('04 - 00 [000000]', result_1) +# self.assertEqual('04 - 59 [000000]', result_2) +# self.assertEqual('04 - 59 [000200]', result_3) + + +# class DecimalFieldTest(TestCase): +# """ +# Tests for the DecimalField from_native() and to_native() behavior +# """ + +# def test_from_native_string(self): +# """ +# Make sure from_native() accepts string values +# """ +# f = serializers.DecimalField() +# result_1 = f.from_native('9000') +# result_2 = f.from_native('1.00000001') + +# self.assertEqual(Decimal('9000'), result_1) +# self.assertEqual(Decimal('1.00000001'), result_2) + +# def test_from_native_invalid_string(self): +# """ +# Make sure from_native() raises ValidationError on passing invalid string +# """ +# f = serializers.DecimalField() + +# try: +# f.from_native('123.45.6') +# except validators.ValidationError as e: +# self.assertEqual(e.messages, ["Enter a number."]) +# else: +# self.fail("ValidationError was not properly raised") + +# def test_from_native_integer(self): +# """ +# Make sure from_native() accepts integer values +# """ +# f = serializers.DecimalField() +# result = f.from_native(9000) + +# self.assertEqual(Decimal('9000'), result) + +# def test_from_native_float(self): +# """ +# Make sure from_native() accepts float values +# """ +# f = serializers.DecimalField() +# result = f.from_native(1.00000001) + +# self.assertEqual(Decimal('1.00000001'), result) + +# def test_from_native_empty(self): +# """ +# Make sure from_native() returns None on empty param. +# """ +# f = serializers.DecimalField() +# result = f.from_native('') + +# self.assertEqual(result, None) + +# def test_from_native_none(self): +# """ +# Make sure from_native() returns None on None param. +# """ +# f = serializers.DecimalField() +# result = f.from_native(None) + +# self.assertEqual(result, None) + +# def test_to_native(self): +# """ +# Make sure to_native() returns Decimal as string. +# """ +# f = serializers.DecimalField() + +# result_1 = f.to_native(Decimal('9000')) +# result_2 = f.to_native(Decimal('1.00000001')) + +# self.assertEqual(Decimal('9000'), result_1) +# self.assertEqual(Decimal('1.00000001'), result_2) + +# def test_to_native_none(self): +# """ +# Make sure from_native() returns None on None param. +# """ +# f = serializers.DecimalField(required=False) +# self.assertEqual(None, f.to_native(None)) + +# def test_valid_serialization(self): +# """ +# Make sure the serializer works correctly +# """ +# class DecimalSerializer(serializers.Serializer): +# decimal_field = serializers.DecimalField(max_value=9010, +# min_value=9000, +# max_digits=6, +# decimal_places=2) + +# self.assertTrue(DecimalSerializer(data={'decimal_field': '9001'}).is_valid()) +# self.assertTrue(DecimalSerializer(data={'decimal_field': '9001.2'}).is_valid()) +# self.assertTrue(DecimalSerializer(data={'decimal_field': '9001.23'}).is_valid()) + +# self.assertFalse(DecimalSerializer(data={'decimal_field': '8000'}).is_valid()) +# self.assertFalse(DecimalSerializer(data={'decimal_field': '9900'}).is_valid()) +# self.assertFalse(DecimalSerializer(data={'decimal_field': '9001.234'}).is_valid()) + +# def test_raise_max_value(self): +# """ +# Make sure max_value violations raises ValidationError +# """ +# class DecimalSerializer(serializers.Serializer): +# decimal_field = serializers.DecimalField(max_value=100) + +# s = DecimalSerializer(data={'decimal_field': '123'}) + +# self.assertFalse(s.is_valid()) +# self.assertEqual(s.errors, {'decimal_field': ['Ensure this value is less than or equal to 100.']}) + +# def test_raise_min_value(self): +# """ +# Make sure min_value violations raises ValidationError +# """ +# class DecimalSerializer(serializers.Serializer): +# decimal_field = serializers.DecimalField(min_value=100) + +# s = DecimalSerializer(data={'decimal_field': '99'}) + +# self.assertFalse(s.is_valid()) +# self.assertEqual(s.errors, {'decimal_field': ['Ensure this value is greater than or equal to 100.']}) + +# def test_raise_max_digits(self): +# """ +# Make sure max_digits violations raises ValidationError +# """ +# class DecimalSerializer(serializers.Serializer): +# decimal_field = serializers.DecimalField(max_digits=5) + +# s = DecimalSerializer(data={'decimal_field': '123.456'}) + +# self.assertFalse(s.is_valid()) +# self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 5 digits in total.']}) + +# def test_raise_max_decimal_places(self): +# """ +# Make sure max_decimal_places violations raises ValidationError +# """ +# class DecimalSerializer(serializers.Serializer): +# decimal_field = serializers.DecimalField(decimal_places=3) + +# s = DecimalSerializer(data={'decimal_field': '123.4567'}) + +# self.assertFalse(s.is_valid()) +# self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 3 decimal places.']}) + +# def test_raise_max_whole_digits(self): +# """ +# Make sure max_whole_digits violations raises ValidationError +# """ +# class DecimalSerializer(serializers.Serializer): +# decimal_field = serializers.DecimalField(max_digits=4, decimal_places=3) + +# s = DecimalSerializer(data={'decimal_field': '12345.6'}) + +# self.assertFalse(s.is_valid()) +# self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 4 digits in total.']}) + + +# class ChoiceFieldTests(TestCase): +# """ +# Tests for the ChoiceField options generator +# """ +# def test_choices_required(self): +# """ +# Make sure proper choices are rendered if field is required +# """ +# f = serializers.ChoiceField(required=True, choices=SAMPLE_CHOICES) +# self.assertEqual(f.choices, SAMPLE_CHOICES) + +# def test_choices_not_required(self): +# """ +# Make sure proper choices (plus blank) are rendered if the field isn't required +# """ +# f = serializers.ChoiceField(required=False, choices=SAMPLE_CHOICES) +# self.assertEqual(f.choices, models.fields.BLANK_CHOICE_DASH + SAMPLE_CHOICES) + +# def test_blank_choice_display(self): +# blank = 'No Preference' +# f = serializers.ChoiceField( +# required=False, +# choices=SAMPLE_CHOICES, +# blank_display_value=blank, +# ) +# self.assertEqual(f.choices, [('', blank)] + SAMPLE_CHOICES) + +# def test_invalid_choice_model(self): +# s = ChoiceFieldModelSerializer(data={'choice': 'wrong_value'}) +# self.assertFalse(s.is_valid()) +# self.assertEqual(s.errors, {'choice': ['Select a valid choice. wrong_value is not one of the available choices.']}) +# self.assertEqual(s.data['choice'], '') + +# def test_empty_choice_model(self): +# """ +# Test that the 'empty' value is correctly passed and used depending on +# the 'null' property on the model field. +# """ +# s = ChoiceFieldModelSerializer(data={'choice': ''}) +# self.assertTrue(s.is_valid()) +# self.assertEqual(s.data['choice'], '') + +# s = ChoiceFieldModelWithNullSerializer(data={'choice': ''}) +# self.assertTrue(s.is_valid()) +# self.assertEqual(s.data['choice'], None) + +# def test_from_native_empty(self): +# """ +# Make sure from_native() returns an empty string on empty param by default. +# """ +# f = serializers.ChoiceField(choices=SAMPLE_CHOICES) +# self.assertEqual(f.from_native(''), '') +# self.assertEqual(f.from_native(None), '') + +# def test_from_native_empty_override(self): +# """ +# Make sure you can override from_native() behavior regarding empty values. +# """ +# f = serializers.ChoiceField(choices=SAMPLE_CHOICES, empty=None) +# self.assertEqual(f.from_native(''), None) +# self.assertEqual(f.from_native(None), None) + +# def test_metadata_choices(self): +# """ +# Make sure proper choices are included in the field's metadata. +# """ +# choices = [{'value': v, 'display_name': n} for v, n in SAMPLE_CHOICES] +# f = serializers.ChoiceField(choices=SAMPLE_CHOICES) +# self.assertEqual(f.metadata()['choices'], choices) + +# def test_metadata_choices_not_required(self): +# """ +# Make sure proper choices are included in the field's metadata. +# """ +# choices = [{'value': v, 'display_name': n} +# for v, n in models.fields.BLANK_CHOICE_DASH + SAMPLE_CHOICES] +# f = serializers.ChoiceField(required=False, choices=SAMPLE_CHOICES) +# self.assertEqual(f.metadata()['choices'], choices) + + +# class EmailFieldTests(TestCase): +# """ +# Tests for EmailField attribute values +# """ + +# class EmailFieldModel(RESTFrameworkModel): +# email_field = models.EmailField(blank=True) + +# class EmailFieldWithGivenMaxLengthModel(RESTFrameworkModel): +# email_field = models.EmailField(max_length=150, blank=True) + +# def test_default_model_value(self): +# class EmailFieldSerializer(serializers.ModelSerializer): +# class Meta: +# model = self.EmailFieldModel + +# serializer = EmailFieldSerializer(data={}) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 75) + +# def test_given_model_value(self): +# class EmailFieldSerializer(serializers.ModelSerializer): +# class Meta: +# model = self.EmailFieldWithGivenMaxLengthModel + +# serializer = EmailFieldSerializer(data={}) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 150) + +# def test_given_serializer_value(self): +# class EmailFieldSerializer(serializers.ModelSerializer): +# email_field = serializers.EmailField(source='email_field', max_length=20, required=False) + +# class Meta: +# model = self.EmailFieldModel + +# serializer = EmailFieldSerializer(data={}) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 20) + + +# class SlugFieldTests(TestCase): +# """ +# Tests for SlugField attribute values +# """ + +# class SlugFieldModel(RESTFrameworkModel): +# slug_field = models.SlugField(blank=True) + +# class SlugFieldWithGivenMaxLengthModel(RESTFrameworkModel): +# slug_field = models.SlugField(max_length=84, blank=True) + +# def test_default_model_value(self): +# class SlugFieldSerializer(serializers.ModelSerializer): +# class Meta: +# model = self.SlugFieldModel + +# serializer = SlugFieldSerializer(data={}) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(getattr(serializer.fields['slug_field'], 'max_length'), 50) + +# def test_given_model_value(self): +# class SlugFieldSerializer(serializers.ModelSerializer): +# class Meta: +# model = self.SlugFieldWithGivenMaxLengthModel + +# serializer = SlugFieldSerializer(data={}) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(getattr(serializer.fields['slug_field'], 'max_length'), 84) + +# def test_given_serializer_value(self): +# class SlugFieldSerializer(serializers.ModelSerializer): +# slug_field = serializers.SlugField(source='slug_field', +# max_length=20, required=False) + +# class Meta: +# model = self.SlugFieldModel + +# serializer = SlugFieldSerializer(data={}) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(getattr(serializer.fields['slug_field'], +# 'max_length'), 20) + +# def test_invalid_slug(self): +# """ +# Make sure an invalid slug raises ValidationError +# """ +# class SlugFieldSerializer(serializers.ModelSerializer): +# slug_field = serializers.SlugField(source='slug_field', max_length=20, required=True) - class Meta: - model = self.SlugFieldModel +# class Meta: +# model = self.SlugFieldModel - s = SlugFieldSerializer(data={'slug_field': 'a b'}) +# s = SlugFieldSerializer(data={'slug_field': 'a b'}) - self.assertEqual(s.is_valid(), False) - self.assertEqual(s.errors, {'slug_field': ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."]}) +# self.assertEqual(s.is_valid(), False) +# self.assertEqual(s.errors, {'slug_field': ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."]}) -class URLFieldTests(TestCase): - """ - Tests for URLField attribute values. +# class URLFieldTests(TestCase): +# """ +# Tests for URLField attribute values. - (Includes test for #1210, checking that validators can be overridden.) - """ +# (Includes test for #1210, checking that validators can be overridden.) +# """ - class URLFieldModel(RESTFrameworkModel): - url_field = models.URLField(blank=True) +# class URLFieldModel(RESTFrameworkModel): +# url_field = models.URLField(blank=True) - class URLFieldWithGivenMaxLengthModel(RESTFrameworkModel): - url_field = models.URLField(max_length=128, blank=True) +# class URLFieldWithGivenMaxLengthModel(RESTFrameworkModel): +# url_field = models.URLField(max_length=128, blank=True) - def test_default_model_value(self): - class URLFieldSerializer(serializers.ModelSerializer): - class Meta: - model = self.URLFieldModel +# def test_default_model_value(self): +# class URLFieldSerializer(serializers.ModelSerializer): +# class Meta: +# model = self.URLFieldModel - serializer = URLFieldSerializer(data={}) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(getattr(serializer.fields['url_field'], - 'max_length'), 200) +# serializer = URLFieldSerializer(data={}) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(getattr(serializer.fields['url_field'], +# 'max_length'), 200) - def test_given_model_value(self): - class URLFieldSerializer(serializers.ModelSerializer): - class Meta: - model = self.URLFieldWithGivenMaxLengthModel +# def test_given_model_value(self): +# class URLFieldSerializer(serializers.ModelSerializer): +# class Meta: +# model = self.URLFieldWithGivenMaxLengthModel - serializer = URLFieldSerializer(data={}) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(getattr(serializer.fields['url_field'], - 'max_length'), 128) +# serializer = URLFieldSerializer(data={}) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(getattr(serializer.fields['url_field'], +# 'max_length'), 128) - def test_given_serializer_value(self): - class URLFieldSerializer(serializers.ModelSerializer): - url_field = serializers.URLField(source='url_field', - max_length=20, required=False) +# def test_given_serializer_value(self): +# class URLFieldSerializer(serializers.ModelSerializer): +# url_field = serializers.URLField(source='url_field', +# max_length=20, required=False) - class Meta: - model = self.URLFieldWithGivenMaxLengthModel +# class Meta: +# model = self.URLFieldWithGivenMaxLengthModel - serializer = URLFieldSerializer(data={}) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(getattr(serializer.fields['url_field'], - 'max_length'), 20) +# serializer = URLFieldSerializer(data={}) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(getattr(serializer.fields['url_field'], +# 'max_length'), 20) - def test_validators_can_be_overridden(self): - url_field = serializers.URLField(validators=[]) - validators = url_field.validators - self.assertEqual([], validators, 'Passing `validators` kwarg should have overridden default validators') +# def test_validators_can_be_overridden(self): +# url_field = serializers.URLField(validators=[]) +# validators = url_field.validators +# self.assertEqual([], validators, 'Passing `validators` kwarg should have overridden default validators') -class FieldMetadata(TestCase): - def setUp(self): - self.required_field = serializers.Field() - self.required_field.label = uuid4().hex - self.required_field.required = True +# class FieldMetadata(TestCase): +# def setUp(self): +# self.required_field = serializers.Field() +# self.required_field.label = uuid4().hex +# self.required_field.required = True - self.optional_field = serializers.Field() - self.optional_field.label = uuid4().hex - self.optional_field.required = False +# self.optional_field = serializers.Field() +# self.optional_field.label = uuid4().hex +# self.optional_field.required = False - def test_required(self): - self.assertEqual(self.required_field.metadata()['required'], True) +# def test_required(self): +# self.assertEqual(self.required_field.metadata()['required'], True) - def test_optional(self): - self.assertEqual(self.optional_field.metadata()['required'], False) +# def test_optional(self): +# self.assertEqual(self.optional_field.metadata()['required'], False) - def test_label(self): - for field in (self.required_field, self.optional_field): - self.assertEqual(field.metadata()['label'], field.label) +# def test_label(self): +# for field in (self.required_field, self.optional_field): +# self.assertEqual(field.metadata()['label'], field.label) -class FieldCallableDefault(TestCase): - def setUp(self): - self.simple_callable = lambda: 'foo bar' +# class FieldCallableDefault(TestCase): +# def setUp(self): +# self.simple_callable = lambda: 'foo bar' - def test_default_can_be_simple_callable(self): - """ - Ensure that the 'default' argument can also be a simple callable. - """ - field = serializers.WritableField(default=self.simple_callable) - into = {} - field.field_from_native({}, {}, 'field', into) - self.assertEqual(into, {'field': 'foo bar'}) +# def test_default_can_be_simple_callable(self): +# """ +# Ensure that the 'default' argument can also be a simple callable. +# """ +# field = serializers.WritableField(default=self.simple_callable) +# into = {} +# field.field_from_native({}, {}, 'field', into) +# self.assertEqual(into, {'field': 'foo bar'}) -class CustomIntegerField(TestCase): - """ - Test that custom fields apply min_value and max_value constraints - """ - def test_custom_fields_can_be_validated_for_value(self): +# class CustomIntegerField(TestCase): +# """ +# Test that custom fields apply min_value and max_value constraints +# """ +# def test_custom_fields_can_be_validated_for_value(self): - class MoneyField(models.PositiveIntegerField): - pass +# class MoneyField(models.PositiveIntegerField): +# pass - class EntryModel(models.Model): - bank = MoneyField(validators=[validators.MaxValueValidator(100)]) +# class EntryModel(models.Model): +# bank = MoneyField(validators=[validators.MaxValueValidator(100)]) - class EntrySerializer(serializers.ModelSerializer): - class Meta: - model = EntryModel +# class EntrySerializer(serializers.ModelSerializer): +# class Meta: +# model = EntryModel - entry = EntryModel(bank=1) +# entry = EntryModel(bank=1) - serializer = EntrySerializer(entry, data={"bank": 11}) - self.assertTrue(serializer.is_valid()) +# serializer = EntrySerializer(entry, data={"bank": 11}) +# self.assertTrue(serializer.is_valid()) - serializer = EntrySerializer(entry, data={"bank": -1}) - self.assertFalse(serializer.is_valid()) +# serializer = EntrySerializer(entry, data={"bank": -1}) +# self.assertFalse(serializer.is_valid()) - serializer = EntrySerializer(entry, data={"bank": 101}) - self.assertFalse(serializer.is_valid()) +# serializer = EntrySerializer(entry, data={"bank": 101}) +# self.assertFalse(serializer.is_valid()) -class BooleanField(TestCase): - """ - Tests for BooleanField - """ - def test_boolean_required(self): - class BooleanRequiredSerializer(serializers.Serializer): - bool_field = serializers.BooleanField(required=True) +# class BooleanField(TestCase): +# """ +# Tests for BooleanField +# """ +# def test_boolean_required(self): +# class BooleanRequiredSerializer(serializers.Serializer): +# bool_field = serializers.BooleanField(required=True) - self.assertFalse(BooleanRequiredSerializer(data={}).is_valid()) +# self.assertFalse(BooleanRequiredSerializer(data={}).is_valid()) -class SerializerMethodFieldTest(TestCase): - """ - Tests for the SerializerMethodField field_to_native() behavior - """ - class SerializerTest(serializers.Serializer): - def get_my_test(self, obj): - return obj.my_test[0:5] +# class SerializerMethodFieldTest(TestCase): +# """ +# Tests for the SerializerMethodField field_to_native() behavior +# """ +# class SerializerTest(serializers.Serializer): +# def get_my_test(self, obj): +# return obj.my_test[0:5] - class Example(): - my_test = 'Hey, this is a test !' +# class Example(): +# my_test = 'Hey, this is a test !' - def test_field_to_native(self): - s = serializers.SerializerMethodField('get_my_test') - s.initialize(self.SerializerTest(), 'name') - result = s.field_to_native(self.Example(), None) - self.assertEqual(result, 'Hey, ') +# def test_field_to_native(self): +# s = serializers.SerializerMethodField('get_my_test') +# s.initialize(self.SerializerTest(), 'name') +# result = s.field_to_native(self.Example(), None) +# self.assertEqual(result, 'Hey, ') diff --git a/tests/test_files.py b/tests/test_files.py index de4f71d1a..a5613fcbe 100644 --- a/tests/test_files.py +++ b/tests/test_files.py @@ -1,92 +1,92 @@ -from __future__ import unicode_literals -from django.test import TestCase -from django.utils import six -from rest_framework import serializers -from rest_framework.compat import BytesIO -import datetime +# from __future__ import unicode_literals +# from django.test import TestCase +# from django.utils import six +# from rest_framework import serializers +# from rest_framework.compat import BytesIO +# import datetime -class UploadedFile(object): - def __init__(self, file=None, created=None): - self.file = file - self.created = created or datetime.datetime.now() +# class UploadedFile(object): +# def __init__(self, file=None, created=None): +# self.file = file +# self.created = created or datetime.datetime.now() -class UploadedFileSerializer(serializers.Serializer): - file = serializers.FileField(required=False) - created = serializers.DateTimeField() +# class UploadedFileSerializer(serializers.Serializer): +# file = serializers.FileField(required=False) +# created = serializers.DateTimeField() - def restore_object(self, attrs, instance=None): - if instance: - instance.file = attrs['file'] - instance.created = attrs['created'] - return instance - return UploadedFile(**attrs) +# def restore_object(self, attrs, instance=None): +# if instance: +# instance.file = attrs['file'] +# instance.created = attrs['created'] +# return instance +# return UploadedFile(**attrs) -class FileSerializerTests(TestCase): - def test_create(self): - now = datetime.datetime.now() - file = BytesIO(six.b('stuff')) - file.name = 'stuff.txt' - file.size = len(file.getvalue()) - serializer = UploadedFileSerializer(data={'created': now}, files={'file': file}) - uploaded_file = UploadedFile(file=file, created=now) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.object.created, uploaded_file.created) - self.assertEqual(serializer.object.file, uploaded_file.file) - self.assertFalse(serializer.object is uploaded_file) +# class FileSerializerTests(TestCase): +# def test_create(self): +# now = datetime.datetime.now() +# file = BytesIO(six.b('stuff')) +# file.name = 'stuff.txt' +# file.size = len(file.getvalue()) +# serializer = UploadedFileSerializer(data={'created': now}, files={'file': file}) +# uploaded_file = UploadedFile(file=file, created=now) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.object.created, uploaded_file.created) +# self.assertEqual(serializer.object.file, uploaded_file.file) +# self.assertFalse(serializer.object is uploaded_file) - def test_creation_failure(self): - """ - Passing files=None should result in an ValidationError +# def test_creation_failure(self): +# """ +# Passing files=None should result in an ValidationError - Regression test for: - https://github.com/tomchristie/django-rest-framework/issues/542 - """ - now = datetime.datetime.now() +# Regression test for: +# https://github.com/tomchristie/django-rest-framework/issues/542 +# """ +# now = datetime.datetime.now() - serializer = UploadedFileSerializer(data={'created': now}) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.object.created, now) - self.assertIsNone(serializer.object.file) +# serializer = UploadedFileSerializer(data={'created': now}) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.object.created, now) +# self.assertIsNone(serializer.object.file) - def test_remove_with_empty_string(self): - """ - Passing empty string as data should cause file to be removed +# def test_remove_with_empty_string(self): +# """ +# Passing empty string as data should cause file to be removed - Test for: - https://github.com/tomchristie/django-rest-framework/issues/937 - """ - now = datetime.datetime.now() - file = BytesIO(six.b('stuff')) - file.name = 'stuff.txt' - file.size = len(file.getvalue()) +# Test for: +# https://github.com/tomchristie/django-rest-framework/issues/937 +# """ +# now = datetime.datetime.now() +# file = BytesIO(six.b('stuff')) +# file.name = 'stuff.txt' +# file.size = len(file.getvalue()) - uploaded_file = UploadedFile(file=file, created=now) +# uploaded_file = UploadedFile(file=file, created=now) - serializer = UploadedFileSerializer(instance=uploaded_file, data={'created': now, 'file': ''}) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.object.created, uploaded_file.created) - self.assertIsNone(serializer.object.file) +# serializer = UploadedFileSerializer(instance=uploaded_file, data={'created': now, 'file': ''}) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.object.created, uploaded_file.created) +# self.assertIsNone(serializer.object.file) - def test_validation_error_with_non_file(self): - """ - Passing non-files should raise a validation error. - """ - now = datetime.datetime.now() - errmsg = 'No file was submitted. Check the encoding type on the form.' +# def test_validation_error_with_non_file(self): +# """ +# Passing non-files should raise a validation error. +# """ +# now = datetime.datetime.now() +# errmsg = 'No file was submitted. Check the encoding type on the form.' - serializer = UploadedFileSerializer(data={'created': now, 'file': 'abc'}) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'file': [errmsg]}) +# serializer = UploadedFileSerializer(data={'created': now, 'file': 'abc'}) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'file': [errmsg]}) - def test_validation_with_no_data(self): - """ - Validation should still function when no data dictionary is provided. - """ - uploaded_file = BytesIO(six.b('stuff')) - uploaded_file.name = 'stuff.txt' - uploaded_file.size = len(uploaded_file.getvalue()) - serializer = UploadedFileSerializer(files={'file': uploaded_file}) - self.assertFalse(serializer.is_valid()) +# def test_validation_with_no_data(self): +# """ +# Validation should still function when no data dictionary is provided. +# """ +# uploaded_file = BytesIO(six.b('stuff')) +# uploaded_file.name = 'stuff.txt' +# uploaded_file.size = len(uploaded_file.getvalue()) +# serializer = UploadedFileSerializer(files={'file': uploaded_file}) +# self.assertFalse(serializer.is_valid()) diff --git a/tests/test_genericrelations.py b/tests/test_genericrelations.py index 95295eaa8..a87ea3fdd 100644 --- a/tests/test_genericrelations.py +++ b/tests/test_genericrelations.py @@ -1,151 +1,151 @@ -from __future__ import unicode_literals -from django.contrib.contenttypes.models import ContentType -from django.contrib.contenttypes.generic import GenericRelation, GenericForeignKey -from django.db import models -from django.test import TestCase -from rest_framework import serializers -from rest_framework.compat import python_2_unicode_compatible +# from __future__ import unicode_literals +# from django.contrib.contenttypes.models import ContentType +# from django.contrib.contenttypes.generic import GenericRelation, GenericForeignKey +# from django.db import models +# from django.test import TestCase +# from rest_framework import serializers +# from rest_framework.compat import python_2_unicode_compatible -@python_2_unicode_compatible -class Tag(models.Model): - """ - Tags have a descriptive slug, and are attached to an arbitrary object. - """ - tag = models.SlugField() - content_type = models.ForeignKey(ContentType) - object_id = models.PositiveIntegerField() - tagged_item = GenericForeignKey('content_type', 'object_id') +# @python_2_unicode_compatible +# class Tag(models.Model): +# """ +# Tags have a descriptive slug, and are attached to an arbitrary object. +# """ +# tag = models.SlugField() +# content_type = models.ForeignKey(ContentType) +# object_id = models.PositiveIntegerField() +# tagged_item = GenericForeignKey('content_type', 'object_id') - def __str__(self): - return self.tag +# def __str__(self): +# return self.tag -@python_2_unicode_compatible -class Bookmark(models.Model): - """ - A URL bookmark that may have multiple tags attached. - """ - url = models.URLField() - tags = GenericRelation(Tag) +# @python_2_unicode_compatible +# class Bookmark(models.Model): +# """ +# A URL bookmark that may have multiple tags attached. +# """ +# url = models.URLField() +# tags = GenericRelation(Tag) - def __str__(self): - return 'Bookmark: %s' % self.url +# def __str__(self): +# return 'Bookmark: %s' % self.url -@python_2_unicode_compatible -class Note(models.Model): - """ - A textual note that may have multiple tags attached. - """ - text = models.TextField() - tags = GenericRelation(Tag) +# @python_2_unicode_compatible +# class Note(models.Model): +# """ +# A textual note that may have multiple tags attached. +# """ +# text = models.TextField() +# tags = GenericRelation(Tag) - def __str__(self): - return 'Note: %s' % self.text +# def __str__(self): +# return 'Note: %s' % self.text -class TestGenericRelations(TestCase): - def setUp(self): - self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/') - Tag.objects.create(tagged_item=self.bookmark, tag='django') - Tag.objects.create(tagged_item=self.bookmark, tag='python') - self.note = Note.objects.create(text='Remember the milk') - Tag.objects.create(tagged_item=self.note, tag='reminder') +# class TestGenericRelations(TestCase): +# def setUp(self): +# self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/') +# Tag.objects.create(tagged_item=self.bookmark, tag='django') +# Tag.objects.create(tagged_item=self.bookmark, tag='python') +# self.note = Note.objects.create(text='Remember the milk') +# Tag.objects.create(tagged_item=self.note, tag='reminder') - def test_generic_relation(self): - """ - Test a relationship that spans a GenericRelation field. - IE. A reverse generic relationship. - """ +# def test_generic_relation(self): +# """ +# Test a relationship that spans a GenericRelation field. +# IE. A reverse generic relationship. +# """ - class BookmarkSerializer(serializers.ModelSerializer): - tags = serializers.RelatedField(many=True) +# class BookmarkSerializer(serializers.ModelSerializer): +# tags = serializers.RelatedField(many=True) - class Meta: - model = Bookmark - exclude = ('id',) +# class Meta: +# model = Bookmark +# exclude = ('id',) - serializer = BookmarkSerializer(self.bookmark) - expected = { - 'tags': ['django', 'python'], - 'url': 'https://www.djangoproject.com/' - } - self.assertEqual(serializer.data, expected) +# serializer = BookmarkSerializer(self.bookmark) +# expected = { +# 'tags': ['django', 'python'], +# 'url': 'https://www.djangoproject.com/' +# } +# self.assertEqual(serializer.data, expected) - def test_generic_nested_relation(self): - """ - Test saving a GenericRelation field via a nested serializer. - """ +# def test_generic_nested_relation(self): +# """ +# Test saving a GenericRelation field via a nested serializer. +# """ - class TagSerializer(serializers.ModelSerializer): - class Meta: - model = Tag - exclude = ('content_type', 'object_id') +# class TagSerializer(serializers.ModelSerializer): +# class Meta: +# model = Tag +# exclude = ('content_type', 'object_id') - class BookmarkSerializer(serializers.ModelSerializer): - tags = TagSerializer(many=True) +# class BookmarkSerializer(serializers.ModelSerializer): +# tags = TagSerializer(many=True) - class Meta: - model = Bookmark - exclude = ('id',) +# class Meta: +# model = Bookmark +# exclude = ('id',) - data = { - 'url': 'https://docs.djangoproject.com/', - 'tags': [ - {'tag': 'contenttypes'}, - {'tag': 'genericrelations'}, - ] - } - serializer = BookmarkSerializer(data=data) - self.assertTrue(serializer.is_valid()) - serializer.save() - self.assertEqual(serializer.object.tags.count(), 2) +# data = { +# 'url': 'https://docs.djangoproject.com/', +# 'tags': [ +# {'tag': 'contenttypes'}, +# {'tag': 'genericrelations'}, +# ] +# } +# serializer = BookmarkSerializer(data=data) +# self.assertTrue(serializer.is_valid()) +# serializer.save() +# self.assertEqual(serializer.object.tags.count(), 2) - def test_generic_fk(self): - """ - Test a relationship that spans a GenericForeignKey field. - IE. A forward generic relationship. - """ +# def test_generic_fk(self): +# """ +# Test a relationship that spans a GenericForeignKey field. +# IE. A forward generic relationship. +# """ - class TagSerializer(serializers.ModelSerializer): - tagged_item = serializers.RelatedField() +# class TagSerializer(serializers.ModelSerializer): +# tagged_item = serializers.RelatedField() - class Meta: - model = Tag - exclude = ('id', 'content_type', 'object_id') +# class Meta: +# model = Tag +# exclude = ('id', 'content_type', 'object_id') - serializer = TagSerializer(Tag.objects.all(), many=True) - expected = [ - { - 'tag': 'django', - 'tagged_item': 'Bookmark: https://www.djangoproject.com/' - }, - { - 'tag': 'python', - 'tagged_item': 'Bookmark: https://www.djangoproject.com/' - }, - { - 'tag': 'reminder', - 'tagged_item': 'Note: Remember the milk' - } - ] - self.assertEqual(serializer.data, expected) +# serializer = TagSerializer(Tag.objects.all(), many=True) +# expected = [ +# { +# 'tag': 'django', +# 'tagged_item': 'Bookmark: https://www.djangoproject.com/' +# }, +# { +# 'tag': 'python', +# 'tagged_item': 'Bookmark: https://www.djangoproject.com/' +# }, +# { +# 'tag': 'reminder', +# 'tagged_item': 'Note: Remember the milk' +# } +# ] +# self.assertEqual(serializer.data, expected) - def test_restore_object_generic_fk(self): - """ - Ensure an object with a generic foreign key can be restored. - """ +# def test_restore_object_generic_fk(self): +# """ +# Ensure an object with a generic foreign key can be restored. +# """ - class TagSerializer(serializers.ModelSerializer): - class Meta: - model = Tag - exclude = ('content_type', 'object_id') +# class TagSerializer(serializers.ModelSerializer): +# class Meta: +# model = Tag +# exclude = ('content_type', 'object_id') - serializer = TagSerializer() +# serializer = TagSerializer() - bookmark = Bookmark(url='http://example.com') - attrs = {'tagged_item': bookmark, 'tag': 'example'} +# bookmark = Bookmark(url='http://example.com') +# attrs = {'tagged_item': bookmark, 'tag': 'example'} - tag = serializer.restore_object(attrs) - self.assertEqual(tag.tagged_item, bookmark) +# tag = serializer.restore_object(attrs) +# self.assertEqual(tag.tagged_item, bookmark) diff --git a/tests/test_generics.py b/tests/test_generics.py index f50d53e99..55f361b24 100644 --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -33,13 +33,9 @@ class InstanceView(generics.RetrieveUpdateDestroyAPIView): """ Example description for OPTIONS. """ - queryset = BasicModel.objects.all() + queryset = BasicModel.objects.exclude(text='filtered out') serializer_class = BasicSerializer - def get_queryset(self): - queryset = super(InstanceView, self).get_queryset() - return queryset.exclude(text='filtered out') - class FKInstanceView(generics.RetrieveUpdateDestroyAPIView): """ @@ -50,11 +46,11 @@ class FKInstanceView(generics.RetrieveUpdateDestroyAPIView): class SlugSerializer(serializers.ModelSerializer): - slug = serializers.Field() # read only + slug = serializers.Field(read_only=True) class Meta: model = SlugBasedModel - exclude = ('id',) + fields = ('text', 'slug') class SlugBasedInstanceView(InstanceView): @@ -125,46 +121,46 @@ class TestRootView(TestCase): self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) self.assertEqual(response.data, {"detail": "Method 'DELETE' not allowed."}) - def test_options_root_view(self): - """ - OPTIONS requests to ListCreateAPIView should return metadata - """ - request = factory.options('/') - with self.assertNumQueries(0): - response = self.view(request).render() - expected = { - 'parses': [ - 'application/json', - 'application/x-www-form-urlencoded', - 'multipart/form-data' - ], - 'renders': [ - 'application/json', - 'text/html' - ], - 'name': 'Root', - 'description': 'Example description for OPTIONS.', - 'actions': { - 'POST': { - 'text': { - 'max_length': 100, - 'read_only': False, - 'required': True, - 'type': 'string', - "label": "Text comes here", - "help_text": "Text description." - }, - 'id': { - 'read_only': True, - 'required': False, - 'type': 'integer', - 'label': 'ID', - }, - } - } - } - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEqual(response.data, expected) + # def test_options_root_view(self): + # """ + # OPTIONS requests to ListCreateAPIView should return metadata + # """ + # request = factory.options('/') + # with self.assertNumQueries(0): + # response = self.view(request).render() + # expected = { + # 'parses': [ + # 'application/json', + # 'application/x-www-form-urlencoded', + # 'multipart/form-data' + # ], + # 'renders': [ + # 'application/json', + # 'text/html' + # ], + # 'name': 'Root', + # 'description': 'Example description for OPTIONS.', + # 'actions': { + # 'POST': { + # 'text': { + # 'max_length': 100, + # 'read_only': False, + # 'required': True, + # 'type': 'string', + # "label": "Text comes here", + # "help_text": "Text description." + # }, + # 'id': { + # 'read_only': True, + # 'required': False, + # 'type': 'integer', + # 'label': 'ID', + # }, + # } + # } + # } + # self.assertEqual(response.status_code, status.HTTP_200_OK) + # self.assertEqual(response.data, expected) def test_post_cannot_set_id(self): """ @@ -223,10 +219,10 @@ class TestInstanceView(TestCase): """ data = {'text': 'foobar'} request = factory.put('/1', data, format='json') - with self.assertNumQueries(2): + with self.assertNumQueries(3): response = self.view(request, pk='1').render() self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEqual(response.data, {'id': 1, 'text': 'foobar'}) + self.assertEqual(dict(response.data), {'id': 1, 'text': 'foobar'}) updated = self.objects.get(id=1) self.assertEqual(updated.text, 'foobar') @@ -237,7 +233,7 @@ class TestInstanceView(TestCase): data = {'text': 'foobar'} request = factory.patch('/1', data, format='json') - with self.assertNumQueries(2): + with self.assertNumQueries(3): response = self.view(request, pk=1).render() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, {'id': 1, 'text': 'foobar'}) @@ -256,88 +252,88 @@ class TestInstanceView(TestCase): ids = [obj.id for obj in self.objects.all()] self.assertEqual(ids, [2, 3]) - def test_options_instance_view(self): - """ - OPTIONS requests to RetrieveUpdateDestroyAPIView should return metadata - """ - request = factory.options('/1') - with self.assertNumQueries(1): - response = self.view(request, pk=1).render() - expected = { - 'parses': [ - 'application/json', - 'application/x-www-form-urlencoded', - 'multipart/form-data' - ], - 'renders': [ - 'application/json', - 'text/html' - ], - 'name': 'Instance', - 'description': 'Example description for OPTIONS.', - 'actions': { - 'PUT': { - 'text': { - 'max_length': 100, - 'read_only': False, - 'required': True, - 'type': 'string', - 'label': 'Text comes here', - 'help_text': 'Text description.' - }, - 'id': { - 'read_only': True, - 'required': False, - 'type': 'integer', - 'label': 'ID', - }, - } - } - } - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEqual(response.data, expected) + # def test_options_instance_view(self): + # """ + # OPTIONS requests to RetrieveUpdateDestroyAPIView should return metadata + # """ + # request = factory.options('/1') + # with self.assertNumQueries(1): + # response = self.view(request, pk=1).render() + # expected = { + # 'parses': [ + # 'application/json', + # 'application/x-www-form-urlencoded', + # 'multipart/form-data' + # ], + # 'renders': [ + # 'application/json', + # 'text/html' + # ], + # 'name': 'Instance', + # 'description': 'Example description for OPTIONS.', + # 'actions': { + # 'PUT': { + # 'text': { + # 'max_length': 100, + # 'read_only': False, + # 'required': True, + # 'type': 'string', + # 'label': 'Text comes here', + # 'help_text': 'Text description.' + # }, + # 'id': { + # 'read_only': True, + # 'required': False, + # 'type': 'integer', + # 'label': 'ID', + # }, + # } + # } + # } + # self.assertEqual(response.status_code, status.HTTP_200_OK) + # self.assertEqual(response.data, expected) - def test_options_before_instance_create(self): - """ - OPTIONS requests to RetrieveUpdateDestroyAPIView should return metadata - before the instance has been created - """ - request = factory.options('/999') - with self.assertNumQueries(1): - response = self.view(request, pk=999).render() - expected = { - 'parses': [ - 'application/json', - 'application/x-www-form-urlencoded', - 'multipart/form-data' - ], - 'renders': [ - 'application/json', - 'text/html' - ], - 'name': 'Instance', - 'description': 'Example description for OPTIONS.', - 'actions': { - 'PUT': { - 'text': { - 'max_length': 100, - 'read_only': False, - 'required': True, - 'type': 'string', - 'label': 'Text comes here', - 'help_text': 'Text description.' - }, - 'id': { - 'read_only': True, - 'required': False, - 'type': 'integer', - 'label': 'ID', - }, - } - } - } - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEqual(response.data, expected) + # def test_options_before_instance_create(self): + # """ + # OPTIONS requests to RetrieveUpdateDestroyAPIView should return metadata + # before the instance has been created + # """ + # request = factory.options('/999') + # with self.assertNumQueries(1): + # response = self.view(request, pk=999).render() + # expected = { + # 'parses': [ + # 'application/json', + # 'application/x-www-form-urlencoded', + # 'multipart/form-data' + # ], + # 'renders': [ + # 'application/json', + # 'text/html' + # ], + # 'name': 'Instance', + # 'description': 'Example description for OPTIONS.', + # 'actions': { + # 'PUT': { + # 'text': { + # 'max_length': 100, + # 'read_only': False, + # 'required': True, + # 'type': 'string', + # 'label': 'Text comes here', + # 'help_text': 'Text description.' + # }, + # 'id': { + # 'read_only': True, + # 'required': False, + # 'type': 'integer', + # 'label': 'ID', + # }, + # } + # } + # } + # self.assertEqual(response.status_code, status.HTTP_200_OK) + # self.assertEqual(response.data, expected) def test_get_instance_view_incorrect_arg(self): """ @@ -355,7 +351,7 @@ class TestInstanceView(TestCase): """ data = {'id': 999, 'text': 'foobar'} request = factory.put('/1', data, format='json') - with self.assertNumQueries(2): + with self.assertNumQueries(3): response = self.view(request, pk=1).render() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, {'id': 1, 'text': 'foobar'}) @@ -370,7 +366,7 @@ class TestInstanceView(TestCase): self.objects.get(id=1).delete() data = {'text': 'foobar'} request = factory.put('/1', data, format='json') - with self.assertNumQueries(3): + with self.assertNumQueries(2): response = self.view(request, pk=1).render() self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data, {'id': 1, 'text': 'foobar'}) @@ -396,7 +392,7 @@ class TestInstanceView(TestCase): data = {'text': 'foobar'} # pk fields can not be created on demand, only the database can set the pk for a new object request = factory.put('/5', data, format='json') - with self.assertNumQueries(3): + with self.assertNumQueries(2): response = self.view(request, pk=5).render() self.assertEqual(response.status_code, status.HTTP_201_CREATED) new_obj = self.objects.get(pk=5) @@ -446,52 +442,52 @@ class TestFKInstanceView(TestCase): ] self.view = FKInstanceView.as_view() - def test_options_root_view(self): - """ - OPTIONS requests to ListCreateAPIView should return metadata - """ - request = factory.options('/999') - with self.assertNumQueries(1): - response = self.view(request, pk=999).render() - expected = { - 'name': 'Fk Instance', - 'description': 'FK: example description for OPTIONS.', - 'renders': [ - 'application/json', - 'text/html' - ], - 'parses': [ - 'application/json', - 'application/x-www-form-urlencoded', - 'multipart/form-data' - ], - 'actions': { - 'PUT': { - 'id': { - 'type': 'integer', - 'required': False, - 'read_only': True, - 'label': 'ID' - }, - 'name': { - 'type': 'string', - 'required': True, - 'read_only': False, - 'label': 'name', - 'max_length': 100 - }, - 'target': { - 'type': 'field', - 'required': True, - 'read_only': False, - 'label': 'Target', - 'help_text': 'Target' - } - } - } - } - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEqual(response.data, expected) + # def test_options_root_view(self): + # """ + # OPTIONS requests to ListCreateAPIView should return metadata + # """ + # request = factory.options('/999') + # with self.assertNumQueries(1): + # response = self.view(request, pk=999).render() + # expected = { + # 'name': 'Fk Instance', + # 'description': 'FK: example description for OPTIONS.', + # 'renders': [ + # 'application/json', + # 'text/html' + # ], + # 'parses': [ + # 'application/json', + # 'application/x-www-form-urlencoded', + # 'multipart/form-data' + # ], + # 'actions': { + # 'PUT': { + # 'id': { + # 'type': 'integer', + # 'required': False, + # 'read_only': True, + # 'label': 'ID' + # }, + # 'name': { + # 'type': 'string', + # 'required': True, + # 'read_only': False, + # 'label': 'name', + # 'max_length': 100 + # }, + # 'target': { + # 'type': 'field', + # 'required': True, + # 'read_only': False, + # 'label': 'Target', + # 'help_text': 'Target' + # } + # } + # } + # } + # self.assertEqual(response.status_code, status.HTTP_200_OK) + # self.assertEqual(response.data, expected) class TestOverriddenGetObject(TestCase): diff --git a/tests/test_hyperlinkedserializers.py b/tests/test_hyperlinkedserializers.py index 0e8c1ed46..ff3663dd3 100644 --- a/tests/test_hyperlinkedserializers.py +++ b/tests/test_hyperlinkedserializers.py @@ -1,406 +1,406 @@ -from __future__ import unicode_literals -import json -from django.test import TestCase -from rest_framework import generics, status, serializers -from django.conf.urls import patterns, url -from rest_framework.settings import api_settings -from rest_framework.test import APIRequestFactory -from tests.models import ( - Anchor, BasicModel, ManyToManyModel, BlogPost, BlogPostComment, - Album, Photo, OptionalRelationModel -) +# from __future__ import unicode_literals +# import json +# from django.test import TestCase +# from rest_framework import generics, status, serializers +# from django.conf.urls import patterns, url +# from rest_framework.settings import api_settings +# from rest_framework.test import APIRequestFactory +# from tests.models import ( +# Anchor, BasicModel, ManyToManyModel, BlogPost, BlogPostComment, +# Album, Photo, OptionalRelationModel +# ) -factory = APIRequestFactory() +# factory = APIRequestFactory() -class BlogPostCommentSerializer(serializers.ModelSerializer): - url = serializers.HyperlinkedIdentityField(view_name='blogpostcomment-detail') - text = serializers.CharField() - blog_post_url = serializers.HyperlinkedRelatedField(source='blog_post', view_name='blogpost-detail') +# class BlogPostCommentSerializer(serializers.ModelSerializer): +# url = serializers.HyperlinkedIdentityField(view_name='blogpostcomment-detail') +# text = serializers.CharField() +# blog_post_url = serializers.HyperlinkedRelatedField(source='blog_post', view_name='blogpost-detail') - class Meta: - model = BlogPostComment - fields = ('text', 'blog_post_url', 'url') +# class Meta: +# model = BlogPostComment +# fields = ('text', 'blog_post_url', 'url') -class PhotoSerializer(serializers.Serializer): - description = serializers.CharField() - album_url = serializers.HyperlinkedRelatedField(source='album', view_name='album-detail', queryset=Album.objects.all(), lookup_field='title') +# class PhotoSerializer(serializers.Serializer): +# description = serializers.CharField() +# album_url = serializers.HyperlinkedRelatedField(source='album', view_name='album-detail', queryset=Album.objects.all(), lookup_field='title') - def restore_object(self, attrs, instance=None): - return Photo(**attrs) +# def restore_object(self, attrs, instance=None): +# return Photo(**attrs) -class AlbumSerializer(serializers.ModelSerializer): - url = serializers.HyperlinkedIdentityField(view_name='album-detail', lookup_field='title') +# class AlbumSerializer(serializers.ModelSerializer): +# url = serializers.HyperlinkedIdentityField(view_name='album-detail', lookup_field='title') - class Meta: - model = Album - fields = ('title', 'url') +# class Meta: +# model = Album +# fields = ('title', 'url') -class BasicSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = BasicModel +# class BasicSerializer(serializers.HyperlinkedModelSerializer): +# class Meta: +# model = BasicModel -class AnchorSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = Anchor +# class AnchorSerializer(serializers.HyperlinkedModelSerializer): +# class Meta: +# model = Anchor -class ManyToManySerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = ManyToManyModel +# class ManyToManySerializer(serializers.HyperlinkedModelSerializer): +# class Meta: +# model = ManyToManyModel -class BlogPostSerializer(serializers.ModelSerializer): - class Meta: - model = BlogPost +# class BlogPostSerializer(serializers.ModelSerializer): +# class Meta: +# model = BlogPost -class OptionalRelationSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = OptionalRelationModel +# class OptionalRelationSerializer(serializers.HyperlinkedModelSerializer): +# class Meta: +# model = OptionalRelationModel -class BasicList(generics.ListCreateAPIView): - queryset = BasicModel.objects.all() - serializer_class = BasicSerializer +# class BasicList(generics.ListCreateAPIView): +# queryset = BasicModel.objects.all() +# serializer_class = BasicSerializer -class BasicDetail(generics.RetrieveUpdateDestroyAPIView): - queryset = BasicModel.objects.all() - serializer_class = BasicSerializer +# class BasicDetail(generics.RetrieveUpdateDestroyAPIView): +# queryset = BasicModel.objects.all() +# serializer_class = BasicSerializer -class AnchorDetail(generics.RetrieveAPIView): - queryset = Anchor.objects.all() - serializer_class = AnchorSerializer +# class AnchorDetail(generics.RetrieveAPIView): +# queryset = Anchor.objects.all() +# serializer_class = AnchorSerializer -class ManyToManyList(generics.ListAPIView): - queryset = ManyToManyModel.objects.all() - serializer_class = ManyToManySerializer +# class ManyToManyList(generics.ListAPIView): +# queryset = ManyToManyModel.objects.all() +# serializer_class = ManyToManySerializer -class ManyToManyDetail(generics.RetrieveAPIView): - queryset = ManyToManyModel.objects.all() - serializer_class = ManyToManySerializer +# class ManyToManyDetail(generics.RetrieveAPIView): +# queryset = ManyToManyModel.objects.all() +# serializer_class = ManyToManySerializer -class BlogPostCommentListCreate(generics.ListCreateAPIView): - queryset = BlogPostComment.objects.all() - serializer_class = BlogPostCommentSerializer +# class BlogPostCommentListCreate(generics.ListCreateAPIView): +# queryset = BlogPostComment.objects.all() +# serializer_class = BlogPostCommentSerializer -class BlogPostCommentDetail(generics.RetrieveAPIView): - queryset = BlogPostComment.objects.all() - serializer_class = BlogPostCommentSerializer +# class BlogPostCommentDetail(generics.RetrieveAPIView): +# queryset = BlogPostComment.objects.all() +# serializer_class = BlogPostCommentSerializer -class BlogPostDetail(generics.RetrieveAPIView): - queryset = BlogPost.objects.all() - serializer_class = BlogPostSerializer +# class BlogPostDetail(generics.RetrieveAPIView): +# queryset = BlogPost.objects.all() +# serializer_class = BlogPostSerializer -class PhotoListCreate(generics.ListCreateAPIView): - queryset = Photo.objects.all() - serializer_class = PhotoSerializer +# class PhotoListCreate(generics.ListCreateAPIView): +# queryset = Photo.objects.all() +# serializer_class = PhotoSerializer -class AlbumDetail(generics.RetrieveAPIView): - queryset = Album.objects.all() - serializer_class = AlbumSerializer - lookup_field = 'title' +# class AlbumDetail(generics.RetrieveAPIView): +# queryset = Album.objects.all() +# serializer_class = AlbumSerializer +# lookup_field = 'title' -class OptionalRelationDetail(generics.RetrieveUpdateDestroyAPIView): - queryset = OptionalRelationModel.objects.all() - serializer_class = OptionalRelationSerializer +# class OptionalRelationDetail(generics.RetrieveUpdateDestroyAPIView): +# queryset = OptionalRelationModel.objects.all() +# serializer_class = OptionalRelationSerializer -urlpatterns = patterns( - '', - url(r'^basic/$', BasicList.as_view(), name='basicmodel-list'), - url(r'^basic/(?P\d+)/$', BasicDetail.as_view(), name='basicmodel-detail'), - url(r'^anchor/(?P\d+)/$', AnchorDetail.as_view(), name='anchor-detail'), - url(r'^manytomany/$', ManyToManyList.as_view(), name='manytomanymodel-list'), - url(r'^manytomany/(?P\d+)/$', ManyToManyDetail.as_view(), name='manytomanymodel-detail'), - url(r'^posts/(?P\d+)/$', BlogPostDetail.as_view(), name='blogpost-detail'), - url(r'^comments/$', BlogPostCommentListCreate.as_view(), name='blogpostcomment-list'), - url(r'^comments/(?P\d+)/$', BlogPostCommentDetail.as_view(), name='blogpostcomment-detail'), - url(r'^albums/(?P\w[\w-]*)/$', AlbumDetail.as_view(), name='album-detail'), - url(r'^photos/$', PhotoListCreate.as_view(), name='photo-list'), - url(r'^optionalrelation/(?P<pk>\d+)/$', OptionalRelationDetail.as_view(), name='optionalrelationmodel-detail'), -) - - -class TestBasicHyperlinkedView(TestCase): - urls = 'tests.test_hyperlinkedserializers' - - 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 = [ - {'url': 'http://testserver/basic/%d/' % obj.id, 'text': obj.text} - for obj in self.objects.all() - ] - self.list_view = BasicList.as_view() - self.detail_view = BasicDetail.as_view() - - def test_get_list_view(self): - """ - GET requests to ListCreateAPIView should return list of objects. - """ - request = factory.get('/basic/') - response = self.list_view(request).render() - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEqual(response.data, self.data) - - def test_get_detail_view(self): - """ - GET requests to ListCreateAPIView should return list of objects. - """ - request = factory.get('/basic/1') - response = self.detail_view(request, pk=1).render() - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEqual(response.data, self.data[0]) - - -class TestManyToManyHyperlinkedView(TestCase): - urls = 'tests.test_hyperlinkedserializers' - - def setUp(self): - """ - Create 3 BasicModel instances. - """ - items = ['foo', 'bar', 'baz'] - anchors = [] - for item in items: - anchor = Anchor(text=item) - anchor.save() - anchors.append(anchor) - - manytomany = ManyToManyModel() - manytomany.save() - manytomany.rel.add(*anchors) - - self.data = [{ - 'url': 'http://testserver/manytomany/1/', - 'rel': [ - 'http://testserver/anchor/1/', - 'http://testserver/anchor/2/', - 'http://testserver/anchor/3/', - ] - }] - self.list_view = ManyToManyList.as_view() - self.detail_view = ManyToManyDetail.as_view() - - def test_get_list_view(self): - """ - GET requests to ListCreateAPIView should return list of objects. - """ - request = factory.get('/manytomany/') - response = self.list_view(request) - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEqual(response.data, self.data) - - def test_get_detail_view(self): - """ - GET requests to ListCreateAPIView should return list of objects. - """ - request = factory.get('/manytomany/1/') - response = self.detail_view(request, pk=1) - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEqual(response.data, self.data[0]) - - -class TestHyperlinkedIdentityFieldLookup(TestCase): - urls = 'tests.test_hyperlinkedserializers' - - def setUp(self): - """ - Create 3 Album instances. - """ - titles = ['foo', 'bar', 'baz'] - for title in titles: - album = Album(title=title) - album.save() - self.detail_view = AlbumDetail.as_view() - self.data = { - 'foo': {'title': 'foo', 'url': 'http://testserver/albums/foo/'}, - 'bar': {'title': 'bar', 'url': 'http://testserver/albums/bar/'}, - 'baz': {'title': 'baz', 'url': 'http://testserver/albums/baz/'} - } - - def test_lookup_field(self): - """ - GET requests to AlbumDetail view should return serialized Albums - with a url field keyed by `title`. - """ - for album in Album.objects.all(): - request = factory.get('/albums/{0}/'.format(album.title)) - response = self.detail_view(request, title=album.title) - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEqual(response.data, self.data[album.title]) - - -class TestCreateWithForeignKeys(TestCase): - urls = 'tests.test_hyperlinkedserializers' - - def setUp(self): - """ - Create a blog post - """ - self.post = BlogPost.objects.create(title="Test post") - self.create_view = BlogPostCommentListCreate.as_view() - - def test_create_comment(self): - - data = { - 'text': 'A test comment', - 'blog_post_url': 'http://testserver/posts/1/' - } - - request = factory.post('/comments/', data=data) - response = self.create_view(request) - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - self.assertEqual(response['Location'], 'http://testserver/comments/1/') - self.assertEqual(self.post.blogpostcomment_set.count(), 1) - self.assertEqual(self.post.blogpostcomment_set.all()[0].text, 'A test comment') - - -class TestCreateWithForeignKeysAndCustomSlug(TestCase): - urls = 'tests.test_hyperlinkedserializers' - - def setUp(self): - """ - Create an Album - """ - self.post = Album.objects.create(title='test-album') - self.list_create_view = PhotoListCreate.as_view() - - def test_create_photo(self): - - data = { - 'description': 'A test photo', - 'album_url': 'http://testserver/albums/test-album/' - } - - request = factory.post('/photos/', data=data) - response = self.list_create_view(request) - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - self.assertNotIn('Location', response, msg='Location should only be included if there is a "url" field on the serializer') - self.assertEqual(self.post.photo_set.count(), 1) - self.assertEqual(self.post.photo_set.all()[0].description, 'A test photo') - - -class TestOptionalRelationHyperlinkedView(TestCase): - urls = 'tests.test_hyperlinkedserializers' - - def setUp(self): - """ - Create 1 OptionalRelationModel instances. - """ - OptionalRelationModel().save() - self.objects = OptionalRelationModel.objects - self.detail_view = OptionalRelationDetail.as_view() - self.data = {"url": "http://testserver/optionalrelation/1/", "other": None} - - def test_get_detail_view(self): - """ - GET requests to RetrieveAPIView with optional relations should return None - for non existing relations. - """ - request = factory.get('/optionalrelationmodel-detail/1') - response = self.detail_view(request, pk=1) - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertEqual(response.data, self.data) - - def test_put_detail_view(self): - """ - PUT requests to RetrieveUpdateDestroyAPIView with optional relations - should accept None for non existing relations. - """ - response = self.client.put('/optionalrelation/1/', - data=json.dumps(self.data), - content_type='application/json') - self.assertEqual(response.status_code, status.HTTP_200_OK) - - -class TestOverriddenURLField(TestCase): - def setUp(self): - class OverriddenURLSerializer(serializers.HyperlinkedModelSerializer): - url = serializers.SerializerMethodField('get_url') - - class Meta: - model = BlogPost - fields = ('title', 'url') - - def get_url(self, obj): - return 'foo bar' - - self.Serializer = OverriddenURLSerializer - self.obj = BlogPost.objects.create(title='New blog post') - - def test_overridden_url_field(self): - """ - The 'url' field should respect overriding. - Regression test for #936. - """ - serializer = self.Serializer(self.obj) - self.assertEqual( - serializer.data, - {'title': 'New blog post', 'url': 'foo bar'} - ) - - -class TestURLFieldNameBySettings(TestCase): - urls = 'tests.test_hyperlinkedserializers' - - def setUp(self): - self.saved_url_field_name = api_settings.URL_FIELD_NAME - api_settings.URL_FIELD_NAME = 'global_url_field' - - class Serializer(serializers.HyperlinkedModelSerializer): - - class Meta: - model = BlogPost - fields = ('title', api_settings.URL_FIELD_NAME) - - self.Serializer = Serializer - self.obj = BlogPost.objects.create(title="New blog post") - - def tearDown(self): - api_settings.URL_FIELD_NAME = self.saved_url_field_name - - def test_overridden_url_field_name(self): - request = factory.get('/posts/') - serializer = self.Serializer(self.obj, context={'request': request}) - self.assertIn(api_settings.URL_FIELD_NAME, serializer.data) - - -class TestURLFieldNameByOptions(TestCase): - urls = 'tests.test_hyperlinkedserializers' - - def setUp(self): - class Serializer(serializers.HyperlinkedModelSerializer): - - class Meta: - model = BlogPost - fields = ('title', 'serializer_url_field') - url_field_name = 'serializer_url_field' - - self.Serializer = Serializer - self.obj = BlogPost.objects.create(title="New blog post") - - def test_overridden_url_field_name(self): - request = factory.get('/posts/') - serializer = self.Serializer(self.obj, context={'request': request}) - self.assertIn(self.Serializer.Meta.url_field_name, serializer.data) +# urlpatterns = patterns( +# '', +# url(r'^basic/$', BasicList.as_view(), name='basicmodel-list'), +# url(r'^basic/(?P<pk>\d+)/$', BasicDetail.as_view(), name='basicmodel-detail'), +# url(r'^anchor/(?P<pk>\d+)/$', AnchorDetail.as_view(), name='anchor-detail'), +# url(r'^manytomany/$', ManyToManyList.as_view(), name='manytomanymodel-list'), +# url(r'^manytomany/(?P<pk>\d+)/$', ManyToManyDetail.as_view(), name='manytomanymodel-detail'), +# url(r'^posts/(?P<pk>\d+)/$', BlogPostDetail.as_view(), name='blogpost-detail'), +# url(r'^comments/$', BlogPostCommentListCreate.as_view(), name='blogpostcomment-list'), +# url(r'^comments/(?P<pk>\d+)/$', BlogPostCommentDetail.as_view(), name='blogpostcomment-detail'), +# url(r'^albums/(?P<title>\w[\w-]*)/$', AlbumDetail.as_view(), name='album-detail'), +# url(r'^photos/$', PhotoListCreate.as_view(), name='photo-list'), +# url(r'^optionalrelation/(?P<pk>\d+)/$', OptionalRelationDetail.as_view(), name='optionalrelationmodel-detail'), +# ) + + +# class TestBasicHyperlinkedView(TestCase): +# urls = 'tests.test_hyperlinkedserializers' + +# 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 = [ +# {'url': 'http://testserver/basic/%d/' % obj.id, 'text': obj.text} +# for obj in self.objects.all() +# ] +# self.list_view = BasicList.as_view() +# self.detail_view = BasicDetail.as_view() + +# def test_get_list_view(self): +# """ +# GET requests to ListCreateAPIView should return list of objects. +# """ +# request = factory.get('/basic/') +# response = self.list_view(request).render() +# self.assertEqual(response.status_code, status.HTTP_200_OK) +# self.assertEqual(response.data, self.data) + +# def test_get_detail_view(self): +# """ +# GET requests to ListCreateAPIView should return list of objects. +# """ +# request = factory.get('/basic/1') +# response = self.detail_view(request, pk=1).render() +# self.assertEqual(response.status_code, status.HTTP_200_OK) +# self.assertEqual(response.data, self.data[0]) + + +# class TestManyToManyHyperlinkedView(TestCase): +# urls = 'tests.test_hyperlinkedserializers' + +# def setUp(self): +# """ +# Create 3 BasicModel instances. +# """ +# items = ['foo', 'bar', 'baz'] +# anchors = [] +# for item in items: +# anchor = Anchor(text=item) +# anchor.save() +# anchors.append(anchor) + +# manytomany = ManyToManyModel() +# manytomany.save() +# manytomany.rel.add(*anchors) + +# self.data = [{ +# 'url': 'http://testserver/manytomany/1/', +# 'rel': [ +# 'http://testserver/anchor/1/', +# 'http://testserver/anchor/2/', +# 'http://testserver/anchor/3/', +# ] +# }] +# self.list_view = ManyToManyList.as_view() +# self.detail_view = ManyToManyDetail.as_view() + +# def test_get_list_view(self): +# """ +# GET requests to ListCreateAPIView should return list of objects. +# """ +# request = factory.get('/manytomany/') +# response = self.list_view(request) +# self.assertEqual(response.status_code, status.HTTP_200_OK) +# self.assertEqual(response.data, self.data) + +# def test_get_detail_view(self): +# """ +# GET requests to ListCreateAPIView should return list of objects. +# """ +# request = factory.get('/manytomany/1/') +# response = self.detail_view(request, pk=1) +# self.assertEqual(response.status_code, status.HTTP_200_OK) +# self.assertEqual(response.data, self.data[0]) + + +# class TestHyperlinkedIdentityFieldLookup(TestCase): +# urls = 'tests.test_hyperlinkedserializers' + +# def setUp(self): +# """ +# Create 3 Album instances. +# """ +# titles = ['foo', 'bar', 'baz'] +# for title in titles: +# album = Album(title=title) +# album.save() +# self.detail_view = AlbumDetail.as_view() +# self.data = { +# 'foo': {'title': 'foo', 'url': 'http://testserver/albums/foo/'}, +# 'bar': {'title': 'bar', 'url': 'http://testserver/albums/bar/'}, +# 'baz': {'title': 'baz', 'url': 'http://testserver/albums/baz/'} +# } + +# def test_lookup_field(self): +# """ +# GET requests to AlbumDetail view should return serialized Albums +# with a url field keyed by `title`. +# """ +# for album in Album.objects.all(): +# request = factory.get('/albums/{0}/'.format(album.title)) +# response = self.detail_view(request, title=album.title) +# self.assertEqual(response.status_code, status.HTTP_200_OK) +# self.assertEqual(response.data, self.data[album.title]) + + +# class TestCreateWithForeignKeys(TestCase): +# urls = 'tests.test_hyperlinkedserializers' + +# def setUp(self): +# """ +# Create a blog post +# """ +# self.post = BlogPost.objects.create(title="Test post") +# self.create_view = BlogPostCommentListCreate.as_view() + +# def test_create_comment(self): + +# data = { +# 'text': 'A test comment', +# 'blog_post_url': 'http://testserver/posts/1/' +# } + +# request = factory.post('/comments/', data=data) +# response = self.create_view(request) +# self.assertEqual(response.status_code, status.HTTP_201_CREATED) +# self.assertEqual(response['Location'], 'http://testserver/comments/1/') +# self.assertEqual(self.post.blogpostcomment_set.count(), 1) +# self.assertEqual(self.post.blogpostcomment_set.all()[0].text, 'A test comment') + + +# class TestCreateWithForeignKeysAndCustomSlug(TestCase): +# urls = 'tests.test_hyperlinkedserializers' + +# def setUp(self): +# """ +# Create an Album +# """ +# self.post = Album.objects.create(title='test-album') +# self.list_create_view = PhotoListCreate.as_view() + +# def test_create_photo(self): + +# data = { +# 'description': 'A test photo', +# 'album_url': 'http://testserver/albums/test-album/' +# } + +# request = factory.post('/photos/', data=data) +# response = self.list_create_view(request) +# self.assertEqual(response.status_code, status.HTTP_201_CREATED) +# self.assertNotIn('Location', response, msg='Location should only be included if there is a "url" field on the serializer') +# self.assertEqual(self.post.photo_set.count(), 1) +# self.assertEqual(self.post.photo_set.all()[0].description, 'A test photo') + + +# class TestOptionalRelationHyperlinkedView(TestCase): +# urls = 'tests.test_hyperlinkedserializers' + +# def setUp(self): +# """ +# Create 1 OptionalRelationModel instances. +# """ +# OptionalRelationModel().save() +# self.objects = OptionalRelationModel.objects +# self.detail_view = OptionalRelationDetail.as_view() +# self.data = {"url": "http://testserver/optionalrelation/1/", "other": None} + +# def test_get_detail_view(self): +# """ +# GET requests to RetrieveAPIView with optional relations should return None +# for non existing relations. +# """ +# request = factory.get('/optionalrelationmodel-detail/1') +# response = self.detail_view(request, pk=1) +# self.assertEqual(response.status_code, status.HTTP_200_OK) +# self.assertEqual(response.data, self.data) + +# def test_put_detail_view(self): +# """ +# PUT requests to RetrieveUpdateDestroyAPIView with optional relations +# should accept None for non existing relations. +# """ +# response = self.client.put('/optionalrelation/1/', +# data=json.dumps(self.data), +# content_type='application/json') +# self.assertEqual(response.status_code, status.HTTP_200_OK) + + +# class TestOverriddenURLField(TestCase): +# def setUp(self): +# class OverriddenURLSerializer(serializers.HyperlinkedModelSerializer): +# url = serializers.SerializerMethodField('get_url') + +# class Meta: +# model = BlogPost +# fields = ('title', 'url') + +# def get_url(self, obj): +# return 'foo bar' + +# self.Serializer = OverriddenURLSerializer +# self.obj = BlogPost.objects.create(title='New blog post') + +# def test_overridden_url_field(self): +# """ +# The 'url' field should respect overriding. +# Regression test for #936. +# """ +# serializer = self.Serializer(self.obj) +# self.assertEqual( +# serializer.data, +# {'title': 'New blog post', 'url': 'foo bar'} +# ) + + +# class TestURLFieldNameBySettings(TestCase): +# urls = 'tests.test_hyperlinkedserializers' + +# def setUp(self): +# self.saved_url_field_name = api_settings.URL_FIELD_NAME +# api_settings.URL_FIELD_NAME = 'global_url_field' + +# class Serializer(serializers.HyperlinkedModelSerializer): + +# class Meta: +# model = BlogPost +# fields = ('title', api_settings.URL_FIELD_NAME) + +# self.Serializer = Serializer +# self.obj = BlogPost.objects.create(title="New blog post") + +# def tearDown(self): +# api_settings.URL_FIELD_NAME = self.saved_url_field_name + +# def test_overridden_url_field_name(self): +# request = factory.get('/posts/') +# serializer = self.Serializer(self.obj, context={'request': request}) +# self.assertIn(api_settings.URL_FIELD_NAME, serializer.data) + + +# class TestURLFieldNameByOptions(TestCase): +# urls = 'tests.test_hyperlinkedserializers' + +# def setUp(self): +# class Serializer(serializers.HyperlinkedModelSerializer): + +# class Meta: +# model = BlogPost +# fields = ('title', 'serializer_url_field') +# url_field_name = 'serializer_url_field' + +# self.Serializer = Serializer +# self.obj = BlogPost.objects.create(title="New blog post") + +# def test_overridden_url_field_name(self): +# request = factory.get('/posts/') +# serializer = self.Serializer(self.obj, context={'request': request}) +# self.assertIn(self.Serializer.Meta.url_field_name, serializer.data) diff --git a/tests/test_nullable_fields.py b/tests/test_nullable_fields.py index 8d0c84bb0..9843182ad 100644 --- a/tests/test_nullable_fields.py +++ b/tests/test_nullable_fields.py @@ -1,39 +1,39 @@ -from django.core.urlresolvers import reverse +# from django.core.urlresolvers import reverse -from django.conf.urls import patterns, url -from rest_framework import serializers, generics -from rest_framework.test import APITestCase -from tests.models import NullableForeignKeySource +# from django.conf.urls import patterns, url +# from rest_framework import serializers, generics +# from rest_framework.test import APITestCase +# from tests.models import NullableForeignKeySource -class NullableFKSourceSerializer(serializers.ModelSerializer): - class Meta: - model = NullableForeignKeySource +# class NullableFKSourceSerializer(serializers.ModelSerializer): +# class Meta: +# model = NullableForeignKeySource -class NullableFKSourceDetail(generics.RetrieveUpdateDestroyAPIView): - queryset = NullableForeignKeySource.objects.all() - serializer_class = NullableFKSourceSerializer +# class NullableFKSourceDetail(generics.RetrieveUpdateDestroyAPIView): +# queryset = NullableForeignKeySource.objects.all() +# serializer_class = NullableFKSourceSerializer -urlpatterns = patterns( - '', - url(r'^objects/(?P<pk>\d+)/$', NullableFKSourceDetail.as_view(), name='object-detail'), -) +# urlpatterns = patterns( +# '', +# url(r'^objects/(?P<pk>\d+)/$', NullableFKSourceDetail.as_view(), name='object-detail'), +# ) -class NullableForeignKeyTests(APITestCase): - """ - DRF should be able to handle nullable foreign keys when a test - Client POST/PUT request is made with its own serialized object. - """ - urls = 'tests.test_nullable_fields' +# class NullableForeignKeyTests(APITestCase): +# """ +# DRF should be able to handle nullable foreign keys when a test +# Client POST/PUT request is made with its own serialized object. +# """ +# urls = 'tests.test_nullable_fields' - def test_updating_object_with_null_fk(self): - obj = NullableForeignKeySource(name='example', target=None) - obj.save() - serialized_data = NullableFKSourceSerializer(obj).data +# def test_updating_object_with_null_fk(self): +# obj = NullableForeignKeySource(name='example', target=None) +# obj.save() +# serialized_data = NullableFKSourceSerializer(obj).data - response = self.client.put(reverse('object-detail', args=[obj.pk]), serialized_data) +# response = self.client.put(reverse('object-detail', args=[obj.pk]), serialized_data) - self.assertEqual(response.data, serialized_data) +# self.assertEqual(response.data, serialized_data) diff --git a/tests/test_pagination.py b/tests/test_pagination.py index 8f9e0005e..2e56d9709 100644 --- a/tests/test_pagination.py +++ b/tests/test_pagination.py @@ -391,10 +391,10 @@ class CustomField(serializers.Field): class BasicModelSerializer(serializers.Serializer): text = CustomField() - def __init__(self, *args, **kwargs): - super(BasicModelSerializer, self).__init__(*args, **kwargs) + def to_native(self, value): if 'view' not in self.context: - raise RuntimeError("context isn't getting passed into serializer init") + raise RuntimeError("context isn't getting passed into serializer") + return super(BasicSerializer, self).to_native(value) class TestContextPassedToCustomField(TestCase): @@ -423,7 +423,7 @@ class LinksSerializer(serializers.Serializer): class CustomPaginationSerializer(pagination.BasePaginationSerializer): links = LinksSerializer(source='*') # Takes the page object as the source - total_results = serializers.Field(source='paginator.count') + total_results = serializers.ReadOnlyField(source='paginator.count') results_field = 'objects' diff --git a/tests/test_permissions.py b/tests/test_permissions.py index b90ba4f19..d5568c551 100644 --- a/tests/test_permissions.py +++ b/tests/test_permissions.py @@ -108,59 +108,59 @@ class ModelPermissionsIntegrationTests(TestCase): response = instance_view(request, pk='2') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) - def test_options_permitted(self): - request = factory.options( - '/', - HTTP_AUTHORIZATION=self.permitted_credentials - ) - response = root_view(request, pk='1') - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertIn('actions', response.data) - self.assertEqual(list(response.data['actions'].keys()), ['POST']) + # def test_options_permitted(self): + # request = factory.options( + # '/', + # HTTP_AUTHORIZATION=self.permitted_credentials + # ) + # response = root_view(request, pk='1') + # self.assertEqual(response.status_code, status.HTTP_200_OK) + # self.assertIn('actions', response.data) + # self.assertEqual(list(response.data['actions'].keys()), ['POST']) - request = factory.options( - '/1', - HTTP_AUTHORIZATION=self.permitted_credentials - ) - response = instance_view(request, pk='1') - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertIn('actions', response.data) - self.assertEqual(list(response.data['actions'].keys()), ['PUT']) + # request = factory.options( + # '/1', + # HTTP_AUTHORIZATION=self.permitted_credentials + # ) + # response = instance_view(request, pk='1') + # self.assertEqual(response.status_code, status.HTTP_200_OK) + # self.assertIn('actions', response.data) + # self.assertEqual(list(response.data['actions'].keys()), ['PUT']) - def test_options_disallowed(self): - request = factory.options( - '/', - HTTP_AUTHORIZATION=self.disallowed_credentials - ) - response = root_view(request, pk='1') - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertNotIn('actions', response.data) + # def test_options_disallowed(self): + # request = factory.options( + # '/', + # HTTP_AUTHORIZATION=self.disallowed_credentials + # ) + # response = root_view(request, pk='1') + # self.assertEqual(response.status_code, status.HTTP_200_OK) + # self.assertNotIn('actions', response.data) - request = factory.options( - '/1', - HTTP_AUTHORIZATION=self.disallowed_credentials - ) - response = instance_view(request, pk='1') - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertNotIn('actions', response.data) + # request = factory.options( + # '/1', + # HTTP_AUTHORIZATION=self.disallowed_credentials + # ) + # response = instance_view(request, pk='1') + # self.assertEqual(response.status_code, status.HTTP_200_OK) + # self.assertNotIn('actions', response.data) - def test_options_updateonly(self): - request = factory.options( - '/', - HTTP_AUTHORIZATION=self.updateonly_credentials - ) - response = root_view(request, pk='1') - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertNotIn('actions', response.data) + # def test_options_updateonly(self): + # request = factory.options( + # '/', + # HTTP_AUTHORIZATION=self.updateonly_credentials + # ) + # response = root_view(request, pk='1') + # self.assertEqual(response.status_code, status.HTTP_200_OK) + # self.assertNotIn('actions', response.data) - request = factory.options( - '/1', - HTTP_AUTHORIZATION=self.updateonly_credentials - ) - response = instance_view(request, pk='1') - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertIn('actions', response.data) - self.assertEqual(list(response.data['actions'].keys()), ['PUT']) + # request = factory.options( + # '/1', + # HTTP_AUTHORIZATION=self.updateonly_credentials + # ) + # response = instance_view(request, pk='1') + # self.assertEqual(response.status_code, status.HTTP_200_OK) + # self.assertIn('actions', response.data) + # self.assertEqual(list(response.data['actions'].keys()), ['PUT']) class BasicPermModel(models.Model): diff --git a/tests/test_relations.py b/tests/test_relations.py index bc1db69fc..a30b12e68 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -1,149 +1,149 @@ -""" -General tests for relational fields. -""" -from __future__ import unicode_literals -from django import get_version -from django.db import models -from django.test import TestCase -from django.utils import unittest -from rest_framework import serializers -from tests.models import BlogPost +# """ +# General tests for relational fields. +# """ +# from __future__ import unicode_literals +# from django import get_version +# from django.db import models +# from django.test import TestCase +# from django.utils import unittest +# from rest_framework import serializers +# from tests.models import BlogPost -class NullModel(models.Model): - pass +# class NullModel(models.Model): +# pass -class FieldTests(TestCase): - def test_pk_related_field_with_empty_string(self): - """ - Regression test for #446 +# class FieldTests(TestCase): +# def test_pk_related_field_with_empty_string(self): +# """ +# Regression test for #446 - https://github.com/tomchristie/django-rest-framework/issues/446 - """ - field = serializers.PrimaryKeyRelatedField(queryset=NullModel.objects.all()) - self.assertRaises(serializers.ValidationError, field.from_native, '') - self.assertRaises(serializers.ValidationError, field.from_native, []) +# https://github.com/tomchristie/django-rest-framework/issues/446 +# """ +# field = serializers.PrimaryKeyRelatedField(queryset=NullModel.objects.all()) +# self.assertRaises(serializers.ValidationError, field.from_native, '') +# self.assertRaises(serializers.ValidationError, field.from_native, []) - def test_hyperlinked_related_field_with_empty_string(self): - field = serializers.HyperlinkedRelatedField(queryset=NullModel.objects.all(), view_name='') - self.assertRaises(serializers.ValidationError, field.from_native, '') - self.assertRaises(serializers.ValidationError, field.from_native, []) +# def test_hyperlinked_related_field_with_empty_string(self): +# field = serializers.HyperlinkedRelatedField(queryset=NullModel.objects.all(), view_name='') +# self.assertRaises(serializers.ValidationError, field.from_native, '') +# self.assertRaises(serializers.ValidationError, field.from_native, []) - def test_slug_related_field_with_empty_string(self): - field = serializers.SlugRelatedField(queryset=NullModel.objects.all(), slug_field='pk') - self.assertRaises(serializers.ValidationError, field.from_native, '') - self.assertRaises(serializers.ValidationError, field.from_native, []) +# def test_slug_related_field_with_empty_string(self): +# field = serializers.SlugRelatedField(queryset=NullModel.objects.all(), slug_field='pk') +# self.assertRaises(serializers.ValidationError, field.from_native, '') +# self.assertRaises(serializers.ValidationError, field.from_native, []) -class TestManyRelatedMixin(TestCase): - def test_missing_many_to_many_related_field(self): - ''' - Regression test for #632 +# class TestManyRelatedMixin(TestCase): +# def test_missing_many_to_many_related_field(self): +# ''' +# Regression test for #632 - https://github.com/tomchristie/django-rest-framework/pull/632 - ''' - field = serializers.RelatedField(many=True, read_only=False) +# https://github.com/tomchristie/django-rest-framework/pull/632 +# ''' +# field = serializers.RelatedField(many=True, read_only=False) - into = {} - field.field_from_native({}, None, 'field_name', into) - self.assertEqual(into['field_name'], []) +# into = {} +# field.field_from_native({}, None, 'field_name', into) +# self.assertEqual(into['field_name'], []) -# Regression tests for #694 (`source` attribute on related fields) +# # Regression tests for #694 (`source` attribute on related fields) -class RelatedFieldSourceTests(TestCase): - def test_related_manager_source(self): - """ - Relational fields should be able to use manager-returning methods as their source. - """ - BlogPost.objects.create(title='blah') - field = serializers.RelatedField(many=True, source='get_blogposts_manager') +# class RelatedFieldSourceTests(TestCase): +# def test_related_manager_source(self): +# """ +# Relational fields should be able to use manager-returning methods as their source. +# """ +# BlogPost.objects.create(title='blah') +# field = serializers.RelatedField(many=True, source='get_blogposts_manager') - class ClassWithManagerMethod(object): - def get_blogposts_manager(self): - return BlogPost.objects +# class ClassWithManagerMethod(object): +# def get_blogposts_manager(self): +# return BlogPost.objects - obj = ClassWithManagerMethod() - value = field.field_to_native(obj, 'field_name') - self.assertEqual(value, ['BlogPost object']) +# obj = ClassWithManagerMethod() +# value = field.field_to_native(obj, 'field_name') +# self.assertEqual(value, ['BlogPost object']) - def test_related_queryset_source(self): - """ - Relational fields should be able to use queryset-returning methods as their source. - """ - BlogPost.objects.create(title='blah') - field = serializers.RelatedField(many=True, source='get_blogposts_queryset') +# def test_related_queryset_source(self): +# """ +# Relational fields should be able to use queryset-returning methods as their source. +# """ +# BlogPost.objects.create(title='blah') +# field = serializers.RelatedField(many=True, source='get_blogposts_queryset') - class ClassWithQuerysetMethod(object): - def get_blogposts_queryset(self): - return BlogPost.objects.all() +# class ClassWithQuerysetMethod(object): +# def get_blogposts_queryset(self): +# return BlogPost.objects.all() - obj = ClassWithQuerysetMethod() - value = field.field_to_native(obj, 'field_name') - self.assertEqual(value, ['BlogPost object']) +# obj = ClassWithQuerysetMethod() +# value = field.field_to_native(obj, 'field_name') +# self.assertEqual(value, ['BlogPost object']) - def test_dotted_source(self): - """ - Source argument should support dotted.source notation. - """ - BlogPost.objects.create(title='blah') - field = serializers.RelatedField(many=True, source='a.b.c') +# def test_dotted_source(self): +# """ +# Source argument should support dotted.source notation. +# """ +# BlogPost.objects.create(title='blah') +# field = serializers.RelatedField(many=True, source='a.b.c') - class ClassWithQuerysetMethod(object): - a = { - 'b': { - 'c': BlogPost.objects.all() - } - } +# class ClassWithQuerysetMethod(object): +# a = { +# 'b': { +# 'c': BlogPost.objects.all() +# } +# } - obj = ClassWithQuerysetMethod() - value = field.field_to_native(obj, 'field_name') - self.assertEqual(value, ['BlogPost object']) +# obj = ClassWithQuerysetMethod() +# value = field.field_to_native(obj, 'field_name') +# self.assertEqual(value, ['BlogPost object']) - # Regression for #1129 - def test_exception_for_incorect_fk(self): - """ - Check that the exception message are correct if the source field - doesn't exist. - """ - from tests.models import ManyToManySource +# # Regression for #1129 +# def test_exception_for_incorect_fk(self): +# """ +# Check that the exception message are correct if the source field +# doesn't exist. +# """ +# from tests.models import ManyToManySource - class Meta: - model = ManyToManySource +# class Meta: +# model = ManyToManySource - attrs = { - 'name': serializers.SlugRelatedField( - slug_field='name', source='banzai'), - 'Meta': Meta, - } +# attrs = { +# 'name': serializers.SlugRelatedField( +# slug_field='name', source='banzai'), +# 'Meta': Meta, +# } - TestSerializer = type( - str('TestSerializer'), - (serializers.ModelSerializer,), - attrs - ) - with self.assertRaises(AttributeError): - TestSerializer(data={'name': 'foo'}) +# TestSerializer = type( +# str('TestSerializer'), +# (serializers.ModelSerializer,), +# attrs +# ) +# with self.assertRaises(AttributeError): +# TestSerializer(data={'name': 'foo'}) -@unittest.skipIf(get_version() < '1.6.0', 'Upstream behaviour changed in v1.6') -class RelatedFieldChoicesTests(TestCase): - """ - Tests for #1408 "Web browseable API doesn't have blank option on drop down list box" - https://github.com/tomchristie/django-rest-framework/issues/1408 - """ - def test_blank_option_is_added_to_choice_if_required_equals_false(self): - """ +# @unittest.skipIf(get_version() < '1.6.0', 'Upstream behaviour changed in v1.6') +# class RelatedFieldChoicesTests(TestCase): +# """ +# Tests for #1408 "Web browseable API doesn't have blank option on drop down list box" +# https://github.com/tomchristie/django-rest-framework/issues/1408 +# """ +# def test_blank_option_is_added_to_choice_if_required_equals_false(self): +# """ - """ - post = BlogPost(title="Checking blank option is added") - post.save() +# """ +# post = BlogPost(title="Checking blank option is added") +# post.save() - queryset = BlogPost.objects.all() - field = serializers.RelatedField(required=False, queryset=queryset) +# queryset = BlogPost.objects.all() +# field = serializers.RelatedField(required=False, queryset=queryset) - choice_count = BlogPost.objects.count() - widget_count = len(field.widget.choices) +# choice_count = BlogPost.objects.count() +# widget_count = len(field.widget.choices) - self.assertEqual(widget_count, choice_count + 1, 'BLANK_CHOICE_DASH option should have been added') +# self.assertEqual(widget_count, choice_count + 1, 'BLANK_CHOICE_DASH option should have been added') diff --git a/tests/test_relations_hyperlink.py b/tests/test_relations_hyperlink.py index 0c8eb2544..315d1abf8 100644 --- a/tests/test_relations_hyperlink.py +++ b/tests/test_relations_hyperlink.py @@ -1,525 +1,525 @@ -from __future__ import unicode_literals -from django.conf.urls import patterns, url -from django.test import TestCase -from rest_framework import serializers -from rest_framework.test import APIRequestFactory -from tests.models import ( - BlogPost, - ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, - NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource -) - -factory = APIRequestFactory() -request = factory.get('/') # Just to ensure we have a request in the serializer context - - -def dummy_view(request, pk): - pass - -urlpatterns = patterns( - '', - url(r'^dummyurl/(?P<pk>[0-9]+)/$', dummy_view, name='dummy-url'), - url(r'^manytomanysource/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanysource-detail'), - url(r'^manytomanytarget/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanytarget-detail'), - url(r'^foreignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeysource-detail'), - url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'), - url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'), - url(r'^onetoonetarget/(?P<pk>[0-9]+)/$', dummy_view, name='onetoonetarget-detail'), - url(r'^nullableonetoonesource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableonetoonesource-detail'), -) - - -# ManyToMany -class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = ManyToManyTarget - fields = ('url', 'name', 'sources') - - -class ManyToManySourceSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = ManyToManySource - fields = ('url', 'name', 'targets') - - -# ForeignKey -class ForeignKeyTargetSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = ForeignKeyTarget - fields = ('url', 'name', 'sources') - - -class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = ForeignKeySource - fields = ('url', 'name', 'target') - - -# Nullable ForeignKey -class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = NullableForeignKeySource - fields = ('url', 'name', 'target') - - -# Nullable OneToOne -class NullableOneToOneTargetSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = OneToOneTarget - fields = ('url', 'name', 'nullable_source') - - -# TODO: Add test that .data cannot be accessed prior to .is_valid - -class HyperlinkedManyToManyTests(TestCase): - urls = 'tests.test_relations_hyperlink' - - def setUp(self): - for idx in range(1, 4): - target = ManyToManyTarget(name='target-%d' % idx) - target.save() - source = ManyToManySource(name='source-%d' % idx) - source.save() - for target in ManyToManyTarget.objects.all(): - source.targets.add(target) - - def test_many_to_many_retrieve(self): - queryset = ManyToManySource.objects.all() - serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']}, - {'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) - - def test_reverse_many_to_many_retrieve(self): - queryset = ManyToManyTarget.objects.all() - serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']}, - {'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) - - 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/']} - instance = ManyToManySource.objects.get(pk=1) - serializer = ManyToManySourceSerializer(instance, data=data, context={'request': request}) - self.assertTrue(serializer.is_valid()) - serializer.save() - self.assertEqual(serializer.data, data) - - # Ensure source 1 is updated, and everything else is as expected - queryset = ManyToManySource.objects.all() - serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}, - {'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) - - def test_reverse_many_to_many_update(self): - data = {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']} - instance = ManyToManyTarget.objects.get(pk=1) - serializer = ManyToManyTargetSerializer(instance, data=data, context={'request': request}) - self.assertTrue(serializer.is_valid()) - serializer.save() - self.assertEqual(serializer.data, data) - - # Ensure target 1 is updated, and everything else is as expected - queryset = ManyToManyTarget.objects.all() - serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']}, - {'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) - - def test_many_to_many_create(self): - data = {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']} - serializer = ManyToManySourceSerializer(data=data, context={'request': request}) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'source-4') - - # Ensure source 4 is added, and everything else is as expected - queryset = ManyToManySource.objects.all() - serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']}, - {'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/']}, - {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']} - ] - self.assertEqual(serializer.data, expected) - - def test_reverse_many_to_many_create(self): - data = {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']} - serializer = ManyToManyTargetSerializer(data=data, context={'request': request}) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'target-4') - - # Ensure target 4 is added, and everything else is as expected - queryset = ManyToManyTarget.objects.all() - serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']}, - {'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/']}, - {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']} - ] - self.assertEqual(serializer.data, expected) - - -class HyperlinkedForeignKeyTests(TestCase): - urls = 'tests.test_relations_hyperlink' - - def setUp(self): - target = ForeignKeyTarget(name='target-1') - target.save() - new_target = ForeignKeyTarget(name='target-2') - new_target.save() - for idx in range(1, 4): - source = ForeignKeySource(name='source-%d' % idx, target=target) - source.save() - - def test_foreign_key_retrieve(self): - queryset = ForeignKeySource.objects.all() - serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, - {'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) - - def test_reverse_foreign_key_retrieve(self): - queryset = ForeignKeyTarget.objects.all() - serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'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) - - def test_foreign_key_update(self): - data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'} - instance = ForeignKeySource.objects.get(pk=1) - serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request}) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.data, data) - serializer.save() - - # Ensure source 1 is updated, and everything else is as expected - queryset = ForeignKeySource.objects.all() - serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'}, - {'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) - - def test_foreign_key_update_incorrect_type(self): - data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 2} - instance = ForeignKeySource.objects.get(pk=1) - serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request}) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'target': ['Incorrect type. Expected url string, received int.']}) - - def test_reverse_foreign_key_update(self): - data = {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']} - instance = ForeignKeyTarget.objects.get(pk=2) - serializer = ForeignKeyTargetSerializer(instance, data=data, context={'request': request}) - self.assertTrue(serializer.is_valid()) - # We shouldn't have saved anything to the db yet since save - # hasn't been called. - queryset = ForeignKeyTarget.objects.all() - new_serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'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(new_serializer.data, expected) - - serializer.save() - self.assertEqual(serializer.data, data) - - # Ensure target 2 is update, and everything else is as expected - queryset = ForeignKeyTarget.objects.all() - serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']}, - {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}, - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_create(self): - data = {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'} - serializer = ForeignKeySourceSerializer(data=data, context={'request': request}) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'source-4') - - # Ensure source 1 is updated, and everything else is as expected - queryset = ForeignKeySource.objects.all() - serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, - {'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/'}, - {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'}, - ] - self.assertEqual(serializer.data, expected) - - def test_reverse_foreign_key_create(self): - data = {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']} - serializer = ForeignKeyTargetSerializer(data=data, context={'request': request}) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'target-3') - - # Ensure target 4 is added, and everything else is as expected - queryset = ForeignKeyTarget.objects.all() - serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']}, - {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []}, - {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}, - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_update_with_invalid_null(self): - data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': None} - instance = ForeignKeySource.objects.get(pk=1) - serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request}) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'target': ['This field is required.']}) - - -class HyperlinkedNullableForeignKeyTests(TestCase): - urls = 'tests.test_relations_hyperlink' - - def setUp(self): - target = ForeignKeyTarget(name='target-1') - target.save() - for idx in range(1, 4): - if idx == 3: - target = None - source = NullableForeignKeySource(name='source-%d' % idx, target=target) - source.save() - - def test_foreign_key_retrieve_with_null(self): - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, - {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, - {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_create_with_valid_null(self): - data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} - serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request}) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'source-4') - - # Ensure source 4 is created, and everything else is as expected - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, - {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, - {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, - {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_create_with_valid_emptystring(self): - """ - The emptystring should be interpreted as null in the context - of relationships. - """ - data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': ''} - expected_data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} - serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request}) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, expected_data) - self.assertEqual(obj.name, 'source-4') - - # Ensure source 4 is created, and everything else is as expected - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, - {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, - {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, - {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_update_with_valid_null(self): - data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None} - instance = NullableForeignKeySource.objects.get(pk=1) - serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request}) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.data, data) - serializer.save() - - # Ensure source 1 is updated, and everything else is as expected - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}, - {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, - {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_update_with_valid_emptystring(self): - """ - The emptystring should be interpreted as null in the context - of relationships. - """ - data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': ''} - expected_data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None} - instance = NullableForeignKeySource.objects.get(pk=1) - serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request}) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.data, expected_data) - serializer.save() - - # Ensure source 1 is updated, and everything else is as expected - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}, - {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, - {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, - ] - self.assertEqual(serializer.data, expected) - - # reverse foreign keys MUST be read_only - # In the general case they do not provide .remove() or .clear() - # and cannot be arbitrarily set. - - # def test_reverse_foreign_key_update(self): - # data = {'id': 1, 'name': 'target-1', 'sources': [1]} - # instance = ForeignKeyTarget.objects.get(pk=1) - # serializer = ForeignKeyTargetSerializer(instance, data=data) - # self.assertTrue(serializer.is_valid()) - # self.assertEqual(serializer.data, data) - # serializer.save() - - # # Ensure target 1 is updated, and everything else is as expected - # queryset = ForeignKeyTarget.objects.all() - # serializer = ForeignKeyTargetSerializer(queryset, many=True) - # expected = [ - # {'id': 1, 'name': 'target-1', 'sources': [1]}, - # {'id': 2, 'name': 'target-2', 'sources': []}, - # ] - # self.assertEqual(serializer.data, expected) - - -class HyperlinkedNullableOneToOneTests(TestCase): - urls = 'tests.test_relations_hyperlink' - - def setUp(self): - target = OneToOneTarget(name='target-1') - target.save() - new_target = OneToOneTarget(name='target-2') - new_target.save() - source = NullableOneToOneSource(name='source-1', target=target) - source.save() - - def test_reverse_foreign_key_retrieve_with_null(self): - queryset = OneToOneTarget.objects.all() - serializer = NullableOneToOneTargetSerializer(queryset, many=True, context={'request': request}) - expected = [ - {'url': 'http://testserver/onetoonetarget/1/', 'name': 'target-1', 'nullable_source': 'http://testserver/nullableonetoonesource/1/'}, - {'url': 'http://testserver/onetoonetarget/2/', 'name': 'target-2', 'nullable_source': None}, - ] - self.assertEqual(serializer.data, expected) - - -# Regression tests for #694 (`source` attribute on related fields) - -class HyperlinkedRelatedFieldSourceTests(TestCase): - urls = 'tests.test_relations_hyperlink' - - def test_related_manager_source(self): - """ - Relational fields should be able to use manager-returning methods as their source. - """ - BlogPost.objects.create(title='blah') - field = serializers.HyperlinkedRelatedField( - many=True, - source='get_blogposts_manager', - view_name='dummy-url', - ) - field.context = {'request': request} - - class ClassWithManagerMethod(object): - def get_blogposts_manager(self): - return BlogPost.objects - - obj = ClassWithManagerMethod() - value = field.field_to_native(obj, 'field_name') - self.assertEqual(value, ['http://testserver/dummyurl/1/']) - - def test_related_queryset_source(self): - """ - Relational fields should be able to use queryset-returning methods as their source. - """ - BlogPost.objects.create(title='blah') - field = serializers.HyperlinkedRelatedField( - many=True, - source='get_blogposts_queryset', - view_name='dummy-url', - ) - field.context = {'request': request} - - class ClassWithQuerysetMethod(object): - def get_blogposts_queryset(self): - return BlogPost.objects.all() - - obj = ClassWithQuerysetMethod() - value = field.field_to_native(obj, 'field_name') - self.assertEqual(value, ['http://testserver/dummyurl/1/']) - - def test_dotted_source(self): - """ - Source argument should support dotted.source notation. - """ - BlogPost.objects.create(title='blah') - field = serializers.HyperlinkedRelatedField( - many=True, - source='a.b.c', - view_name='dummy-url', - ) - field.context = {'request': request} - - class ClassWithQuerysetMethod(object): - a = { - 'b': { - 'c': BlogPost.objects.all() - } - } - - obj = ClassWithQuerysetMethod() - value = field.field_to_native(obj, 'field_name') - self.assertEqual(value, ['http://testserver/dummyurl/1/']) +# from __future__ import unicode_literals +# from django.conf.urls import patterns, url +# from django.test import TestCase +# from rest_framework import serializers +# from rest_framework.test import APIRequestFactory +# from tests.models import ( +# BlogPost, +# ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, +# NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource +# ) + +# factory = APIRequestFactory() +# request = factory.get('/') # Just to ensure we have a request in the serializer context + + +# def dummy_view(request, pk): +# pass + +# urlpatterns = patterns( +# '', +# url(r'^dummyurl/(?P<pk>[0-9]+)/$', dummy_view, name='dummy-url'), +# url(r'^manytomanysource/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanysource-detail'), +# url(r'^manytomanytarget/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanytarget-detail'), +# url(r'^foreignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeysource-detail'), +# url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'), +# url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'), +# url(r'^onetoonetarget/(?P<pk>[0-9]+)/$', dummy_view, name='onetoonetarget-detail'), +# url(r'^nullableonetoonesource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableonetoonesource-detail'), +# ) + + +# # ManyToMany +# class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer): +# class Meta: +# model = ManyToManyTarget +# fields = ('url', 'name', 'sources') + + +# class ManyToManySourceSerializer(serializers.HyperlinkedModelSerializer): +# class Meta: +# model = ManyToManySource +# fields = ('url', 'name', 'targets') + + +# # ForeignKey +# class ForeignKeyTargetSerializer(serializers.HyperlinkedModelSerializer): +# class Meta: +# model = ForeignKeyTarget +# fields = ('url', 'name', 'sources') + + +# class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): +# class Meta: +# model = ForeignKeySource +# fields = ('url', 'name', 'target') + + +# # Nullable ForeignKey +# class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): +# class Meta: +# model = NullableForeignKeySource +# fields = ('url', 'name', 'target') + + +# # Nullable OneToOne +# class NullableOneToOneTargetSerializer(serializers.HyperlinkedModelSerializer): +# class Meta: +# model = OneToOneTarget +# fields = ('url', 'name', 'nullable_source') + + +# # TODO: Add test that .data cannot be accessed prior to .is_valid + +# class HyperlinkedManyToManyTests(TestCase): +# urls = 'tests.test_relations_hyperlink' + +# def setUp(self): +# for idx in range(1, 4): +# target = ManyToManyTarget(name='target-%d' % idx) +# target.save() +# source = ManyToManySource(name='source-%d' % idx) +# source.save() +# for target in ManyToManyTarget.objects.all(): +# source.targets.add(target) + +# def test_many_to_many_retrieve(self): +# queryset = ManyToManySource.objects.all() +# serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']}, +# {'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) + +# def test_reverse_many_to_many_retrieve(self): +# queryset = ManyToManyTarget.objects.all() +# serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']}, +# {'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) + +# 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/']} +# instance = ManyToManySource.objects.get(pk=1) +# serializer = ManyToManySourceSerializer(instance, data=data, context={'request': request}) +# self.assertTrue(serializer.is_valid()) +# serializer.save() +# self.assertEqual(serializer.data, data) + +# # Ensure source 1 is updated, and everything else is as expected +# queryset = ManyToManySource.objects.all() +# serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}, +# {'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) + +# def test_reverse_many_to_many_update(self): +# data = {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']} +# instance = ManyToManyTarget.objects.get(pk=1) +# serializer = ManyToManyTargetSerializer(instance, data=data, context={'request': request}) +# self.assertTrue(serializer.is_valid()) +# serializer.save() +# self.assertEqual(serializer.data, data) + +# # Ensure target 1 is updated, and everything else is as expected +# queryset = ManyToManyTarget.objects.all() +# serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']}, +# {'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) + +# def test_many_to_many_create(self): +# data = {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']} +# serializer = ManyToManySourceSerializer(data=data, context={'request': request}) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'source-4') + +# # Ensure source 4 is added, and everything else is as expected +# queryset = ManyToManySource.objects.all() +# serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']}, +# {'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/']}, +# {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']} +# ] +# self.assertEqual(serializer.data, expected) + +# def test_reverse_many_to_many_create(self): +# data = {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']} +# serializer = ManyToManyTargetSerializer(data=data, context={'request': request}) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'target-4') + +# # Ensure target 4 is added, and everything else is as expected +# queryset = ManyToManyTarget.objects.all() +# serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']}, +# {'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/']}, +# {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']} +# ] +# self.assertEqual(serializer.data, expected) + + +# class HyperlinkedForeignKeyTests(TestCase): +# urls = 'tests.test_relations_hyperlink' + +# def setUp(self): +# target = ForeignKeyTarget(name='target-1') +# target.save() +# new_target = ForeignKeyTarget(name='target-2') +# new_target.save() +# for idx in range(1, 4): +# source = ForeignKeySource(name='source-%d' % idx, target=target) +# source.save() + +# def test_foreign_key_retrieve(self): +# queryset = ForeignKeySource.objects.all() +# serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, +# {'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) + +# def test_reverse_foreign_key_retrieve(self): +# queryset = ForeignKeyTarget.objects.all() +# serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'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) + +# def test_foreign_key_update(self): +# data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'} +# instance = ForeignKeySource.objects.get(pk=1) +# serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request}) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.data, data) +# serializer.save() + +# # Ensure source 1 is updated, and everything else is as expected +# queryset = ForeignKeySource.objects.all() +# serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'}, +# {'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) + +# def test_foreign_key_update_incorrect_type(self): +# data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 2} +# instance = ForeignKeySource.objects.get(pk=1) +# serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request}) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'target': ['Incorrect type. Expected url string, received int.']}) + +# def test_reverse_foreign_key_update(self): +# data = {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']} +# instance = ForeignKeyTarget.objects.get(pk=2) +# serializer = ForeignKeyTargetSerializer(instance, data=data, context={'request': request}) +# self.assertTrue(serializer.is_valid()) +# # We shouldn't have saved anything to the db yet since save +# # hasn't been called. +# queryset = ForeignKeyTarget.objects.all() +# new_serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'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(new_serializer.data, expected) + +# serializer.save() +# self.assertEqual(serializer.data, data) + +# # Ensure target 2 is update, and everything else is as expected +# queryset = ForeignKeyTarget.objects.all() +# serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']}, +# {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}, +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_create(self): +# data = {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'} +# serializer = ForeignKeySourceSerializer(data=data, context={'request': request}) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'source-4') + +# # Ensure source 1 is updated, and everything else is as expected +# queryset = ForeignKeySource.objects.all() +# serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, +# {'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/'}, +# {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'}, +# ] +# self.assertEqual(serializer.data, expected) + +# def test_reverse_foreign_key_create(self): +# data = {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']} +# serializer = ForeignKeyTargetSerializer(data=data, context={'request': request}) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'target-3') + +# # Ensure target 4 is added, and everything else is as expected +# queryset = ForeignKeyTarget.objects.all() +# serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']}, +# {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []}, +# {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}, +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_update_with_invalid_null(self): +# data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': None} +# instance = ForeignKeySource.objects.get(pk=1) +# serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request}) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'target': ['This field is required.']}) + + +# class HyperlinkedNullableForeignKeyTests(TestCase): +# urls = 'tests.test_relations_hyperlink' + +# def setUp(self): +# target = ForeignKeyTarget(name='target-1') +# target.save() +# for idx in range(1, 4): +# if idx == 3: +# target = None +# source = NullableForeignKeySource(name='source-%d' % idx, target=target) +# source.save() + +# def test_foreign_key_retrieve_with_null(self): +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, +# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, +# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_create_with_valid_null(self): +# data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} +# serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request}) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'source-4') + +# # Ensure source 4 is created, and everything else is as expected +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, +# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, +# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, +# {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_create_with_valid_emptystring(self): +# """ +# The emptystring should be interpreted as null in the context +# of relationships. +# """ +# data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': ''} +# expected_data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} +# serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request}) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, expected_data) +# self.assertEqual(obj.name, 'source-4') + +# # Ensure source 4 is created, and everything else is as expected +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, +# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, +# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, +# {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_update_with_valid_null(self): +# data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None} +# instance = NullableForeignKeySource.objects.get(pk=1) +# serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request}) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.data, data) +# serializer.save() + +# # Ensure source 1 is updated, and everything else is as expected +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}, +# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, +# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_update_with_valid_emptystring(self): +# """ +# The emptystring should be interpreted as null in the context +# of relationships. +# """ +# data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': ''} +# expected_data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None} +# instance = NullableForeignKeySource.objects.get(pk=1) +# serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request}) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.data, expected_data) +# serializer.save() + +# # Ensure source 1 is updated, and everything else is as expected +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}, +# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, +# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, +# ] +# self.assertEqual(serializer.data, expected) + +# # reverse foreign keys MUST be read_only +# # In the general case they do not provide .remove() or .clear() +# # and cannot be arbitrarily set. + +# # def test_reverse_foreign_key_update(self): +# # data = {'id': 1, 'name': 'target-1', 'sources': [1]} +# # instance = ForeignKeyTarget.objects.get(pk=1) +# # serializer = ForeignKeyTargetSerializer(instance, data=data) +# # self.assertTrue(serializer.is_valid()) +# # self.assertEqual(serializer.data, data) +# # serializer.save() + +# # # Ensure target 1 is updated, and everything else is as expected +# # queryset = ForeignKeyTarget.objects.all() +# # serializer = ForeignKeyTargetSerializer(queryset, many=True) +# # expected = [ +# # {'id': 1, 'name': 'target-1', 'sources': [1]}, +# # {'id': 2, 'name': 'target-2', 'sources': []}, +# # ] +# # self.assertEqual(serializer.data, expected) + + +# class HyperlinkedNullableOneToOneTests(TestCase): +# urls = 'tests.test_relations_hyperlink' + +# def setUp(self): +# target = OneToOneTarget(name='target-1') +# target.save() +# new_target = OneToOneTarget(name='target-2') +# new_target.save() +# source = NullableOneToOneSource(name='source-1', target=target) +# source.save() + +# def test_reverse_foreign_key_retrieve_with_null(self): +# queryset = OneToOneTarget.objects.all() +# serializer = NullableOneToOneTargetSerializer(queryset, many=True, context={'request': request}) +# expected = [ +# {'url': 'http://testserver/onetoonetarget/1/', 'name': 'target-1', 'nullable_source': 'http://testserver/nullableonetoonesource/1/'}, +# {'url': 'http://testserver/onetoonetarget/2/', 'name': 'target-2', 'nullable_source': None}, +# ] +# self.assertEqual(serializer.data, expected) + + +# # Regression tests for #694 (`source` attribute on related fields) + +# class HyperlinkedRelatedFieldSourceTests(TestCase): +# urls = 'tests.test_relations_hyperlink' + +# def test_related_manager_source(self): +# """ +# Relational fields should be able to use manager-returning methods as their source. +# """ +# BlogPost.objects.create(title='blah') +# field = serializers.HyperlinkedRelatedField( +# many=True, +# source='get_blogposts_manager', +# view_name='dummy-url', +# ) +# field.context = {'request': request} + +# class ClassWithManagerMethod(object): +# def get_blogposts_manager(self): +# return BlogPost.objects + +# obj = ClassWithManagerMethod() +# value = field.field_to_native(obj, 'field_name') +# self.assertEqual(value, ['http://testserver/dummyurl/1/']) + +# def test_related_queryset_source(self): +# """ +# Relational fields should be able to use queryset-returning methods as their source. +# """ +# BlogPost.objects.create(title='blah') +# field = serializers.HyperlinkedRelatedField( +# many=True, +# source='get_blogposts_queryset', +# view_name='dummy-url', +# ) +# field.context = {'request': request} + +# class ClassWithQuerysetMethod(object): +# def get_blogposts_queryset(self): +# return BlogPost.objects.all() + +# obj = ClassWithQuerysetMethod() +# value = field.field_to_native(obj, 'field_name') +# self.assertEqual(value, ['http://testserver/dummyurl/1/']) + +# def test_dotted_source(self): +# """ +# Source argument should support dotted.source notation. +# """ +# BlogPost.objects.create(title='blah') +# field = serializers.HyperlinkedRelatedField( +# many=True, +# source='a.b.c', +# view_name='dummy-url', +# ) +# field.context = {'request': request} + +# class ClassWithQuerysetMethod(object): +# a = { +# 'b': { +# 'c': BlogPost.objects.all() +# } +# } + +# obj = ClassWithQuerysetMethod() +# value = field.field_to_native(obj, 'field_name') +# self.assertEqual(value, ['http://testserver/dummyurl/1/']) diff --git a/tests/test_relations_nested.py b/tests/test_relations_nested.py index 4d9da4896..4a99fee99 100644 --- a/tests/test_relations_nested.py +++ b/tests/test_relations_nested.py @@ -1,326 +1,326 @@ -from __future__ import unicode_literals -from django.db import models -from django.test import TestCase -from rest_framework import serializers +# from __future__ import unicode_literals +# from django.db import models +# from django.test import TestCase +# from rest_framework import serializers -from .models import OneToOneTarget +# from .models import OneToOneTarget -class OneToOneSource(models.Model): - name = models.CharField(max_length=100) - target = models.OneToOneField(OneToOneTarget, related_name='source', - null=True, blank=True) +# class OneToOneSource(models.Model): +# name = models.CharField(max_length=100) +# target = models.OneToOneField(OneToOneTarget, related_name='source', +# null=True, blank=True) -class OneToManyTarget(models.Model): - name = models.CharField(max_length=100) +# class OneToManyTarget(models.Model): +# name = models.CharField(max_length=100) -class OneToManySource(models.Model): - name = models.CharField(max_length=100) - target = models.ForeignKey(OneToManyTarget, related_name='sources') +# class OneToManySource(models.Model): +# name = models.CharField(max_length=100) +# target = models.ForeignKey(OneToManyTarget, related_name='sources') -class ReverseNestedOneToOneTests(TestCase): - def setUp(self): - class OneToOneSourceSerializer(serializers.ModelSerializer): - class Meta: - model = OneToOneSource - fields = ('id', 'name') +# class ReverseNestedOneToOneTests(TestCase): +# def setUp(self): +# class OneToOneSourceSerializer(serializers.ModelSerializer): +# class Meta: +# model = OneToOneSource +# fields = ('id', 'name') - class OneToOneTargetSerializer(serializers.ModelSerializer): - source = OneToOneSourceSerializer() +# class OneToOneTargetSerializer(serializers.ModelSerializer): +# source = OneToOneSourceSerializer() - class Meta: - model = OneToOneTarget - fields = ('id', 'name', 'source') +# class Meta: +# model = OneToOneTarget +# fields = ('id', 'name', 'source') - self.Serializer = OneToOneTargetSerializer +# self.Serializer = OneToOneTargetSerializer - for idx in range(1, 4): - target = OneToOneTarget(name='target-%d' % idx) - target.save() - source = OneToOneSource(name='source-%d' % idx, target=target) - source.save() +# for idx in range(1, 4): +# target = OneToOneTarget(name='target-%d' % idx) +# target.save() +# source = OneToOneSource(name='source-%d' % idx, target=target) +# source.save() - def test_one_to_one_retrieve(self): - queryset = OneToOneTarget.objects.all() - serializer = self.Serializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, - {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, - {'id': 3, 'name': 'target-3', 'source': {'id': 3, 'name': 'source-3'}} - ] - self.assertEqual(serializer.data, expected) +# def test_one_to_one_retrieve(self): +# queryset = OneToOneTarget.objects.all() +# serializer = self.Serializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, +# {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, +# {'id': 3, 'name': 'target-3', 'source': {'id': 3, 'name': 'source-3'}} +# ] +# self.assertEqual(serializer.data, expected) - def test_one_to_one_create(self): - data = {'id': 4, 'name': 'target-4', 'source': {'id': 4, 'name': 'source-4'}} - serializer = self.Serializer(data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'target-4') +# def test_one_to_one_create(self): +# data = {'id': 4, 'name': 'target-4', 'source': {'id': 4, 'name': 'source-4'}} +# serializer = self.Serializer(data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'target-4') - # Ensure (target 4, target_source 4, source 4) are added, and - # everything else is as expected. - queryset = OneToOneTarget.objects.all() - serializer = self.Serializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, - {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, - {'id': 3, 'name': 'target-3', 'source': {'id': 3, 'name': 'source-3'}}, - {'id': 4, 'name': 'target-4', 'source': {'id': 4, 'name': 'source-4'}} - ] - self.assertEqual(serializer.data, expected) +# # Ensure (target 4, target_source 4, source 4) are added, and +# # everything else is as expected. +# queryset = OneToOneTarget.objects.all() +# serializer = self.Serializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, +# {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, +# {'id': 3, 'name': 'target-3', 'source': {'id': 3, 'name': 'source-3'}}, +# {'id': 4, 'name': 'target-4', 'source': {'id': 4, 'name': 'source-4'}} +# ] +# self.assertEqual(serializer.data, expected) - def test_one_to_one_create_with_invalid_data(self): - data = {'id': 4, 'name': 'target-4', 'source': {'id': 4}} - serializer = self.Serializer(data=data) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'source': [{'name': ['This field is required.']}]}) +# def test_one_to_one_create_with_invalid_data(self): +# data = {'id': 4, 'name': 'target-4', 'source': {'id': 4}} +# serializer = self.Serializer(data=data) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'source': [{'name': ['This field is required.']}]}) - def test_one_to_one_update(self): - data = {'id': 3, 'name': 'target-3-updated', 'source': {'id': 3, 'name': 'source-3-updated'}} - instance = OneToOneTarget.objects.get(pk=3) - serializer = self.Serializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'target-3-updated') +# def test_one_to_one_update(self): +# data = {'id': 3, 'name': 'target-3-updated', 'source': {'id': 3, 'name': 'source-3-updated'}} +# instance = OneToOneTarget.objects.get(pk=3) +# serializer = self.Serializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'target-3-updated') - # Ensure (target 3, target_source 3, source 3) are updated, - # and everything else is as expected. - queryset = OneToOneTarget.objects.all() - serializer = self.Serializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, - {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, - {'id': 3, 'name': 'target-3-updated', 'source': {'id': 3, 'name': 'source-3-updated'}} - ] - self.assertEqual(serializer.data, expected) +# # Ensure (target 3, target_source 3, source 3) are updated, +# # and everything else is as expected. +# queryset = OneToOneTarget.objects.all() +# serializer = self.Serializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, +# {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, +# {'id': 3, 'name': 'target-3-updated', 'source': {'id': 3, 'name': 'source-3-updated'}} +# ] +# self.assertEqual(serializer.data, expected) -class ForwardNestedOneToOneTests(TestCase): - def setUp(self): - class OneToOneTargetSerializer(serializers.ModelSerializer): - class Meta: - model = OneToOneTarget - fields = ('id', 'name') +# class ForwardNestedOneToOneTests(TestCase): +# def setUp(self): +# class OneToOneTargetSerializer(serializers.ModelSerializer): +# class Meta: +# model = OneToOneTarget +# fields = ('id', 'name') - class OneToOneSourceSerializer(serializers.ModelSerializer): - target = OneToOneTargetSerializer() +# class OneToOneSourceSerializer(serializers.ModelSerializer): +# target = OneToOneTargetSerializer() - class Meta: - model = OneToOneSource - fields = ('id', 'name', 'target') +# class Meta: +# model = OneToOneSource +# fields = ('id', 'name', 'target') - self.Serializer = OneToOneSourceSerializer +# self.Serializer = OneToOneSourceSerializer - for idx in range(1, 4): - target = OneToOneTarget(name='target-%d' % idx) - target.save() - source = OneToOneSource(name='source-%d' % idx, target=target) - source.save() +# for idx in range(1, 4): +# target = OneToOneTarget(name='target-%d' % idx) +# target.save() +# source = OneToOneSource(name='source-%d' % idx, target=target) +# source.save() - def test_one_to_one_retrieve(self): - queryset = OneToOneSource.objects.all() - serializer = self.Serializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, - {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, - {'id': 3, 'name': 'source-3', 'target': {'id': 3, 'name': 'target-3'}} - ] - self.assertEqual(serializer.data, expected) +# def test_one_to_one_retrieve(self): +# queryset = OneToOneSource.objects.all() +# serializer = self.Serializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, +# {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, +# {'id': 3, 'name': 'source-3', 'target': {'id': 3, 'name': 'target-3'}} +# ] +# self.assertEqual(serializer.data, expected) - def test_one_to_one_create(self): - data = {'id': 4, 'name': 'source-4', 'target': {'id': 4, 'name': 'target-4'}} - serializer = self.Serializer(data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'source-4') +# def test_one_to_one_create(self): +# data = {'id': 4, 'name': 'source-4', 'target': {'id': 4, 'name': 'target-4'}} +# serializer = self.Serializer(data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'source-4') - # Ensure (target 4, target_source 4, source 4) are added, and - # everything else is as expected. - queryset = OneToOneSource.objects.all() - serializer = self.Serializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, - {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, - {'id': 3, 'name': 'source-3', 'target': {'id': 3, 'name': 'target-3'}}, - {'id': 4, 'name': 'source-4', 'target': {'id': 4, 'name': 'target-4'}} - ] - self.assertEqual(serializer.data, expected) +# # Ensure (target 4, target_source 4, source 4) are added, and +# # everything else is as expected. +# queryset = OneToOneSource.objects.all() +# serializer = self.Serializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, +# {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, +# {'id': 3, 'name': 'source-3', 'target': {'id': 3, 'name': 'target-3'}}, +# {'id': 4, 'name': 'source-4', 'target': {'id': 4, 'name': 'target-4'}} +# ] +# self.assertEqual(serializer.data, expected) - def test_one_to_one_create_with_invalid_data(self): - data = {'id': 4, 'name': 'source-4', 'target': {'id': 4}} - serializer = self.Serializer(data=data) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'target': [{'name': ['This field is required.']}]}) +# def test_one_to_one_create_with_invalid_data(self): +# data = {'id': 4, 'name': 'source-4', 'target': {'id': 4}} +# serializer = self.Serializer(data=data) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'target': [{'name': ['This field is required.']}]}) - def test_one_to_one_update(self): - data = {'id': 3, 'name': 'source-3-updated', 'target': {'id': 3, 'name': 'target-3-updated'}} - instance = OneToOneSource.objects.get(pk=3) - serializer = self.Serializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'source-3-updated') +# def test_one_to_one_update(self): +# data = {'id': 3, 'name': 'source-3-updated', 'target': {'id': 3, 'name': 'target-3-updated'}} +# instance = OneToOneSource.objects.get(pk=3) +# serializer = self.Serializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'source-3-updated') - # Ensure (target 3, target_source 3, source 3) are updated, - # and everything else is as expected. - queryset = OneToOneSource.objects.all() - serializer = self.Serializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, - {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, - {'id': 3, 'name': 'source-3-updated', 'target': {'id': 3, 'name': 'target-3-updated'}} - ] - self.assertEqual(serializer.data, expected) +# # Ensure (target 3, target_source 3, source 3) are updated, +# # and everything else is as expected. +# queryset = OneToOneSource.objects.all() +# serializer = self.Serializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, +# {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, +# {'id': 3, 'name': 'source-3-updated', 'target': {'id': 3, 'name': 'target-3-updated'}} +# ] +# self.assertEqual(serializer.data, expected) - def test_one_to_one_update_to_null(self): - data = {'id': 3, 'name': 'source-3-updated', 'target': None} - instance = OneToOneSource.objects.get(pk=3) - serializer = self.Serializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() +# def test_one_to_one_update_to_null(self): +# data = {'id': 3, 'name': 'source-3-updated', 'target': None} +# instance = OneToOneSource.objects.get(pk=3) +# serializer = self.Serializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'source-3-updated') - self.assertEqual(obj.target, None) +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'source-3-updated') +# self.assertEqual(obj.target, None) - queryset = OneToOneSource.objects.all() - serializer = self.Serializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, - {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, - {'id': 3, 'name': 'source-3-updated', 'target': None} - ] - self.assertEqual(serializer.data, expected) +# queryset = OneToOneSource.objects.all() +# serializer = self.Serializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, +# {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, +# {'id': 3, 'name': 'source-3-updated', 'target': None} +# ] +# self.assertEqual(serializer.data, expected) - # TODO: Nullable 1-1 tests - # def test_one_to_one_delete(self): - # data = {'id': 3, 'name': 'target-3', 'target_source': None} - # instance = OneToOneTarget.objects.get(pk=3) - # serializer = self.Serializer(instance, data=data) - # self.assertTrue(serializer.is_valid()) - # serializer.save() +# # TODO: Nullable 1-1 tests +# # def test_one_to_one_delete(self): +# # data = {'id': 3, 'name': 'target-3', 'target_source': None} +# # instance = OneToOneTarget.objects.get(pk=3) +# # serializer = self.Serializer(instance, data=data) +# # self.assertTrue(serializer.is_valid()) +# # serializer.save() - # # Ensure (target_source 3, source 3) are deleted, - # # and everything else is as expected. - # queryset = OneToOneTarget.objects.all() - # serializer = self.Serializer(queryset) - # expected = [ - # {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, - # {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, - # {'id': 3, 'name': 'target-3', 'source': None} - # ] - # self.assertEqual(serializer.data, expected) +# # # Ensure (target_source 3, source 3) are deleted, +# # # and everything else is as expected. +# # queryset = OneToOneTarget.objects.all() +# # serializer = self.Serializer(queryset) +# # expected = [ +# # {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, +# # {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, +# # {'id': 3, 'name': 'target-3', 'source': None} +# # ] +# # self.assertEqual(serializer.data, expected) -class ReverseNestedOneToManyTests(TestCase): - def setUp(self): - class OneToManySourceSerializer(serializers.ModelSerializer): - class Meta: - model = OneToManySource - fields = ('id', 'name') +# class ReverseNestedOneToManyTests(TestCase): +# def setUp(self): +# class OneToManySourceSerializer(serializers.ModelSerializer): +# class Meta: +# model = OneToManySource +# fields = ('id', 'name') - class OneToManyTargetSerializer(serializers.ModelSerializer): - sources = OneToManySourceSerializer(many=True, allow_add_remove=True) +# class OneToManyTargetSerializer(serializers.ModelSerializer): +# sources = OneToManySourceSerializer(many=True, allow_add_remove=True) - class Meta: - model = OneToManyTarget - fields = ('id', 'name', 'sources') +# class Meta: +# model = OneToManyTarget +# fields = ('id', 'name', 'sources') - self.Serializer = OneToManyTargetSerializer +# self.Serializer = OneToManyTargetSerializer - target = OneToManyTarget(name='target-1') - target.save() - for idx in range(1, 4): - source = OneToManySource(name='source-%d' % idx, target=target) - source.save() +# target = OneToManyTarget(name='target-1') +# target.save() +# for idx in range(1, 4): +# source = OneToManySource(name='source-%d' % idx, target=target) +# source.save() - def test_one_to_many_retrieve(self): - queryset = OneToManyTarget.objects.all() - serializer = self.Serializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, - {'id': 2, 'name': 'source-2'}, - {'id': 3, 'name': 'source-3'}]}, - ] - self.assertEqual(serializer.data, expected) +# def test_one_to_many_retrieve(self): +# queryset = OneToManyTarget.objects.all() +# serializer = self.Serializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, +# {'id': 2, 'name': 'source-2'}, +# {'id': 3, 'name': 'source-3'}]}, +# ] +# self.assertEqual(serializer.data, expected) - def test_one_to_many_create(self): - data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, - {'id': 2, 'name': 'source-2'}, - {'id': 3, 'name': 'source-3'}, - {'id': 4, 'name': 'source-4'}]} - instance = OneToManyTarget.objects.get(pk=1) - serializer = self.Serializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'target-1') +# def test_one_to_many_create(self): +# data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, +# {'id': 2, 'name': 'source-2'}, +# {'id': 3, 'name': 'source-3'}, +# {'id': 4, 'name': 'source-4'}]} +# instance = OneToManyTarget.objects.get(pk=1) +# serializer = self.Serializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'target-1') - # Ensure source 4 is added, and everything else is as - # expected. - queryset = OneToManyTarget.objects.all() - serializer = self.Serializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, - {'id': 2, 'name': 'source-2'}, - {'id': 3, 'name': 'source-3'}, - {'id': 4, 'name': 'source-4'}]} - ] - self.assertEqual(serializer.data, expected) +# # Ensure source 4 is added, and everything else is as +# # expected. +# queryset = OneToManyTarget.objects.all() +# serializer = self.Serializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, +# {'id': 2, 'name': 'source-2'}, +# {'id': 3, 'name': 'source-3'}, +# {'id': 4, 'name': 'source-4'}]} +# ] +# self.assertEqual(serializer.data, expected) - def test_one_to_many_create_with_invalid_data(self): - data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, - {'id': 2, 'name': 'source-2'}, - {'id': 3, 'name': 'source-3'}, - {'id': 4}]} - serializer = self.Serializer(data=data) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'sources': [{}, {}, {}, {'name': ['This field is required.']}]}) +# def test_one_to_many_create_with_invalid_data(self): +# data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, +# {'id': 2, 'name': 'source-2'}, +# {'id': 3, 'name': 'source-3'}, +# {'id': 4}]} +# serializer = self.Serializer(data=data) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'sources': [{}, {}, {}, {'name': ['This field is required.']}]}) - def test_one_to_many_update(self): - data = {'id': 1, 'name': 'target-1-updated', 'sources': [{'id': 1, 'name': 'source-1-updated'}, - {'id': 2, 'name': 'source-2'}, - {'id': 3, 'name': 'source-3'}]} - instance = OneToManyTarget.objects.get(pk=1) - serializer = self.Serializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'target-1-updated') +# def test_one_to_many_update(self): +# data = {'id': 1, 'name': 'target-1-updated', 'sources': [{'id': 1, 'name': 'source-1-updated'}, +# {'id': 2, 'name': 'source-2'}, +# {'id': 3, 'name': 'source-3'}]} +# instance = OneToManyTarget.objects.get(pk=1) +# serializer = self.Serializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'target-1-updated') - # Ensure (target 1, source 1) are updated, - # and everything else is as expected. - queryset = OneToManyTarget.objects.all() - serializer = self.Serializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1-updated', 'sources': [{'id': 1, 'name': 'source-1-updated'}, - {'id': 2, 'name': 'source-2'}, - {'id': 3, 'name': 'source-3'}]} +# # Ensure (target 1, source 1) are updated, +# # and everything else is as expected. +# queryset = OneToManyTarget.objects.all() +# serializer = self.Serializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1-updated', 'sources': [{'id': 1, 'name': 'source-1-updated'}, +# {'id': 2, 'name': 'source-2'}, +# {'id': 3, 'name': 'source-3'}]} - ] - self.assertEqual(serializer.data, expected) +# ] +# self.assertEqual(serializer.data, expected) - def test_one_to_many_delete(self): - data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, - {'id': 3, 'name': 'source-3'}]} - instance = OneToManyTarget.objects.get(pk=1) - serializer = self.Serializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - serializer.save() +# def test_one_to_many_delete(self): +# data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, +# {'id': 3, 'name': 'source-3'}]} +# instance = OneToManyTarget.objects.get(pk=1) +# serializer = self.Serializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# serializer.save() - # Ensure source 2 is deleted, and everything else is as - # expected. - queryset = OneToManyTarget.objects.all() - serializer = self.Serializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, - {'id': 3, 'name': 'source-3'}]} +# # Ensure source 2 is deleted, and everything else is as +# # expected. +# queryset = OneToManyTarget.objects.all() +# serializer = self.Serializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, +# {'id': 3, 'name': 'source-3'}]} - ] - self.assertEqual(serializer.data, expected) +# ] +# self.assertEqual(serializer.data, expected) diff --git a/tests/test_relations_pk.py b/tests/test_relations_pk.py index e3f836ed6..031a79b32 100644 --- a/tests/test_relations_pk.py +++ b/tests/test_relations_pk.py @@ -1,551 +1,551 @@ -from __future__ import unicode_literals -from django.db import models -from django.test import TestCase -from django.utils import six -from rest_framework import serializers -from tests.models import ( - BlogPost, ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, - NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource, -) - - -# ManyToMany -class ManyToManyTargetSerializer(serializers.ModelSerializer): - class Meta: - model = ManyToManyTarget - fields = ('id', 'name', 'sources') - - -class ManyToManySourceSerializer(serializers.ModelSerializer): - class Meta: - model = ManyToManySource - fields = ('id', 'name', 'targets') - - -# ForeignKey -class ForeignKeyTargetSerializer(serializers.ModelSerializer): - class Meta: - model = ForeignKeyTarget - fields = ('id', 'name', 'sources') - - -class ForeignKeySourceSerializer(serializers.ModelSerializer): - class Meta: - model = ForeignKeySource - fields = ('id', 'name', 'target') - - -# Nullable ForeignKey -class NullableForeignKeySourceSerializer(serializers.ModelSerializer): - class Meta: - model = NullableForeignKeySource - fields = ('id', 'name', 'target') - - -# Nullable OneToOne -class NullableOneToOneTargetSerializer(serializers.ModelSerializer): - class Meta: - model = OneToOneTarget - fields = ('id', 'name', 'nullable_source') - - -# TODO: Add test that .data cannot be accessed prior to .is_valid - -class PKManyToManyTests(TestCase): - def setUp(self): - for idx in range(1, 4): - target = ManyToManyTarget(name='target-%d' % idx) - target.save() - source = ManyToManySource(name='source-%d' % idx) - source.save() - for target in ManyToManyTarget.objects.all(): - source.targets.add(target) - - def test_many_to_many_retrieve(self): - queryset = ManyToManySource.objects.all() - serializer = ManyToManySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'targets': [1]}, - {'id': 2, 'name': 'source-2', 'targets': [1, 2]}, - {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]} - ] - self.assertEqual(serializer.data, expected) - - def test_reverse_many_to_many_retrieve(self): - queryset = ManyToManyTarget.objects.all() - serializer = ManyToManyTargetSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, - {'id': 2, 'name': 'target-2', 'sources': [2, 3]}, - {'id': 3, 'name': 'target-3', 'sources': [3]} - ] - self.assertEqual(serializer.data, expected) - - def test_many_to_many_update(self): - data = {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]} - instance = ManyToManySource.objects.get(pk=1) - serializer = ManyToManySourceSerializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - serializer.save() - self.assertEqual(serializer.data, data) - - # Ensure source 1 is updated, and everything else is as expected - queryset = ManyToManySource.objects.all() - serializer = ManyToManySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]}, - {'id': 2, 'name': 'source-2', 'targets': [1, 2]}, - {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]} - ] - self.assertEqual(serializer.data, expected) - - def test_reverse_many_to_many_update(self): - data = {'id': 1, 'name': 'target-1', 'sources': [1]} - instance = ManyToManyTarget.objects.get(pk=1) - serializer = ManyToManyTargetSerializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - serializer.save() - self.assertEqual(serializer.data, data) - - # Ensure target 1 is updated, and everything else is as expected - queryset = ManyToManyTarget.objects.all() - serializer = ManyToManyTargetSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': [1]}, - {'id': 2, 'name': 'target-2', 'sources': [2, 3]}, - {'id': 3, 'name': 'target-3', 'sources': [3]} - ] - self.assertEqual(serializer.data, expected) - - def test_many_to_many_create(self): - data = {'id': 4, 'name': 'source-4', 'targets': [1, 3]} - serializer = ManyToManySourceSerializer(data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'source-4') - - # Ensure source 4 is added, and everything else is as expected - queryset = ManyToManySource.objects.all() - serializer = ManyToManySourceSerializer(queryset, many=True) - self.assertFalse(serializer.fields['targets'].read_only) - expected = [ - {'id': 1, 'name': 'source-1', 'targets': [1]}, - {'id': 2, 'name': 'source-2', 'targets': [1, 2]}, - {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]}, - {'id': 4, 'name': 'source-4', 'targets': [1, 3]}, - ] - self.assertEqual(serializer.data, expected) - - def test_reverse_many_to_many_create(self): - data = {'id': 4, 'name': 'target-4', 'sources': [1, 3]} - serializer = ManyToManyTargetSerializer(data=data) - self.assertFalse(serializer.fields['sources'].read_only) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'target-4') - - # Ensure target 4 is added, and everything else is as expected - queryset = ManyToManyTarget.objects.all() - serializer = ManyToManyTargetSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, - {'id': 2, 'name': 'target-2', 'sources': [2, 3]}, - {'id': 3, 'name': 'target-3', 'sources': [3]}, - {'id': 4, 'name': 'target-4', 'sources': [1, 3]} - ] - self.assertEqual(serializer.data, expected) - - -class PKForeignKeyTests(TestCase): - def setUp(self): - target = ForeignKeyTarget(name='target-1') - target.save() - new_target = ForeignKeyTarget(name='target-2') - new_target.save() - for idx in range(1, 4): - source = ForeignKeySource(name='source-%d' % idx, target=target) - source.save() - - def test_foreign_key_retrieve(self): - queryset = ForeignKeySource.objects.all() - serializer = ForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': 1}, - {'id': 2, 'name': 'source-2', 'target': 1}, - {'id': 3, 'name': 'source-3', 'target': 1} - ] - self.assertEqual(serializer.data, expected) - - def test_reverse_foreign_key_retrieve(self): - queryset = ForeignKeyTarget.objects.all() - serializer = ForeignKeyTargetSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, - {'id': 2, 'name': 'target-2', 'sources': []}, - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_update(self): - data = {'id': 1, 'name': 'source-1', 'target': 2} - instance = ForeignKeySource.objects.get(pk=1) - serializer = ForeignKeySourceSerializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.data, data) - serializer.save() - - # Ensure source 1 is updated, and everything else is as expected - queryset = ForeignKeySource.objects.all() - serializer = ForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': 2}, - {'id': 2, 'name': 'source-2', 'target': 1}, - {'id': 3, 'name': 'source-3', 'target': 1} - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_update_incorrect_type(self): - data = {'id': 1, 'name': 'source-1', 'target': 'foo'} - instance = ForeignKeySource.objects.get(pk=1) - serializer = ForeignKeySourceSerializer(instance, data=data) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'target': ['Incorrect type. Expected pk value, received %s.' % six.text_type.__name__]}) - - def test_reverse_foreign_key_update(self): - data = {'id': 2, 'name': 'target-2', 'sources': [1, 3]} - instance = ForeignKeyTarget.objects.get(pk=2) - serializer = ForeignKeyTargetSerializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - # We shouldn't have saved anything to the db yet since save - # hasn't been called. - queryset = ForeignKeyTarget.objects.all() - new_serializer = ForeignKeyTargetSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, - {'id': 2, 'name': 'target-2', 'sources': []}, - ] - self.assertEqual(new_serializer.data, expected) - - serializer.save() - self.assertEqual(serializer.data, data) - - # Ensure target 2 is update, and everything else is as expected - queryset = ForeignKeyTarget.objects.all() - serializer = ForeignKeyTargetSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': [2]}, - {'id': 2, 'name': 'target-2', 'sources': [1, 3]}, - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_create(self): - data = {'id': 4, 'name': 'source-4', 'target': 2} - serializer = ForeignKeySourceSerializer(data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'source-4') - - # Ensure source 4 is added, and everything else is as expected - queryset = ForeignKeySource.objects.all() - serializer = ForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': 1}, - {'id': 2, 'name': 'source-2', 'target': 1}, - {'id': 3, 'name': 'source-3', 'target': 1}, - {'id': 4, 'name': 'source-4', 'target': 2}, - ] - self.assertEqual(serializer.data, expected) - - def test_reverse_foreign_key_create(self): - data = {'id': 3, 'name': 'target-3', 'sources': [1, 3]} - serializer = ForeignKeyTargetSerializer(data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'target-3') - - # Ensure target 3 is added, and everything else is as expected - queryset = ForeignKeyTarget.objects.all() - serializer = ForeignKeyTargetSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': [2]}, - {'id': 2, 'name': 'target-2', 'sources': []}, - {'id': 3, 'name': 'target-3', 'sources': [1, 3]}, - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_update_with_invalid_null(self): - data = {'id': 1, 'name': 'source-1', 'target': None} - instance = ForeignKeySource.objects.get(pk=1) - serializer = ForeignKeySourceSerializer(instance, data=data) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'target': ['This field is required.']}) - - def test_foreign_key_with_empty(self): - """ - Regression test for #1072 - - https://github.com/tomchristie/django-rest-framework/issues/1072 - """ - serializer = NullableForeignKeySourceSerializer() - self.assertEqual(serializer.data['target'], None) - - -class PKNullableForeignKeyTests(TestCase): - def setUp(self): - target = ForeignKeyTarget(name='target-1') - target.save() - for idx in range(1, 4): - if idx == 3: - target = None - source = NullableForeignKeySource(name='source-%d' % idx, target=target) - source.save() - - def test_foreign_key_retrieve_with_null(self): - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': 1}, - {'id': 2, 'name': 'source-2', 'target': 1}, - {'id': 3, 'name': 'source-3', 'target': None}, - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_create_with_valid_null(self): - data = {'id': 4, 'name': 'source-4', 'target': None} - serializer = NullableForeignKeySourceSerializer(data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'source-4') - - # Ensure source 4 is created, and everything else is as expected - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': 1}, - {'id': 2, 'name': 'source-2', 'target': 1}, - {'id': 3, 'name': 'source-3', 'target': None}, - {'id': 4, 'name': 'source-4', 'target': None} - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_create_with_valid_emptystring(self): - """ - The emptystring should be interpreted as null in the context - of relationships. - """ - data = {'id': 4, 'name': 'source-4', 'target': ''} - expected_data = {'id': 4, 'name': 'source-4', 'target': None} - serializer = NullableForeignKeySourceSerializer(data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, expected_data) - self.assertEqual(obj.name, 'source-4') - - # Ensure source 4 is created, and everything else is as expected - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': 1}, - {'id': 2, 'name': 'source-2', 'target': 1}, - {'id': 3, 'name': 'source-3', 'target': None}, - {'id': 4, 'name': 'source-4', 'target': None} - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_update_with_valid_null(self): - data = {'id': 1, 'name': 'source-1', 'target': None} - instance = NullableForeignKeySource.objects.get(pk=1) - serializer = NullableForeignKeySourceSerializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.data, data) - serializer.save() - - # Ensure source 1 is updated, and everything else is as expected - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': None}, - {'id': 2, 'name': 'source-2', 'target': 1}, - {'id': 3, 'name': 'source-3', 'target': None} - ] - self.assertEqual(serializer.data, expected) - - def test_foreign_key_update_with_valid_emptystring(self): - """ - The emptystring should be interpreted as null in the context - of relationships. - """ - data = {'id': 1, 'name': 'source-1', 'target': ''} - expected_data = {'id': 1, 'name': 'source-1', 'target': None} - instance = NullableForeignKeySource.objects.get(pk=1) - serializer = NullableForeignKeySourceSerializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.data, expected_data) - serializer.save() - - # Ensure source 1 is updated, and everything else is as expected - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': None}, - {'id': 2, 'name': 'source-2', 'target': 1}, - {'id': 3, 'name': 'source-3', 'target': None} - ] - self.assertEqual(serializer.data, expected) - - # reverse foreign keys MUST be read_only - # In the general case they do not provide .remove() or .clear() - # and cannot be arbitrarily set. - - # def test_reverse_foreign_key_update(self): - # data = {'id': 1, 'name': 'target-1', 'sources': [1]} - # instance = ForeignKeyTarget.objects.get(pk=1) - # serializer = ForeignKeyTargetSerializer(instance, data=data) - # self.assertTrue(serializer.is_valid()) - # self.assertEqual(serializer.data, data) - # serializer.save() - - # # Ensure target 1 is updated, and everything else is as expected - # queryset = ForeignKeyTarget.objects.all() - # serializer = ForeignKeyTargetSerializer(queryset, many=True) - # expected = [ - # {'id': 1, 'name': 'target-1', 'sources': [1]}, - # {'id': 2, 'name': 'target-2', 'sources': []}, - # ] - # self.assertEqual(serializer.data, expected) - - -class PKNullableOneToOneTests(TestCase): - def setUp(self): - target = OneToOneTarget(name='target-1') - target.save() - new_target = OneToOneTarget(name='target-2') - new_target.save() - source = NullableOneToOneSource(name='source-1', target=new_target) - source.save() - - def test_reverse_foreign_key_retrieve_with_null(self): - queryset = OneToOneTarget.objects.all() - serializer = NullableOneToOneTargetSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'nullable_source': None}, - {'id': 2, 'name': 'target-2', 'nullable_source': 1}, - ] - self.assertEqual(serializer.data, expected) - - -# The below models and tests ensure that serializer fields corresponding -# to a ManyToManyField field with a user-specified ``through`` model are -# set to read only - - -class ManyToManyThroughTarget(models.Model): - name = models.CharField(max_length=100) - - -class ManyToManyThrough(models.Model): - source = models.ForeignKey('ManyToManyThroughSource') - target = models.ForeignKey(ManyToManyThroughTarget) - - -class ManyToManyThroughSource(models.Model): - name = models.CharField(max_length=100) - targets = models.ManyToManyField(ManyToManyThroughTarget, - related_name='sources', - through='ManyToManyThrough') - - -class ManyToManyThroughTargetSerializer(serializers.ModelSerializer): - class Meta: - model = ManyToManyThroughTarget - fields = ('id', 'name', 'sources') - - -class ManyToManyThroughSourceSerializer(serializers.ModelSerializer): - class Meta: - model = ManyToManyThroughSource - fields = ('id', 'name', 'targets') - - -class PKManyToManyThroughTests(TestCase): - def setUp(self): - self.source = ManyToManyThroughSource.objects.create( - name='through-source-1') - self.target = ManyToManyThroughTarget.objects.create( - name='through-target-1') - - def test_many_to_many_create(self): - data = {'id': 2, 'name': 'source-2', 'targets': [self.target.pk]} - serializer = ManyToManyThroughSourceSerializer(data=data) - self.assertTrue(serializer.fields['targets'].read_only) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(obj.name, 'source-2') - self.assertEqual(obj.targets.count(), 0) - - def test_many_to_many_reverse_create(self): - data = {'id': 2, 'name': 'target-2', 'sources': [self.source.pk]} - serializer = ManyToManyThroughTargetSerializer(data=data) - self.assertTrue(serializer.fields['sources'].read_only) - self.assertTrue(serializer.is_valid()) - serializer.save() - obj = serializer.save() - self.assertEqual(obj.name, 'target-2') - self.assertEqual(obj.sources.count(), 0) - - -# Regression tests for #694 (`source` attribute on related fields) - - -class PrimaryKeyRelatedFieldSourceTests(TestCase): - def test_related_manager_source(self): - """ - Relational fields should be able to use manager-returning methods as their source. - """ - BlogPost.objects.create(title='blah') - field = serializers.PrimaryKeyRelatedField(many=True, source='get_blogposts_manager') - - class ClassWithManagerMethod(object): - def get_blogposts_manager(self): - return BlogPost.objects - - obj = ClassWithManagerMethod() - value = field.field_to_native(obj, 'field_name') - self.assertEqual(value, [1]) - - def test_related_queryset_source(self): - """ - Relational fields should be able to use queryset-returning methods as their source. - """ - BlogPost.objects.create(title='blah') - field = serializers.PrimaryKeyRelatedField(many=True, source='get_blogposts_queryset') - - class ClassWithQuerysetMethod(object): - def get_blogposts_queryset(self): - return BlogPost.objects.all() - - obj = ClassWithQuerysetMethod() - value = field.field_to_native(obj, 'field_name') - self.assertEqual(value, [1]) - - def test_dotted_source(self): - """ - Source argument should support dotted.source notation. - """ - BlogPost.objects.create(title='blah') - field = serializers.PrimaryKeyRelatedField(many=True, source='a.b.c') - - class ClassWithQuerysetMethod(object): - a = { - 'b': { - 'c': BlogPost.objects.all() - } - } - - obj = ClassWithQuerysetMethod() - value = field.field_to_native(obj, 'field_name') - self.assertEqual(value, [1]) +# from __future__ import unicode_literals +# from django.db import models +# from django.test import TestCase +# from django.utils import six +# from rest_framework import serializers +# from tests.models import ( +# BlogPost, ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, +# NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource, +# ) + + +# # ManyToMany +# class ManyToManyTargetSerializer(serializers.ModelSerializer): +# class Meta: +# model = ManyToManyTarget +# fields = ('id', 'name', 'sources') + + +# class ManyToManySourceSerializer(serializers.ModelSerializer): +# class Meta: +# model = ManyToManySource +# fields = ('id', 'name', 'targets') + + +# # ForeignKey +# class ForeignKeyTargetSerializer(serializers.ModelSerializer): +# class Meta: +# model = ForeignKeyTarget +# fields = ('id', 'name', 'sources') + + +# class ForeignKeySourceSerializer(serializers.ModelSerializer): +# class Meta: +# model = ForeignKeySource +# fields = ('id', 'name', 'target') + + +# # Nullable ForeignKey +# class NullableForeignKeySourceSerializer(serializers.ModelSerializer): +# class Meta: +# model = NullableForeignKeySource +# fields = ('id', 'name', 'target') + + +# # Nullable OneToOne +# class NullableOneToOneTargetSerializer(serializers.ModelSerializer): +# class Meta: +# model = OneToOneTarget +# fields = ('id', 'name', 'nullable_source') + + +# # TODO: Add test that .data cannot be accessed prior to .is_valid + +# class PKManyToManyTests(TestCase): +# def setUp(self): +# for idx in range(1, 4): +# target = ManyToManyTarget(name='target-%d' % idx) +# target.save() +# source = ManyToManySource(name='source-%d' % idx) +# source.save() +# for target in ManyToManyTarget.objects.all(): +# source.targets.add(target) + +# def test_many_to_many_retrieve(self): +# queryset = ManyToManySource.objects.all() +# serializer = ManyToManySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'targets': [1]}, +# {'id': 2, 'name': 'source-2', 'targets': [1, 2]}, +# {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]} +# ] +# self.assertEqual(serializer.data, expected) + +# def test_reverse_many_to_many_retrieve(self): +# queryset = ManyToManyTarget.objects.all() +# serializer = ManyToManyTargetSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, +# {'id': 2, 'name': 'target-2', 'sources': [2, 3]}, +# {'id': 3, 'name': 'target-3', 'sources': [3]} +# ] +# self.assertEqual(serializer.data, expected) + +# def test_many_to_many_update(self): +# data = {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]} +# instance = ManyToManySource.objects.get(pk=1) +# serializer = ManyToManySourceSerializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# serializer.save() +# self.assertEqual(serializer.data, data) + +# # Ensure source 1 is updated, and everything else is as expected +# queryset = ManyToManySource.objects.all() +# serializer = ManyToManySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]}, +# {'id': 2, 'name': 'source-2', 'targets': [1, 2]}, +# {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]} +# ] +# self.assertEqual(serializer.data, expected) + +# def test_reverse_many_to_many_update(self): +# data = {'id': 1, 'name': 'target-1', 'sources': [1]} +# instance = ManyToManyTarget.objects.get(pk=1) +# serializer = ManyToManyTargetSerializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# serializer.save() +# self.assertEqual(serializer.data, data) + +# # Ensure target 1 is updated, and everything else is as expected +# queryset = ManyToManyTarget.objects.all() +# serializer = ManyToManyTargetSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': [1]}, +# {'id': 2, 'name': 'target-2', 'sources': [2, 3]}, +# {'id': 3, 'name': 'target-3', 'sources': [3]} +# ] +# self.assertEqual(serializer.data, expected) + +# def test_many_to_many_create(self): +# data = {'id': 4, 'name': 'source-4', 'targets': [1, 3]} +# serializer = ManyToManySourceSerializer(data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'source-4') + +# # Ensure source 4 is added, and everything else is as expected +# queryset = ManyToManySource.objects.all() +# serializer = ManyToManySourceSerializer(queryset, many=True) +# self.assertFalse(serializer.fields['targets'].read_only) +# expected = [ +# {'id': 1, 'name': 'source-1', 'targets': [1]}, +# {'id': 2, 'name': 'source-2', 'targets': [1, 2]}, +# {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]}, +# {'id': 4, 'name': 'source-4', 'targets': [1, 3]}, +# ] +# self.assertEqual(serializer.data, expected) + +# def test_reverse_many_to_many_create(self): +# data = {'id': 4, 'name': 'target-4', 'sources': [1, 3]} +# serializer = ManyToManyTargetSerializer(data=data) +# self.assertFalse(serializer.fields['sources'].read_only) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'target-4') + +# # Ensure target 4 is added, and everything else is as expected +# queryset = ManyToManyTarget.objects.all() +# serializer = ManyToManyTargetSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, +# {'id': 2, 'name': 'target-2', 'sources': [2, 3]}, +# {'id': 3, 'name': 'target-3', 'sources': [3]}, +# {'id': 4, 'name': 'target-4', 'sources': [1, 3]} +# ] +# self.assertEqual(serializer.data, expected) + + +# class PKForeignKeyTests(TestCase): +# def setUp(self): +# target = ForeignKeyTarget(name='target-1') +# target.save() +# new_target = ForeignKeyTarget(name='target-2') +# new_target.save() +# for idx in range(1, 4): +# source = ForeignKeySource(name='source-%d' % idx, target=target) +# source.save() + +# def test_foreign_key_retrieve(self): +# queryset = ForeignKeySource.objects.all() +# serializer = ForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': 1}, +# {'id': 2, 'name': 'source-2', 'target': 1}, +# {'id': 3, 'name': 'source-3', 'target': 1} +# ] +# self.assertEqual(serializer.data, expected) + +# def test_reverse_foreign_key_retrieve(self): +# queryset = ForeignKeyTarget.objects.all() +# serializer = ForeignKeyTargetSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, +# {'id': 2, 'name': 'target-2', 'sources': []}, +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_update(self): +# data = {'id': 1, 'name': 'source-1', 'target': 2} +# instance = ForeignKeySource.objects.get(pk=1) +# serializer = ForeignKeySourceSerializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.data, data) +# serializer.save() + +# # Ensure source 1 is updated, and everything else is as expected +# queryset = ForeignKeySource.objects.all() +# serializer = ForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': 2}, +# {'id': 2, 'name': 'source-2', 'target': 1}, +# {'id': 3, 'name': 'source-3', 'target': 1} +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_update_incorrect_type(self): +# data = {'id': 1, 'name': 'source-1', 'target': 'foo'} +# instance = ForeignKeySource.objects.get(pk=1) +# serializer = ForeignKeySourceSerializer(instance, data=data) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'target': ['Incorrect type. Expected pk value, received %s.' % six.text_type.__name__]}) + +# def test_reverse_foreign_key_update(self): +# data = {'id': 2, 'name': 'target-2', 'sources': [1, 3]} +# instance = ForeignKeyTarget.objects.get(pk=2) +# serializer = ForeignKeyTargetSerializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# # We shouldn't have saved anything to the db yet since save +# # hasn't been called. +# queryset = ForeignKeyTarget.objects.all() +# new_serializer = ForeignKeyTargetSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, +# {'id': 2, 'name': 'target-2', 'sources': []}, +# ] +# self.assertEqual(new_serializer.data, expected) + +# serializer.save() +# self.assertEqual(serializer.data, data) + +# # Ensure target 2 is update, and everything else is as expected +# queryset = ForeignKeyTarget.objects.all() +# serializer = ForeignKeyTargetSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': [2]}, +# {'id': 2, 'name': 'target-2', 'sources': [1, 3]}, +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_create(self): +# data = {'id': 4, 'name': 'source-4', 'target': 2} +# serializer = ForeignKeySourceSerializer(data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'source-4') + +# # Ensure source 4 is added, and everything else is as expected +# queryset = ForeignKeySource.objects.all() +# serializer = ForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': 1}, +# {'id': 2, 'name': 'source-2', 'target': 1}, +# {'id': 3, 'name': 'source-3', 'target': 1}, +# {'id': 4, 'name': 'source-4', 'target': 2}, +# ] +# self.assertEqual(serializer.data, expected) + +# def test_reverse_foreign_key_create(self): +# data = {'id': 3, 'name': 'target-3', 'sources': [1, 3]} +# serializer = ForeignKeyTargetSerializer(data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'target-3') + +# # Ensure target 3 is added, and everything else is as expected +# queryset = ForeignKeyTarget.objects.all() +# serializer = ForeignKeyTargetSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': [2]}, +# {'id': 2, 'name': 'target-2', 'sources': []}, +# {'id': 3, 'name': 'target-3', 'sources': [1, 3]}, +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_update_with_invalid_null(self): +# data = {'id': 1, 'name': 'source-1', 'target': None} +# instance = ForeignKeySource.objects.get(pk=1) +# serializer = ForeignKeySourceSerializer(instance, data=data) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'target': ['This field is required.']}) + +# def test_foreign_key_with_empty(self): +# """ +# Regression test for #1072 + +# https://github.com/tomchristie/django-rest-framework/issues/1072 +# """ +# serializer = NullableForeignKeySourceSerializer() +# self.assertEqual(serializer.data['target'], None) + + +# class PKNullableForeignKeyTests(TestCase): +# def setUp(self): +# target = ForeignKeyTarget(name='target-1') +# target.save() +# for idx in range(1, 4): +# if idx == 3: +# target = None +# source = NullableForeignKeySource(name='source-%d' % idx, target=target) +# source.save() + +# def test_foreign_key_retrieve_with_null(self): +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': 1}, +# {'id': 2, 'name': 'source-2', 'target': 1}, +# {'id': 3, 'name': 'source-3', 'target': None}, +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_create_with_valid_null(self): +# data = {'id': 4, 'name': 'source-4', 'target': None} +# serializer = NullableForeignKeySourceSerializer(data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'source-4') + +# # Ensure source 4 is created, and everything else is as expected +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': 1}, +# {'id': 2, 'name': 'source-2', 'target': 1}, +# {'id': 3, 'name': 'source-3', 'target': None}, +# {'id': 4, 'name': 'source-4', 'target': None} +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_create_with_valid_emptystring(self): +# """ +# The emptystring should be interpreted as null in the context +# of relationships. +# """ +# data = {'id': 4, 'name': 'source-4', 'target': ''} +# expected_data = {'id': 4, 'name': 'source-4', 'target': None} +# serializer = NullableForeignKeySourceSerializer(data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, expected_data) +# self.assertEqual(obj.name, 'source-4') + +# # Ensure source 4 is created, and everything else is as expected +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': 1}, +# {'id': 2, 'name': 'source-2', 'target': 1}, +# {'id': 3, 'name': 'source-3', 'target': None}, +# {'id': 4, 'name': 'source-4', 'target': None} +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_update_with_valid_null(self): +# data = {'id': 1, 'name': 'source-1', 'target': None} +# instance = NullableForeignKeySource.objects.get(pk=1) +# serializer = NullableForeignKeySourceSerializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.data, data) +# serializer.save() + +# # Ensure source 1 is updated, and everything else is as expected +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': None}, +# {'id': 2, 'name': 'source-2', 'target': 1}, +# {'id': 3, 'name': 'source-3', 'target': None} +# ] +# self.assertEqual(serializer.data, expected) + +# def test_foreign_key_update_with_valid_emptystring(self): +# """ +# The emptystring should be interpreted as null in the context +# of relationships. +# """ +# data = {'id': 1, 'name': 'source-1', 'target': ''} +# expected_data = {'id': 1, 'name': 'source-1', 'target': None} +# instance = NullableForeignKeySource.objects.get(pk=1) +# serializer = NullableForeignKeySourceSerializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.data, expected_data) +# serializer.save() + +# # Ensure source 1 is updated, and everything else is as expected +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': None}, +# {'id': 2, 'name': 'source-2', 'target': 1}, +# {'id': 3, 'name': 'source-3', 'target': None} +# ] +# self.assertEqual(serializer.data, expected) + +# # reverse foreign keys MUST be read_only +# # In the general case they do not provide .remove() or .clear() +# # and cannot be arbitrarily set. + +# # def test_reverse_foreign_key_update(self): +# # data = {'id': 1, 'name': 'target-1', 'sources': [1]} +# # instance = ForeignKeyTarget.objects.get(pk=1) +# # serializer = ForeignKeyTargetSerializer(instance, data=data) +# # self.assertTrue(serializer.is_valid()) +# # self.assertEqual(serializer.data, data) +# # serializer.save() + +# # # Ensure target 1 is updated, and everything else is as expected +# # queryset = ForeignKeyTarget.objects.all() +# # serializer = ForeignKeyTargetSerializer(queryset, many=True) +# # expected = [ +# # {'id': 1, 'name': 'target-1', 'sources': [1]}, +# # {'id': 2, 'name': 'target-2', 'sources': []}, +# # ] +# # self.assertEqual(serializer.data, expected) + + +# class PKNullableOneToOneTests(TestCase): +# def setUp(self): +# target = OneToOneTarget(name='target-1') +# target.save() +# new_target = OneToOneTarget(name='target-2') +# new_target.save() +# source = NullableOneToOneSource(name='source-1', target=new_target) +# source.save() + +# def test_reverse_foreign_key_retrieve_with_null(self): +# queryset = OneToOneTarget.objects.all() +# serializer = NullableOneToOneTargetSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'nullable_source': None}, +# {'id': 2, 'name': 'target-2', 'nullable_source': 1}, +# ] +# self.assertEqual(serializer.data, expected) + + +# # The below models and tests ensure that serializer fields corresponding +# # to a ManyToManyField field with a user-specified ``through`` model are +# # set to read only + + +# class ManyToManyThroughTarget(models.Model): +# name = models.CharField(max_length=100) + + +# class ManyToManyThrough(models.Model): +# source = models.ForeignKey('ManyToManyThroughSource') +# target = models.ForeignKey(ManyToManyThroughTarget) + + +# class ManyToManyThroughSource(models.Model): +# name = models.CharField(max_length=100) +# targets = models.ManyToManyField(ManyToManyThroughTarget, +# related_name='sources', +# through='ManyToManyThrough') + + +# class ManyToManyThroughTargetSerializer(serializers.ModelSerializer): +# class Meta: +# model = ManyToManyThroughTarget +# fields = ('id', 'name', 'sources') + + +# class ManyToManyThroughSourceSerializer(serializers.ModelSerializer): +# class Meta: +# model = ManyToManyThroughSource +# fields = ('id', 'name', 'targets') + + +# class PKManyToManyThroughTests(TestCase): +# def setUp(self): +# self.source = ManyToManyThroughSource.objects.create( +# name='through-source-1') +# self.target = ManyToManyThroughTarget.objects.create( +# name='through-target-1') + +# def test_many_to_many_create(self): +# data = {'id': 2, 'name': 'source-2', 'targets': [self.target.pk]} +# serializer = ManyToManyThroughSourceSerializer(data=data) +# self.assertTrue(serializer.fields['targets'].read_only) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(obj.name, 'source-2') +# self.assertEqual(obj.targets.count(), 0) + +# def test_many_to_many_reverse_create(self): +# data = {'id': 2, 'name': 'target-2', 'sources': [self.source.pk]} +# serializer = ManyToManyThroughTargetSerializer(data=data) +# self.assertTrue(serializer.fields['sources'].read_only) +# self.assertTrue(serializer.is_valid()) +# serializer.save() +# obj = serializer.save() +# self.assertEqual(obj.name, 'target-2') +# self.assertEqual(obj.sources.count(), 0) + + +# # Regression tests for #694 (`source` attribute on related fields) + + +# class PrimaryKeyRelatedFieldSourceTests(TestCase): +# def test_related_manager_source(self): +# """ +# Relational fields should be able to use manager-returning methods as their source. +# """ +# BlogPost.objects.create(title='blah') +# field = serializers.PrimaryKeyRelatedField(many=True, source='get_blogposts_manager') + +# class ClassWithManagerMethod(object): +# def get_blogposts_manager(self): +# return BlogPost.objects + +# obj = ClassWithManagerMethod() +# value = field.field_to_native(obj, 'field_name') +# self.assertEqual(value, [1]) + +# def test_related_queryset_source(self): +# """ +# Relational fields should be able to use queryset-returning methods as their source. +# """ +# BlogPost.objects.create(title='blah') +# field = serializers.PrimaryKeyRelatedField(many=True, source='get_blogposts_queryset') + +# class ClassWithQuerysetMethod(object): +# def get_blogposts_queryset(self): +# return BlogPost.objects.all() + +# obj = ClassWithQuerysetMethod() +# value = field.field_to_native(obj, 'field_name') +# self.assertEqual(value, [1]) + +# def test_dotted_source(self): +# """ +# Source argument should support dotted.source notation. +# """ +# BlogPost.objects.create(title='blah') +# field = serializers.PrimaryKeyRelatedField(many=True, source='a.b.c') + +# class ClassWithQuerysetMethod(object): +# a = { +# 'b': { +# 'c': BlogPost.objects.all() +# } +# } + +# obj = ClassWithQuerysetMethod() +# value = field.field_to_native(obj, 'field_name') +# self.assertEqual(value, [1]) diff --git a/tests/test_relations_slug.py b/tests/test_relations_slug.py index 97ebf23a1..f7a59a957 100644 --- a/tests/test_relations_slug.py +++ b/tests/test_relations_slug.py @@ -1,257 +1,257 @@ -from django.test import TestCase -from rest_framework import serializers -from tests.models import NullableForeignKeySource, ForeignKeySource, ForeignKeyTarget +# from django.test import TestCase +# from rest_framework import serializers +# from tests.models import NullableForeignKeySource, ForeignKeySource, ForeignKeyTarget -class ForeignKeyTargetSerializer(serializers.ModelSerializer): - sources = serializers.SlugRelatedField(many=True, slug_field='name') +# class ForeignKeyTargetSerializer(serializers.ModelSerializer): +# sources = serializers.SlugRelatedField(many=True, slug_field='name') - class Meta: - model = ForeignKeyTarget +# class Meta: +# model = ForeignKeyTarget -class ForeignKeySourceSerializer(serializers.ModelSerializer): - target = serializers.SlugRelatedField(slug_field='name') +# class ForeignKeySourceSerializer(serializers.ModelSerializer): +# target = serializers.SlugRelatedField(slug_field='name') - class Meta: - model = ForeignKeySource +# class Meta: +# model = ForeignKeySource -class NullableForeignKeySourceSerializer(serializers.ModelSerializer): - target = serializers.SlugRelatedField(slug_field='name', required=False) +# class NullableForeignKeySourceSerializer(serializers.ModelSerializer): +# target = serializers.SlugRelatedField(slug_field='name', required=False) - class Meta: - model = NullableForeignKeySource +# class Meta: +# model = NullableForeignKeySource -# TODO: M2M Tests, FKTests (Non-nullable), One2One -class SlugForeignKeyTests(TestCase): - def setUp(self): - target = ForeignKeyTarget(name='target-1') - target.save() - new_target = ForeignKeyTarget(name='target-2') - new_target.save() - for idx in range(1, 4): - source = ForeignKeySource(name='source-%d' % idx, target=target) - source.save() +# # TODO: M2M Tests, FKTests (Non-nullable), One2One +# class SlugForeignKeyTests(TestCase): +# def setUp(self): +# target = ForeignKeyTarget(name='target-1') +# target.save() +# new_target = ForeignKeyTarget(name='target-2') +# new_target.save() +# for idx in range(1, 4): +# source = ForeignKeySource(name='source-%d' % idx, target=target) +# source.save() - def test_foreign_key_retrieve(self): - queryset = ForeignKeySource.objects.all() - serializer = ForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': 'target-1'}, - {'id': 2, 'name': 'source-2', 'target': 'target-1'}, - {'id': 3, 'name': 'source-3', 'target': 'target-1'} - ] - self.assertEqual(serializer.data, expected) +# def test_foreign_key_retrieve(self): +# queryset = ForeignKeySource.objects.all() +# serializer = ForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': 'target-1'}, +# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, +# {'id': 3, 'name': 'source-3', 'target': 'target-1'} +# ] +# self.assertEqual(serializer.data, expected) - def test_reverse_foreign_key_retrieve(self): - queryset = ForeignKeyTarget.objects.all() - serializer = ForeignKeyTargetSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']}, - {'id': 2, 'name': 'target-2', 'sources': []}, - ] - self.assertEqual(serializer.data, expected) +# def test_reverse_foreign_key_retrieve(self): +# queryset = ForeignKeyTarget.objects.all() +# serializer = ForeignKeyTargetSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']}, +# {'id': 2, 'name': 'target-2', 'sources': []}, +# ] +# self.assertEqual(serializer.data, expected) - def test_foreign_key_update(self): - data = {'id': 1, 'name': 'source-1', 'target': 'target-2'} - instance = ForeignKeySource.objects.get(pk=1) - serializer = ForeignKeySourceSerializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.data, data) - serializer.save() +# def test_foreign_key_update(self): +# data = {'id': 1, 'name': 'source-1', 'target': 'target-2'} +# instance = ForeignKeySource.objects.get(pk=1) +# serializer = ForeignKeySourceSerializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.data, data) +# serializer.save() - # Ensure source 1 is updated, and everything else is as expected - queryset = ForeignKeySource.objects.all() - serializer = ForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': 'target-2'}, - {'id': 2, 'name': 'source-2', 'target': 'target-1'}, - {'id': 3, 'name': 'source-3', 'target': 'target-1'} - ] - self.assertEqual(serializer.data, expected) +# # Ensure source 1 is updated, and everything else is as expected +# queryset = ForeignKeySource.objects.all() +# serializer = ForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': 'target-2'}, +# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, +# {'id': 3, 'name': 'source-3', 'target': 'target-1'} +# ] +# self.assertEqual(serializer.data, expected) - def test_foreign_key_update_incorrect_type(self): - data = {'id': 1, 'name': 'source-1', 'target': 123} - instance = ForeignKeySource.objects.get(pk=1) - serializer = ForeignKeySourceSerializer(instance, data=data) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'target': ['Object with name=123 does not exist.']}) +# def test_foreign_key_update_incorrect_type(self): +# data = {'id': 1, 'name': 'source-1', 'target': 123} +# instance = ForeignKeySource.objects.get(pk=1) +# serializer = ForeignKeySourceSerializer(instance, data=data) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'target': ['Object with name=123 does not exist.']}) - def test_reverse_foreign_key_update(self): - data = {'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']} - instance = ForeignKeyTarget.objects.get(pk=2) - serializer = ForeignKeyTargetSerializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - # We shouldn't have saved anything to the db yet since save - # hasn't been called. - queryset = ForeignKeyTarget.objects.all() - new_serializer = ForeignKeyTargetSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']}, - {'id': 2, 'name': 'target-2', 'sources': []}, - ] - self.assertEqual(new_serializer.data, expected) +# def test_reverse_foreign_key_update(self): +# data = {'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']} +# instance = ForeignKeyTarget.objects.get(pk=2) +# serializer = ForeignKeyTargetSerializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# # We shouldn't have saved anything to the db yet since save +# # hasn't been called. +# queryset = ForeignKeyTarget.objects.all() +# new_serializer = ForeignKeyTargetSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']}, +# {'id': 2, 'name': 'target-2', 'sources': []}, +# ] +# self.assertEqual(new_serializer.data, expected) - serializer.save() - self.assertEqual(serializer.data, data) +# serializer.save() +# self.assertEqual(serializer.data, data) - # Ensure target 2 is update, and everything else is as expected - queryset = ForeignKeyTarget.objects.all() - serializer = ForeignKeyTargetSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': ['source-2']}, - {'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']}, - ] - self.assertEqual(serializer.data, expected) +# # Ensure target 2 is update, and everything else is as expected +# queryset = ForeignKeyTarget.objects.all() +# serializer = ForeignKeyTargetSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': ['source-2']}, +# {'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']}, +# ] +# self.assertEqual(serializer.data, expected) - def test_foreign_key_create(self): - data = {'id': 4, 'name': 'source-4', 'target': 'target-2'} - serializer = ForeignKeySourceSerializer(data=data) - serializer.is_valid() - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'source-4') +# def test_foreign_key_create(self): +# data = {'id': 4, 'name': 'source-4', 'target': 'target-2'} +# serializer = ForeignKeySourceSerializer(data=data) +# serializer.is_valid() +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'source-4') - # Ensure source 4 is added, and everything else is as expected - queryset = ForeignKeySource.objects.all() - serializer = ForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': 'target-1'}, - {'id': 2, 'name': 'source-2', 'target': 'target-1'}, - {'id': 3, 'name': 'source-3', 'target': 'target-1'}, - {'id': 4, 'name': 'source-4', 'target': 'target-2'}, - ] - self.assertEqual(serializer.data, expected) +# # Ensure source 4 is added, and everything else is as expected +# queryset = ForeignKeySource.objects.all() +# serializer = ForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': 'target-1'}, +# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, +# {'id': 3, 'name': 'source-3', 'target': 'target-1'}, +# {'id': 4, 'name': 'source-4', 'target': 'target-2'}, +# ] +# self.assertEqual(serializer.data, expected) - def test_reverse_foreign_key_create(self): - data = {'id': 3, 'name': 'target-3', 'sources': ['source-1', 'source-3']} - serializer = ForeignKeyTargetSerializer(data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'target-3') +# def test_reverse_foreign_key_create(self): +# data = {'id': 3, 'name': 'target-3', 'sources': ['source-1', 'source-3']} +# serializer = ForeignKeyTargetSerializer(data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'target-3') - # Ensure target 3 is added, and everything else is as expected - queryset = ForeignKeyTarget.objects.all() - serializer = ForeignKeyTargetSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'target-1', 'sources': ['source-2']}, - {'id': 2, 'name': 'target-2', 'sources': []}, - {'id': 3, 'name': 'target-3', 'sources': ['source-1', 'source-3']}, - ] - self.assertEqual(serializer.data, expected) +# # Ensure target 3 is added, and everything else is as expected +# queryset = ForeignKeyTarget.objects.all() +# serializer = ForeignKeyTargetSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'target-1', 'sources': ['source-2']}, +# {'id': 2, 'name': 'target-2', 'sources': []}, +# {'id': 3, 'name': 'target-3', 'sources': ['source-1', 'source-3']}, +# ] +# self.assertEqual(serializer.data, expected) - def test_foreign_key_update_with_invalid_null(self): - data = {'id': 1, 'name': 'source-1', 'target': None} - instance = ForeignKeySource.objects.get(pk=1) - serializer = ForeignKeySourceSerializer(instance, data=data) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'target': ['This field is required.']}) +# def test_foreign_key_update_with_invalid_null(self): +# data = {'id': 1, 'name': 'source-1', 'target': None} +# instance = ForeignKeySource.objects.get(pk=1) +# serializer = ForeignKeySourceSerializer(instance, data=data) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'target': ['This field is required.']}) -class SlugNullableForeignKeyTests(TestCase): - def setUp(self): - target = ForeignKeyTarget(name='target-1') - target.save() - for idx in range(1, 4): - if idx == 3: - target = None - source = NullableForeignKeySource(name='source-%d' % idx, target=target) - source.save() +# class SlugNullableForeignKeyTests(TestCase): +# def setUp(self): +# target = ForeignKeyTarget(name='target-1') +# target.save() +# for idx in range(1, 4): +# if idx == 3: +# target = None +# source = NullableForeignKeySource(name='source-%d' % idx, target=target) +# source.save() - def test_foreign_key_retrieve_with_null(self): - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': 'target-1'}, - {'id': 2, 'name': 'source-2', 'target': 'target-1'}, - {'id': 3, 'name': 'source-3', 'target': None}, - ] - self.assertEqual(serializer.data, expected) +# def test_foreign_key_retrieve_with_null(self): +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': 'target-1'}, +# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, +# {'id': 3, 'name': 'source-3', 'target': None}, +# ] +# self.assertEqual(serializer.data, expected) - def test_foreign_key_create_with_valid_null(self): - data = {'id': 4, 'name': 'source-4', 'target': None} - serializer = NullableForeignKeySourceSerializer(data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, data) - self.assertEqual(obj.name, 'source-4') +# def test_foreign_key_create_with_valid_null(self): +# data = {'id': 4, 'name': 'source-4', 'target': None} +# serializer = NullableForeignKeySourceSerializer(data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, data) +# self.assertEqual(obj.name, 'source-4') - # Ensure source 4 is created, and everything else is as expected - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': 'target-1'}, - {'id': 2, 'name': 'source-2', 'target': 'target-1'}, - {'id': 3, 'name': 'source-3', 'target': None}, - {'id': 4, 'name': 'source-4', 'target': None} - ] - self.assertEqual(serializer.data, expected) +# # Ensure source 4 is created, and everything else is as expected +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': 'target-1'}, +# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, +# {'id': 3, 'name': 'source-3', 'target': None}, +# {'id': 4, 'name': 'source-4', 'target': None} +# ] +# self.assertEqual(serializer.data, expected) - def test_foreign_key_create_with_valid_emptystring(self): - """ - The emptystring should be interpreted as null in the context - of relationships. - """ - data = {'id': 4, 'name': 'source-4', 'target': ''} - expected_data = {'id': 4, 'name': 'source-4', 'target': None} - serializer = NullableForeignKeySourceSerializer(data=data) - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - self.assertEqual(serializer.data, expected_data) - self.assertEqual(obj.name, 'source-4') +# def test_foreign_key_create_with_valid_emptystring(self): +# """ +# The emptystring should be interpreted as null in the context +# of relationships. +# """ +# data = {'id': 4, 'name': 'source-4', 'target': ''} +# expected_data = {'id': 4, 'name': 'source-4', 'target': None} +# serializer = NullableForeignKeySourceSerializer(data=data) +# self.assertTrue(serializer.is_valid()) +# obj = serializer.save() +# self.assertEqual(serializer.data, expected_data) +# self.assertEqual(obj.name, 'source-4') - # Ensure source 4 is created, and everything else is as expected - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': 'target-1'}, - {'id': 2, 'name': 'source-2', 'target': 'target-1'}, - {'id': 3, 'name': 'source-3', 'target': None}, - {'id': 4, 'name': 'source-4', 'target': None} - ] - self.assertEqual(serializer.data, expected) +# # Ensure source 4 is created, and everything else is as expected +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': 'target-1'}, +# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, +# {'id': 3, 'name': 'source-3', 'target': None}, +# {'id': 4, 'name': 'source-4', 'target': None} +# ] +# self.assertEqual(serializer.data, expected) - def test_foreign_key_update_with_valid_null(self): - data = {'id': 1, 'name': 'source-1', 'target': None} - instance = NullableForeignKeySource.objects.get(pk=1) - serializer = NullableForeignKeySourceSerializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.data, data) - serializer.save() +# def test_foreign_key_update_with_valid_null(self): +# data = {'id': 1, 'name': 'source-1', 'target': None} +# instance = NullableForeignKeySource.objects.get(pk=1) +# serializer = NullableForeignKeySourceSerializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.data, data) +# serializer.save() - # Ensure source 1 is updated, and everything else is as expected - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': None}, - {'id': 2, 'name': 'source-2', 'target': 'target-1'}, - {'id': 3, 'name': 'source-3', 'target': None} - ] - self.assertEqual(serializer.data, expected) +# # Ensure source 1 is updated, and everything else is as expected +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': None}, +# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, +# {'id': 3, 'name': 'source-3', 'target': None} +# ] +# self.assertEqual(serializer.data, expected) - def test_foreign_key_update_with_valid_emptystring(self): - """ - The emptystring should be interpreted as null in the context - of relationships. - """ - data = {'id': 1, 'name': 'source-1', 'target': ''} - expected_data = {'id': 1, 'name': 'source-1', 'target': None} - instance = NullableForeignKeySource.objects.get(pk=1) - serializer = NullableForeignKeySourceSerializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.data, expected_data) - serializer.save() +# def test_foreign_key_update_with_valid_emptystring(self): +# """ +# The emptystring should be interpreted as null in the context +# of relationships. +# """ +# data = {'id': 1, 'name': 'source-1', 'target': ''} +# expected_data = {'id': 1, 'name': 'source-1', 'target': None} +# instance = NullableForeignKeySource.objects.get(pk=1) +# serializer = NullableForeignKeySourceSerializer(instance, data=data) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.data, expected_data) +# serializer.save() - # Ensure source 1 is updated, and everything else is as expected - queryset = NullableForeignKeySource.objects.all() - serializer = NullableForeignKeySourceSerializer(queryset, many=True) - expected = [ - {'id': 1, 'name': 'source-1', 'target': None}, - {'id': 2, 'name': 'source-2', 'target': 'target-1'}, - {'id': 3, 'name': 'source-3', 'target': None} - ] - self.assertEqual(serializer.data, expected) +# # Ensure source 1 is updated, and everything else is as expected +# queryset = NullableForeignKeySource.objects.all() +# serializer = NullableForeignKeySourceSerializer(queryset, many=True) +# expected = [ +# {'id': 1, 'name': 'source-1', 'target': None}, +# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, +# {'id': 3, 'name': 'source-3', 'target': None} +# ] +# self.assertEqual(serializer.data, expected) From c1036c17533a3091401ff90f825571f0e6125eca Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 3 Sep 2014 16:34:09 +0100 Subject: [PATCH 017/249] More test passing --- rest_framework/relations.py | 56 +- tests/test_serializer.py | 3748 +++++++++++++------------- tests/test_serializer_bulk_update.py | 484 ++-- tests/test_serializer_empty.py | 22 +- tests/test_serializer_import.py | 32 +- tests/test_serializer_nested.py | 586 ++-- tests/test_serializers.py | 50 +- 7 files changed, 2516 insertions(+), 2462 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 0b01394a8..661a1249a 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -1,6 +1,7 @@ from rest_framework.fields import Field +from rest_framework.reverse import reverse from django.core.exceptions import ObjectDoesNotExist -from django.core.urlresolvers import resolve, get_script_prefix +from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch from rest_framework.compat import urlparse @@ -100,11 +101,64 @@ class HyperlinkedIdentityField(RelatedField): lookup_field = 'pk' def __init__(self, **kwargs): + kwargs['read_only'] = True self.view_name = kwargs.pop('view_name') self.lookup_field = kwargs.pop('lookup_field', self.lookup_field) self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field) super(HyperlinkedIdentityField, self).__init__(**kwargs) + def get_attribute(self, instance): + return instance + + def to_primative(self, value): + request = self.context.get('request', None) + format = self.context.get('format', None) + + assert request is not None, ( + "`HyperlinkedIdentityField` requires the request in the serializer" + " context. Add `context={'request': request}` when instantiating " + "the serializer." + ) + + # By default use whatever format is given for the current context + # unless the target is a different type to the source. + # + # Eg. Consider a HyperlinkedIdentityField pointing from a json + # representation to an html property of that representation... + # + # '/snippets/1/' should link to '/snippets/1/highlight/' + # ...but... + # '/snippets/1/.json' should link to '/snippets/1/highlight/.html' + if format and self.format and self.format != format: + format = self.format + + # Return the hyperlink, or error if incorrectly configured. + try: + return self.get_url(value, self.view_name, request, format) + except NoReverseMatch: + msg = ( + 'Could not resolve URL for hyperlinked relationship using ' + 'view name "%s". You may have failed to include the related ' + 'model in your API, or incorrectly configured the ' + '`lookup_field` attribute on this field.' + ) + raise Exception(msg % self.view_name) + + def get_url(self, obj, view_name, request, format): + """ + Given an object, return the URL that hyperlinks to the object. + + May raise a `NoReverseMatch` if the `view_name` and `lookup_field` + attributes are not configured to correctly match the URL conf. + """ + # Unsaved objects will not yet have a valid URL. + if obj.pk is None: + return None + + lookup_value = getattr(obj, self.lookup_field) + kwargs = {self.lookup_url_kwarg: lookup_value} + return reverse(view_name, kwargs=kwargs, request=request, format=format) + class SlugRelatedField(RelatedField): def __init__(self, **kwargs): diff --git a/tests/test_serializer.py b/tests/test_serializer.py index fa5cafcfb..b0eb4e270 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -1,2004 +1,2004 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals -from django.db import models -from django.db.models.fields import BLANK_CHOICE_DASH -from django.test import TestCase -from django.utils import unittest -from django.utils.datastructures import MultiValueDict -from django.utils.translation import ugettext_lazy as _ -from rest_framework import serializers, fields, relations -from tests.models import ( - HasPositiveIntegerAsChoice, Album, ActionItem, Anchor, BasicModel, - BlankFieldModel, BlogPost, BlogPostComment, Book, CallableDefaultValueModel, - DefaultValueModel, ManyToManyModel, Person, ReadOnlyManyToManyModel, Photo, - RESTFrameworkModel, ForeignKeySource -) -from tests.models import BasicModelSerializer -import datetime -import pickle -try: - import PIL -except: - PIL = None - - -if PIL is not None: - class AMOAFModel(RESTFrameworkModel): - char_field = models.CharField(max_length=1024, blank=True) - comma_separated_integer_field = models.CommaSeparatedIntegerField(max_length=1024, blank=True) - decimal_field = models.DecimalField(max_digits=64, decimal_places=32, blank=True) - email_field = models.EmailField(max_length=1024, blank=True) - file_field = models.FileField(upload_to='test', max_length=1024, blank=True) - image_field = models.ImageField(upload_to='test', max_length=1024, blank=True) - slug_field = models.SlugField(max_length=1024, blank=True) - url_field = models.URLField(max_length=1024, blank=True) - nullable_char_field = models.CharField(max_length=1024, blank=True, null=True) - - class DVOAFModel(RESTFrameworkModel): - positive_integer_field = models.PositiveIntegerField(blank=True) - positive_small_integer_field = models.PositiveSmallIntegerField(blank=True) - email_field = models.EmailField(blank=True) - file_field = models.FileField(upload_to='test', blank=True) - image_field = models.ImageField(upload_to='test', blank=True) - slug_field = models.SlugField(blank=True) - url_field = models.URLField(blank=True) +# # -*- coding: utf-8 -*- +# from __future__ import unicode_literals +# from django.db import models +# from django.db.models.fields import BLANK_CHOICE_DASH +# from django.test import TestCase +# from django.utils import unittest +# from django.utils.datastructures import MultiValueDict +# from django.utils.translation import ugettext_lazy as _ +# from rest_framework import serializers, fields, relations +# from tests.models import ( +# HasPositiveIntegerAsChoice, Album, ActionItem, Anchor, BasicModel, +# BlankFieldModel, BlogPost, BlogPostComment, Book, CallableDefaultValueModel, +# DefaultValueModel, ManyToManyModel, Person, ReadOnlyManyToManyModel, Photo, +# RESTFrameworkModel, ForeignKeySource +# ) +# from tests.models import BasicModelSerializer +# import datetime +# import pickle +# try: +# import PIL +# except: +# PIL = None + + +# if PIL is not None: +# class AMOAFModel(RESTFrameworkModel): +# char_field = models.CharField(max_length=1024, blank=True) +# comma_separated_integer_field = models.CommaSeparatedIntegerField(max_length=1024, blank=True) +# decimal_field = models.DecimalField(max_digits=64, decimal_places=32, blank=True) +# email_field = models.EmailField(max_length=1024, blank=True) +# file_field = models.FileField(upload_to='test', max_length=1024, blank=True) +# image_field = models.ImageField(upload_to='test', max_length=1024, blank=True) +# slug_field = models.SlugField(max_length=1024, blank=True) +# url_field = models.URLField(max_length=1024, blank=True) +# nullable_char_field = models.CharField(max_length=1024, blank=True, null=True) + +# class DVOAFModel(RESTFrameworkModel): +# positive_integer_field = models.PositiveIntegerField(blank=True) +# positive_small_integer_field = models.PositiveSmallIntegerField(blank=True) +# email_field = models.EmailField(blank=True) +# file_field = models.FileField(upload_to='test', blank=True) +# image_field = models.ImageField(upload_to='test', blank=True) +# slug_field = models.SlugField(blank=True) +# url_field = models.URLField(blank=True) -class SubComment(object): - def __init__(self, sub_comment): - self.sub_comment = sub_comment +# class SubComment(object): +# def __init__(self, sub_comment): +# self.sub_comment = sub_comment -class Comment(object): - def __init__(self, email, content, created): - self.email = email - self.content = content - self.created = created or datetime.datetime.now() +# class Comment(object): +# def __init__(self, email, content, created): +# self.email = email +# self.content = content +# self.created = created or datetime.datetime.now() - def __eq__(self, other): - return all([getattr(self, attr) == getattr(other, attr) - for attr in ('email', 'content', 'created')]) +# def __eq__(self, other): +# return all([getattr(self, attr) == getattr(other, attr) +# for attr in ('email', 'content', 'created')]) - def get_sub_comment(self): - sub_comment = SubComment('And Merry Christmas!') - return sub_comment +# def get_sub_comment(self): +# sub_comment = SubComment('And Merry Christmas!') +# return sub_comment -class CommentSerializer(serializers.Serializer): - email = serializers.EmailField() - content = serializers.CharField(max_length=1000) - created = serializers.DateTimeField() - sub_comment = serializers.Field(source='get_sub_comment.sub_comment') +# class CommentSerializer(serializers.Serializer): +# email = serializers.EmailField() +# content = serializers.CharField(max_length=1000) +# created = serializers.DateTimeField() +# sub_comment = serializers.Field(source='get_sub_comment.sub_comment') - def restore_object(self, data, instance=None): - if instance is None: - return Comment(**data) - for key, val in data.items(): - setattr(instance, key, val) - return instance +# def restore_object(self, data, instance=None): +# if instance is None: +# return Comment(**data) +# for key, val in data.items(): +# setattr(instance, key, val) +# return instance -class NamesSerializer(serializers.Serializer): - first = serializers.CharField() - last = serializers.CharField(required=False, default='') - initials = serializers.CharField(required=False, default='') +# class NamesSerializer(serializers.Serializer): +# first = serializers.CharField() +# last = serializers.CharField(required=False, default='') +# initials = serializers.CharField(required=False, default='') -class PersonIdentifierSerializer(serializers.Serializer): - ssn = serializers.CharField() - names = NamesSerializer(source='names', required=False) +# class PersonIdentifierSerializer(serializers.Serializer): +# ssn = serializers.CharField() +# names = NamesSerializer(source='names', required=False) -class BookSerializer(serializers.ModelSerializer): - isbn = serializers.RegexField(regex=r'^[0-9]{13}$', error_messages={'invalid': 'isbn has to be exact 13 numbers'}) +# class BookSerializer(serializers.ModelSerializer): +# isbn = serializers.RegexField(regex=r'^[0-9]{13}$', error_messages={'invalid': 'isbn has to be exact 13 numbers'}) - class Meta: - model = Book +# class Meta: +# model = Book -class ActionItemSerializer(serializers.ModelSerializer): +# class ActionItemSerializer(serializers.ModelSerializer): - class Meta: - model = ActionItem +# class Meta: +# model = ActionItem -class ActionItemSerializerOptionalFields(serializers.ModelSerializer): - """ - Intended to test that fields with `required=False` are excluded from validation. - """ - title = serializers.CharField(required=False) +# class ActionItemSerializerOptionalFields(serializers.ModelSerializer): +# """ +# Intended to test that fields with `required=False` are excluded from validation. +# """ +# title = serializers.CharField(required=False) - class Meta: - model = ActionItem - fields = ('title',) +# class Meta: +# model = ActionItem +# fields = ('title',) -class ActionItemSerializerCustomRestore(serializers.ModelSerializer): +# class ActionItemSerializerCustomRestore(serializers.ModelSerializer): - class Meta: - model = ActionItem +# class Meta: +# model = ActionItem - def restore_object(self, data, instance=None): - if instance is None: - return ActionItem(**data) - for key, val in data.items(): - setattr(instance, key, val) - return instance +# def restore_object(self, data, instance=None): +# if instance is None: +# return ActionItem(**data) +# for key, val in data.items(): +# setattr(instance, key, val) +# return instance -class PersonSerializer(serializers.ModelSerializer): - info = serializers.Field(source='info') +# class PersonSerializer(serializers.ModelSerializer): +# info = serializers.Field(source='info') - class Meta: - model = Person - fields = ('name', 'age', 'info') - read_only_fields = ('age',) +# class Meta: +# model = Person +# fields = ('name', 'age', 'info') +# read_only_fields = ('age',) -class NestedSerializer(serializers.Serializer): - info = serializers.Field() +# class NestedSerializer(serializers.Serializer): +# info = serializers.Field() -class ModelSerializerWithNestedSerializer(serializers.ModelSerializer): - nested = NestedSerializer(source='*') +# class ModelSerializerWithNestedSerializer(serializers.ModelSerializer): +# nested = NestedSerializer(source='*') - class Meta: - model = Person +# class Meta: +# model = Person -class NestedSerializerWithRenamedField(serializers.Serializer): - renamed_info = serializers.Field(source='info') +# class NestedSerializerWithRenamedField(serializers.Serializer): +# renamed_info = serializers.Field(source='info') -class ModelSerializerWithNestedSerializerWithRenamedField(serializers.ModelSerializer): - nested = NestedSerializerWithRenamedField(source='*') +# class ModelSerializerWithNestedSerializerWithRenamedField(serializers.ModelSerializer): +# nested = NestedSerializerWithRenamedField(source='*') - class Meta: - model = Person +# class Meta: +# model = Person -class PersonSerializerInvalidReadOnly(serializers.ModelSerializer): - """ - Testing for #652. - """ - info = serializers.Field(source='info') +# class PersonSerializerInvalidReadOnly(serializers.ModelSerializer): +# """ +# Testing for #652. +# """ +# info = serializers.Field(source='info') - class Meta: - model = Person - fields = ('name', 'age', 'info') - read_only_fields = ('age', 'info') +# class Meta: +# model = Person +# fields = ('name', 'age', 'info') +# read_only_fields = ('age', 'info') -class AlbumsSerializer(serializers.ModelSerializer): +# class AlbumsSerializer(serializers.ModelSerializer): - class Meta: - model = Album - fields = ['title', 'ref'] # lists are also valid options +# class Meta: +# model = Album +# fields = ['title', 'ref'] # lists are also valid options -class PositiveIntegerAsChoiceSerializer(serializers.ModelSerializer): - class Meta: - model = HasPositiveIntegerAsChoice - fields = ['some_integer'] +# class PositiveIntegerAsChoiceSerializer(serializers.ModelSerializer): +# class Meta: +# model = HasPositiveIntegerAsChoice +# fields = ['some_integer'] -class ForeignKeySourceSerializer(serializers.ModelSerializer): - class Meta: - model = ForeignKeySource +# class ForeignKeySourceSerializer(serializers.ModelSerializer): +# class Meta: +# model = ForeignKeySource -class HyperlinkedForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): - class Meta: - model = ForeignKeySource +# class HyperlinkedForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): +# class Meta: +# model = ForeignKeySource -class BasicTests(TestCase): - def setUp(self): - self.comment = Comment( - 'tom@example.com', - 'Happy new year!', - datetime.datetime(2012, 1, 1) - ) - self.actionitem = ActionItem(title='Some to do item',) - self.data = { - 'email': 'tom@example.com', - 'content': 'Happy new year!', - 'created': datetime.datetime(2012, 1, 1), - 'sub_comment': 'This wont change' - } - self.expected = { - 'email': 'tom@example.com', - 'content': 'Happy new year!', - 'created': datetime.datetime(2012, 1, 1), - 'sub_comment': 'And Merry Christmas!' - } - self.person_data = {'name': 'dwight', 'age': 35} - self.person = Person(**self.person_data) - self.person.save() - - def test_empty(self): - serializer = CommentSerializer() - expected = { - 'email': '', - 'content': '', - 'created': None - } - self.assertEqual(serializer.data, expected) - - def test_retrieve(self): - serializer = CommentSerializer(self.comment) - self.assertEqual(serializer.data, self.expected) - - def test_create(self): - serializer = CommentSerializer(data=self.data) - expected = self.comment - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.object, expected) - self.assertFalse(serializer.object is expected) - self.assertEqual(serializer.data['sub_comment'], 'And Merry Christmas!') - - def test_create_nested(self): - """Test a serializer with nested data.""" - names = {'first': 'John', 'last': 'Doe', 'initials': 'jd'} - data = {'ssn': '1234567890', 'names': names} - serializer = PersonIdentifierSerializer(data=data) - - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.object, data) - self.assertFalse(serializer.object is data) - self.assertEqual(serializer.data['names'], names) - - def test_create_partial_nested(self): - """Test a serializer with nested data which has missing fields.""" - names = {'first': 'John'} - data = {'ssn': '1234567890', 'names': names} - serializer = PersonIdentifierSerializer(data=data) - - expected_names = {'first': 'John', 'last': '', 'initials': ''} - data['names'] = expected_names - - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.object, data) - self.assertFalse(serializer.object is expected_names) - self.assertEqual(serializer.data['names'], expected_names) - - def test_null_nested(self): - """Test a serializer with a nonexistent nested field""" - data = {'ssn': '1234567890'} - serializer = PersonIdentifierSerializer(data=data) - - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.object, data) - self.assertFalse(serializer.object is data) - expected = {'ssn': '1234567890', 'names': None} - self.assertEqual(serializer.data, expected) - - def test_update(self): - serializer = CommentSerializer(self.comment, data=self.data) - expected = self.comment - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.object, expected) - self.assertTrue(serializer.object is expected) - self.assertEqual(serializer.data['sub_comment'], 'And Merry Christmas!') - - def test_partial_update(self): - msg = 'Merry New Year!' - partial_data = {'content': msg} - serializer = CommentSerializer(self.comment, data=partial_data) - self.assertEqual(serializer.is_valid(), False) - serializer = CommentSerializer(self.comment, data=partial_data, partial=True) - expected = self.comment - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.object, expected) - self.assertTrue(serializer.object is expected) - self.assertEqual(serializer.data['content'], msg) - - def test_model_fields_as_expected(self): - """ - Make sure that the fields returned are the same as defined - in the Meta data - """ - serializer = PersonSerializer(self.person) - self.assertEqual( - set(serializer.data.keys()), - set(['name', 'age', 'info']) - ) - - def test_field_with_dictionary(self): - """ - Make sure that dictionaries from fields are left intact - """ - serializer = PersonSerializer(self.person) - expected = self.person_data - self.assertEqual(serializer.data['info'], expected) - - def test_read_only_fields(self): - """ - Attempting to update fields set as read_only should have no effect. - """ - serializer = PersonSerializer(self.person, data={'name': 'dwight', 'age': 99}) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - self.assertEqual(serializer.errors, {}) - # Assert age is unchanged (35) - self.assertEqual(instance.age, self.person_data['age']) - - def test_invalid_read_only_fields(self): - """ - Regression test for #652. - """ - self.assertRaises(AssertionError, PersonSerializerInvalidReadOnly, []) - - def test_serializer_data_is_cleared_on_save(self): - """ - Check _data attribute is cleared on `save()` - - Regression test for #1116 - — id field is not populated if `data` is accessed prior to `save()` - """ - serializer = ActionItemSerializer(self.actionitem) - self.assertIsNone(serializer.data.get('id', None), 'New instance. `id` should not be set.') - serializer.save() - self.assertIsNotNone(serializer.data.get('id', None), 'Model is saved. `id` should be set.') - - def test_fields_marked_as_not_required_are_excluded_from_validation(self): - """ - Check that fields with `required=False` are included in list of exclusions. - """ - serializer = ActionItemSerializerOptionalFields(self.actionitem) - exclusions = serializer.get_validation_exclusions() - self.assertTrue('title' in exclusions, '`title` field was marked `required=False` and should be excluded') - - -class DictStyleSerializer(serializers.Serializer): - """ - Note that we don't have any `restore_object` method, so the default - case of simply returning a dict will apply. - """ - email = serializers.EmailField() - - -class DictStyleSerializerTests(TestCase): - def test_dict_style_deserialize(self): - """ - Ensure serializers can deserialize into a dict. - """ - data = {'email': 'foo@example.com'} - serializer = DictStyleSerializer(data=data) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.data, data) - - def test_dict_style_serialize(self): - """ - Ensure serializers can serialize dict objects. - """ - data = {'email': 'foo@example.com'} - serializer = DictStyleSerializer(data) - self.assertEqual(serializer.data, data) - - -class ValidationTests(TestCase): - def setUp(self): - self.comment = Comment( - 'tom@example.com', - 'Happy new year!', - datetime.datetime(2012, 1, 1) - ) - self.data = { - 'email': 'tom@example.com', - 'content': 'x' * 1001, - 'created': datetime.datetime(2012, 1, 1) - } - self.actionitem = ActionItem(title='Some to do item',) - - def test_create(self): - serializer = CommentSerializer(data=self.data) - self.assertEqual(serializer.is_valid(), False) - self.assertEqual(serializer.errors, {'content': ['Ensure this value has at most 1000 characters (it has 1001).']}) - - def test_update(self): - serializer = CommentSerializer(self.comment, data=self.data) - self.assertEqual(serializer.is_valid(), False) - self.assertEqual(serializer.errors, {'content': ['Ensure this value has at most 1000 characters (it has 1001).']}) - - def test_update_missing_field(self): - data = { - 'content': 'xxx', - 'created': datetime.datetime(2012, 1, 1) - } - serializer = CommentSerializer(self.comment, data=data) - self.assertEqual(serializer.is_valid(), False) - self.assertEqual(serializer.errors, {'email': ['This field is required.']}) - - def test_missing_bool_with_default(self): - """Make sure that a boolean value with a 'False' value is not - mistaken for not having a default.""" - data = { - 'title': 'Some action item', - # No 'done' value. - } - serializer = ActionItemSerializer(self.actionitem, data=data) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.errors, {}) - - def test_cross_field_validation(self): - - class CommentSerializerWithCrossFieldValidator(CommentSerializer): - - def validate(self, attrs): - if attrs["email"] not in attrs["content"]: - raise serializers.ValidationError("Email address not in content") - return attrs - - data = { - 'email': 'tom@example.com', - 'content': 'A comment from tom@example.com', - 'created': datetime.datetime(2012, 1, 1) - } - - serializer = CommentSerializerWithCrossFieldValidator(data=data) - self.assertTrue(serializer.is_valid()) - - data['content'] = 'A comment from foo@bar.com' - - serializer = CommentSerializerWithCrossFieldValidator(data=data) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'non_field_errors': ['Email address not in content']}) - - def test_null_is_true_fields(self): - """ - Omitting a value for null-field should validate. - """ - serializer = PersonSerializer(data={'name': 'marko'}) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.errors, {}) - - def test_modelserializer_max_length_exceeded(self): - data = { - 'title': 'x' * 201, - } - serializer = ActionItemSerializer(data=data) - self.assertEqual(serializer.is_valid(), False) - self.assertEqual(serializer.errors, {'title': ['Ensure this value has at most 200 characters (it has 201).']}) - - def test_modelserializer_max_length_exceeded_with_custom_restore(self): - """ - When overriding ModelSerializer.restore_object, validation tests should still apply. - Regression test for #623. - - https://github.com/tomchristie/django-rest-framework/pull/623 - """ - data = { - 'title': 'x' * 201, - } - serializer = ActionItemSerializerCustomRestore(data=data) - self.assertEqual(serializer.is_valid(), False) - self.assertEqual(serializer.errors, {'title': ['Ensure this value has at most 200 characters (it has 201).']}) - - def test_default_modelfield_max_length_exceeded(self): - data = { - 'title': 'Testing "info" field...', - 'info': 'x' * 13, - } - serializer = ActionItemSerializer(data=data) - self.assertEqual(serializer.is_valid(), False) - self.assertEqual(serializer.errors, {'info': ['Ensure this value has at most 12 characters (it has 13).']}) - - def test_datetime_validation_failure(self): - """ - Test DateTimeField validation errors on non-str values. - Regression test for #669. - - https://github.com/tomchristie/django-rest-framework/issues/669 - """ - data = self.data - data['created'] = 0 - - serializer = CommentSerializer(data=data) - self.assertEqual(serializer.is_valid(), False) - - self.assertIn('created', serializer.errors) - - def test_missing_model_field_exception_msg(self): - """ - Assert that a meaningful exception message is outputted when the model - field is missing (e.g. when mistyping ``model``). - """ - class BrokenModelSerializer(serializers.ModelSerializer): - class Meta: - fields = ['some_field'] - - try: - BrokenModelSerializer() - except AssertionError as e: - self.assertEqual(e.args[0], "Serializer class 'BrokenModelSerializer' is missing 'model' Meta option") - except: - self.fail('Wrong exception type thrown.') - - def test_writable_star_source_on_nested_serializer(self): - """ - Assert that a nested serializer instantiated with source='*' correctly - expands the data into the outer serializer. - """ - serializer = ModelSerializerWithNestedSerializer(data={ - 'name': 'marko', - 'nested': {'info': 'hi'}}, - ) - self.assertEqual(serializer.is_valid(), True) - - def test_writable_star_source_on_nested_serializer_with_parent_object(self): - class TitleSerializer(serializers.Serializer): - title = serializers.WritableField(source='title') - - class AlbumSerializer(serializers.ModelSerializer): - nested = TitleSerializer(source='*') - - class Meta: - model = Album - fields = ('nested',) - - class PhotoSerializer(serializers.ModelSerializer): - album = AlbumSerializer(source='album') - - class Meta: - model = Photo - fields = ('album', ) - - photo = Photo(album=Album()) - - data = {'album': {'nested': {'title': 'test'}}} - - serializer = PhotoSerializer(photo, data=data) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.data, data) - - def test_writable_star_source_with_inner_source_fields(self): - """ - Tests that a serializer with source="*" correctly expands the - it's fields into the outer serializer even if they have their - own 'source' parameters. - """ - - serializer = ModelSerializerWithNestedSerializerWithRenamedField(data={ - 'name': 'marko', - 'nested': {'renamed_info': 'hi'}}, - ) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.errors, {}) - - -class CustomValidationTests(TestCase): - class CommentSerializerWithFieldValidator(CommentSerializer): - - def validate_email(self, attrs, source): - attrs[source] - return attrs - - def validate_content(self, attrs, source): - value = attrs[source] - if "test" not in value: - raise serializers.ValidationError("Test not in value") - return attrs - - def test_field_validation(self): - data = { - 'email': 'tom@example.com', - 'content': 'A test comment', - 'created': datetime.datetime(2012, 1, 1) - } - - serializer = self.CommentSerializerWithFieldValidator(data=data) - self.assertTrue(serializer.is_valid()) - - data['content'] = 'This should not validate' - - serializer = self.CommentSerializerWithFieldValidator(data=data) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'content': ['Test not in value']}) - - def test_missing_data(self): - """ - Make sure that validate_content isn't called if the field is missing - """ - incomplete_data = { - 'email': 'tom@example.com', - 'created': datetime.datetime(2012, 1, 1) - } - serializer = self.CommentSerializerWithFieldValidator(data=incomplete_data) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'content': ['This field is required.']}) - - def test_wrong_data(self): - """ - Make sure that validate_content isn't called if the field input is wrong - """ - wrong_data = { - 'email': 'not an email', - 'content': 'A test comment', - 'created': datetime.datetime(2012, 1, 1) - } - serializer = self.CommentSerializerWithFieldValidator(data=wrong_data) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'email': ['Enter a valid email address.']}) - - def test_partial_update(self): - """ - Make sure that validate_email isn't called when partial=True and email - isn't found in data. - """ - initial_data = { - 'email': 'tom@example.com', - 'content': 'A test comment', - 'created': datetime.datetime(2012, 1, 1) - } - - serializer = self.CommentSerializerWithFieldValidator(data=initial_data) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.object - - new_content = 'An *updated* test comment' - partial_data = { - 'content': new_content - } - - serializer = self.CommentSerializerWithFieldValidator(instance=instance, - data=partial_data, - partial=True) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.object - self.assertEqual(instance.content, new_content) - - -class PositiveIntegerAsChoiceTests(TestCase): - def test_positive_integer_in_json_is_correctly_parsed(self): - data = {'some_integer': 1} - serializer = PositiveIntegerAsChoiceSerializer(data=data) - self.assertEqual(serializer.is_valid(), True) - - -class ModelValidationTests(TestCase): - def test_validate_unique(self): - """ - Just check if serializers.ModelSerializer handles unique checks via .full_clean() - """ - serializer = AlbumsSerializer(data={'title': 'a', 'ref': '1'}) - serializer.is_valid() - serializer.save() - second_serializer = AlbumsSerializer(data={'title': 'a'}) - self.assertFalse(second_serializer.is_valid()) - self.assertEqual(second_serializer.errors, {'title': ['Album with this Title already exists.']}) - third_serializer = AlbumsSerializer(data=[{'title': 'b', 'ref': '1'}, {'title': 'c'}], many=True) - self.assertFalse(third_serializer.is_valid()) - self.assertEqual(third_serializer.errors, [{'ref': ['Album with this Ref already exists.']}, {}]) - - def test_foreign_key_is_null_with_partial(self): - """ - Test ModelSerializer validation with partial=True - - Specifically test that a null foreign key does not pass validation - """ - album = Album(title='test') - album.save() - - class PhotoSerializer(serializers.ModelSerializer): - class Meta: - model = Photo - - photo_serializer = PhotoSerializer(data={'description': 'test', 'album': album.pk}) - self.assertTrue(photo_serializer.is_valid()) - photo = photo_serializer.save() - - # Updating only the album (foreign key) - photo_serializer = PhotoSerializer(instance=photo, data={'album': ''}, partial=True) - self.assertFalse(photo_serializer.is_valid()) - self.assertTrue('album' in photo_serializer.errors) - self.assertEqual(photo_serializer.errors['album'], [photo_serializer.error_messages['required']]) - - def test_foreign_key_with_partial(self): - """ - Test ModelSerializer validation with partial=True - - Specifically test foreign key validation. - """ - - album = Album(title='test') - album.save() - - class PhotoSerializer(serializers.ModelSerializer): - class Meta: - model = Photo - - photo_serializer = PhotoSerializer(data={'description': 'test', 'album': album.pk}) - self.assertTrue(photo_serializer.is_valid()) - photo = photo_serializer.save() - - # Updating only the album (foreign key) - photo_serializer = PhotoSerializer(instance=photo, data={'album': album.pk}, partial=True) - self.assertTrue(photo_serializer.is_valid()) - self.assertTrue(photo_serializer.save()) - - # Updating only the description - photo_serializer = PhotoSerializer(instance=photo, - data={'description': 'new'}, - partial=True) - - self.assertTrue(photo_serializer.is_valid()) - self.assertTrue(photo_serializer.save()) - - -class RegexValidationTest(TestCase): - def test_create_failed(self): - serializer = BookSerializer(data={'isbn': '1234567890'}) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'isbn': ['isbn has to be exact 13 numbers']}) - - serializer = BookSerializer(data={'isbn': '12345678901234'}) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'isbn': ['isbn has to be exact 13 numbers']}) - - serializer = BookSerializer(data={'isbn': 'abcdefghijklm'}) - self.assertFalse(serializer.is_valid()) - self.assertEqual(serializer.errors, {'isbn': ['isbn has to be exact 13 numbers']}) - - def test_create_success(self): - serializer = BookSerializer(data={'isbn': '1234567890123'}) - self.assertTrue(serializer.is_valid()) - - -class MetadataTests(TestCase): - def test_empty(self): - serializer = CommentSerializer() - expected = { - 'email': serializers.CharField, - 'content': serializers.CharField, - 'created': serializers.DateTimeField - } - for field_name, field in expected.items(): - self.assertTrue(isinstance(serializer.data.fields[field_name], field)) - - -class ManyToManyTests(TestCase): - def setUp(self): - class ManyToManySerializer(serializers.ModelSerializer): - class Meta: - model = ManyToManyModel - - self.serializer_class = ManyToManySerializer - - # An anchor instance to use for the relationship - self.anchor = Anchor() - self.anchor.save() - - # A model instance with a many to many relationship to the anchor - self.instance = ManyToManyModel() - self.instance.save() - self.instance.rel.add(self.anchor) - - # A serialized representation of the model instance - self.data = {'id': 1, 'rel': [self.anchor.id]} - - def test_retrieve(self): - """ - Serialize an instance of a model with a ManyToMany relationship. - """ - serializer = self.serializer_class(instance=self.instance) - expected = self.data - self.assertEqual(serializer.data, expected) - - def test_create(self): - """ - Create an instance of a model with a ManyToMany relationship. - """ - data = {'rel': [self.anchor.id]} - serializer = self.serializer_class(data=data) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - self.assertEqual(len(ManyToManyModel.objects.all()), 2) - self.assertEqual(instance.pk, 2) - self.assertEqual(list(instance.rel.all()), [self.anchor]) - - def test_update(self): - """ - Update an instance of a model with a ManyToMany relationship. - """ - new_anchor = Anchor() - new_anchor.save() - data = {'rel': [self.anchor.id, new_anchor.id]} - serializer = self.serializer_class(self.instance, data=data) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - self.assertEqual(len(ManyToManyModel.objects.all()), 1) - self.assertEqual(instance.pk, 1) - self.assertEqual(list(instance.rel.all()), [self.anchor, new_anchor]) - - def test_create_empty_relationship(self): - """ - Create an instance of a model with a ManyToMany relationship, - containing no items. - """ - data = {'rel': []} - serializer = self.serializer_class(data=data) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - self.assertEqual(len(ManyToManyModel.objects.all()), 2) - self.assertEqual(instance.pk, 2) - self.assertEqual(list(instance.rel.all()), []) - - def test_update_empty_relationship(self): - """ - Update an instance of a model with a ManyToMany relationship, - containing no items. - """ - new_anchor = Anchor() - new_anchor.save() - data = {'rel': []} - serializer = self.serializer_class(self.instance, data=data) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - self.assertEqual(len(ManyToManyModel.objects.all()), 1) - self.assertEqual(instance.pk, 1) - self.assertEqual(list(instance.rel.all()), []) - - def test_create_empty_relationship_flat_data(self): - """ - Create an instance of a model with a ManyToMany relationship, - containing no items, using a representation that does not support - lists (eg form data). - """ - data = MultiValueDict() - data.setlist('rel', ['']) - serializer = self.serializer_class(data=data) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - self.assertEqual(len(ManyToManyModel.objects.all()), 2) - self.assertEqual(instance.pk, 2) - self.assertEqual(list(instance.rel.all()), []) - - -class ReadOnlyManyToManyTests(TestCase): - def setUp(self): - class ReadOnlyManyToManySerializer(serializers.ModelSerializer): - rel = serializers.RelatedField(many=True, read_only=True) - - class Meta: - model = ReadOnlyManyToManyModel - - self.serializer_class = ReadOnlyManyToManySerializer - - # An anchor instance to use for the relationship - self.anchor = Anchor() - self.anchor.save() - - # A model instance with a many to many relationship to the anchor - self.instance = ReadOnlyManyToManyModel() - self.instance.save() - self.instance.rel.add(self.anchor) - - # A serialized representation of the model instance - self.data = {'rel': [self.anchor.id], 'id': 1, 'text': 'anchor'} - - def test_update(self): - """ - Attempt to update an instance of a model with a ManyToMany - relationship. Not updated due to read_only=True - """ - new_anchor = Anchor() - new_anchor.save() - data = {'rel': [self.anchor.id, new_anchor.id]} - serializer = self.serializer_class(self.instance, data=data) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - self.assertEqual(len(ReadOnlyManyToManyModel.objects.all()), 1) - self.assertEqual(instance.pk, 1) - # rel is still as original (1 entry) - self.assertEqual(list(instance.rel.all()), [self.anchor]) - - def test_update_without_relationship(self): - """ - Attempt to update an instance of a model where many to ManyToMany - relationship is not supplied. Not updated due to read_only=True - """ - new_anchor = Anchor() - new_anchor.save() - data = {} - serializer = self.serializer_class(self.instance, data=data) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - self.assertEqual(len(ReadOnlyManyToManyModel.objects.all()), 1) - self.assertEqual(instance.pk, 1) - # rel is still as original (1 entry) - self.assertEqual(list(instance.rel.all()), [self.anchor]) - - -class DefaultValueTests(TestCase): - def setUp(self): - class DefaultValueSerializer(serializers.ModelSerializer): - class Meta: - model = DefaultValueModel - - self.serializer_class = DefaultValueSerializer - self.objects = DefaultValueModel.objects - - def test_create_using_default(self): - data = {} - serializer = self.serializer_class(data=data) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - self.assertEqual(len(self.objects.all()), 1) - self.assertEqual(instance.pk, 1) - self.assertEqual(instance.text, 'foobar') - - def test_create_overriding_default(self): - data = {'text': 'overridden'} - serializer = self.serializer_class(data=data) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - self.assertEqual(len(self.objects.all()), 1) - self.assertEqual(instance.pk, 1) - self.assertEqual(instance.text, 'overridden') - - def test_partial_update_default(self): - """ Regression test for issue #532 """ - data = {'text': 'overridden'} - serializer = self.serializer_class(data=data, partial=True) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - - data = {'extra': 'extra_value'} - serializer = self.serializer_class(instance=instance, data=data, partial=True) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - - self.assertEqual(instance.extra, 'extra_value') - self.assertEqual(instance.text, 'overridden') - - -class WritableFieldDefaultValueTests(TestCase): - - def setUp(self): - self.expected = {'default': 'value'} - self.create_field = fields.WritableField - - def test_get_default_value_with_noncallable(self): - field = self.create_field(default=self.expected) - got = field.get_default_value() - self.assertEqual(got, self.expected) - - def test_get_default_value_with_callable(self): - field = self.create_field(default=lambda: self.expected) - got = field.get_default_value() - self.assertEqual(got, self.expected) - - def test_get_default_value_when_not_required(self): - field = self.create_field(default=self.expected, required=False) - got = field.get_default_value() - self.assertEqual(got, self.expected) - - def test_get_default_value_returns_None(self): - field = self.create_field() - got = field.get_default_value() - self.assertIsNone(got) - - def test_get_default_value_returns_non_True_values(self): - values = [None, '', False, 0, [], (), {}] # values that assumed as 'False' in the 'if' clause - for expected in values: - field = self.create_field(default=expected) - got = field.get_default_value() - self.assertEqual(got, expected) - - -class RelatedFieldDefaultValueTests(WritableFieldDefaultValueTests): - - def setUp(self): - self.expected = {'foo': 'bar'} - self.create_field = relations.RelatedField - - def test_get_default_value_returns_empty_list(self): - field = self.create_field(many=True) - got = field.get_default_value() - self.assertListEqual(got, []) - - def test_get_default_value_returns_expected(self): - expected = [1, 2, 3] - field = self.create_field(many=True, default=expected) - got = field.get_default_value() - self.assertListEqual(got, expected) - - -class CallableDefaultValueTests(TestCase): - def setUp(self): - class CallableDefaultValueSerializer(serializers.ModelSerializer): - class Meta: - model = CallableDefaultValueModel - - self.serializer_class = CallableDefaultValueSerializer - self.objects = CallableDefaultValueModel.objects - - def test_create_using_default(self): - data = {} - serializer = self.serializer_class(data=data) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - self.assertEqual(len(self.objects.all()), 1) - self.assertEqual(instance.pk, 1) - self.assertEqual(instance.text, 'foobar') - - def test_create_overriding_default(self): - data = {'text': 'overridden'} - serializer = self.serializer_class(data=data) - self.assertEqual(serializer.is_valid(), True) - instance = serializer.save() - self.assertEqual(len(self.objects.all()), 1) - self.assertEqual(instance.pk, 1) - self.assertEqual(instance.text, 'overridden') - - -class ManyRelatedTests(TestCase): - def test_reverse_relations(self): - post = BlogPost.objects.create(title="Test blog post") - post.blogpostcomment_set.create(text="I hate this blog post") - post.blogpostcomment_set.create(text="I love this blog post") - - class BlogPostCommentSerializer(serializers.Serializer): - text = serializers.CharField() - - class BlogPostSerializer(serializers.Serializer): - title = serializers.CharField() - comments = BlogPostCommentSerializer(source='blogpostcomment_set') - - serializer = BlogPostSerializer(instance=post) - expected = { - 'title': 'Test blog post', - 'comments': [ - {'text': 'I hate this blog post'}, - {'text': 'I love this blog post'} - ] - } - - self.assertEqual(serializer.data, expected) - - def test_include_reverse_relations(self): - post = BlogPost.objects.create(title="Test blog post") - post.blogpostcomment_set.create(text="I hate this blog post") - post.blogpostcomment_set.create(text="I love this blog post") - - class BlogPostSerializer(serializers.ModelSerializer): - class Meta: - model = BlogPost - fields = ('id', 'title', 'blogpostcomment_set') - - serializer = BlogPostSerializer(instance=post) - expected = { - 'id': 1, 'title': 'Test blog post', 'blogpostcomment_set': [1, 2] - } - self.assertEqual(serializer.data, expected) - - def test_depth_include_reverse_relations(self): - post = BlogPost.objects.create(title="Test blog post") - post.blogpostcomment_set.create(text="I hate this blog post") - post.blogpostcomment_set.create(text="I love this blog post") - - class BlogPostSerializer(serializers.ModelSerializer): - class Meta: - model = BlogPost - fields = ('id', 'title', 'blogpostcomment_set') - depth = 1 - - serializer = BlogPostSerializer(instance=post) - expected = { - 'id': 1, 'title': 'Test blog post', - 'blogpostcomment_set': [ - {'id': 1, 'text': 'I hate this blog post', 'blog_post': 1}, - {'id': 2, 'text': 'I love this blog post', 'blog_post': 1} - ] - } - self.assertEqual(serializer.data, expected) - - def test_callable_source(self): - post = BlogPost.objects.create(title="Test blog post") - post.blogpostcomment_set.create(text="I love this blog post") - - class BlogPostCommentSerializer(serializers.Serializer): - text = serializers.CharField() - - class BlogPostSerializer(serializers.Serializer): - title = serializers.CharField() - first_comment = BlogPostCommentSerializer(source='get_first_comment') - - serializer = BlogPostSerializer(post) - - expected = { - 'title': 'Test blog post', - 'first_comment': {'text': 'I love this blog post'} - } - self.assertEqual(serializer.data, expected) - - -class RelatedTraversalTest(TestCase): - def test_nested_traversal(self): - """ - Source argument should support dotted.source notation. - """ - user = Person.objects.create(name="django") - post = BlogPost.objects.create(title="Test blog post", writer=user) - post.blogpostcomment_set.create(text="I love this blog post") +# class BasicTests(TestCase): +# def setUp(self): +# self.comment = Comment( +# 'tom@example.com', +# 'Happy new year!', +# datetime.datetime(2012, 1, 1) +# ) +# self.actionitem = ActionItem(title='Some to do item',) +# self.data = { +# 'email': 'tom@example.com', +# 'content': 'Happy new year!', +# 'created': datetime.datetime(2012, 1, 1), +# 'sub_comment': 'This wont change' +# } +# self.expected = { +# 'email': 'tom@example.com', +# 'content': 'Happy new year!', +# 'created': datetime.datetime(2012, 1, 1), +# 'sub_comment': 'And Merry Christmas!' +# } +# self.person_data = {'name': 'dwight', 'age': 35} +# self.person = Person(**self.person_data) +# self.person.save() + +# def test_empty(self): +# serializer = CommentSerializer() +# expected = { +# 'email': '', +# 'content': '', +# 'created': None +# } +# self.assertEqual(serializer.data, expected) + +# def test_retrieve(self): +# serializer = CommentSerializer(self.comment) +# self.assertEqual(serializer.data, self.expected) + +# def test_create(self): +# serializer = CommentSerializer(data=self.data) +# expected = self.comment +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.object, expected) +# self.assertFalse(serializer.object is expected) +# self.assertEqual(serializer.data['sub_comment'], 'And Merry Christmas!') + +# def test_create_nested(self): +# """Test a serializer with nested data.""" +# names = {'first': 'John', 'last': 'Doe', 'initials': 'jd'} +# data = {'ssn': '1234567890', 'names': names} +# serializer = PersonIdentifierSerializer(data=data) + +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.object, data) +# self.assertFalse(serializer.object is data) +# self.assertEqual(serializer.data['names'], names) + +# def test_create_partial_nested(self): +# """Test a serializer with nested data which has missing fields.""" +# names = {'first': 'John'} +# data = {'ssn': '1234567890', 'names': names} +# serializer = PersonIdentifierSerializer(data=data) + +# expected_names = {'first': 'John', 'last': '', 'initials': ''} +# data['names'] = expected_names + +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.object, data) +# self.assertFalse(serializer.object is expected_names) +# self.assertEqual(serializer.data['names'], expected_names) + +# def test_null_nested(self): +# """Test a serializer with a nonexistent nested field""" +# data = {'ssn': '1234567890'} +# serializer = PersonIdentifierSerializer(data=data) + +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.object, data) +# self.assertFalse(serializer.object is data) +# expected = {'ssn': '1234567890', 'names': None} +# self.assertEqual(serializer.data, expected) + +# def test_update(self): +# serializer = CommentSerializer(self.comment, data=self.data) +# expected = self.comment +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.object, expected) +# self.assertTrue(serializer.object is expected) +# self.assertEqual(serializer.data['sub_comment'], 'And Merry Christmas!') + +# def test_partial_update(self): +# msg = 'Merry New Year!' +# partial_data = {'content': msg} +# serializer = CommentSerializer(self.comment, data=partial_data) +# self.assertEqual(serializer.is_valid(), False) +# serializer = CommentSerializer(self.comment, data=partial_data, partial=True) +# expected = self.comment +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.object, expected) +# self.assertTrue(serializer.object is expected) +# self.assertEqual(serializer.data['content'], msg) + +# def test_model_fields_as_expected(self): +# """ +# Make sure that the fields returned are the same as defined +# in the Meta data +# """ +# serializer = PersonSerializer(self.person) +# self.assertEqual( +# set(serializer.data.keys()), +# set(['name', 'age', 'info']) +# ) + +# def test_field_with_dictionary(self): +# """ +# Make sure that dictionaries from fields are left intact +# """ +# serializer = PersonSerializer(self.person) +# expected = self.person_data +# self.assertEqual(serializer.data['info'], expected) + +# def test_read_only_fields(self): +# """ +# Attempting to update fields set as read_only should have no effect. +# """ +# serializer = PersonSerializer(self.person, data={'name': 'dwight', 'age': 99}) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() +# self.assertEqual(serializer.errors, {}) +# # Assert age is unchanged (35) +# self.assertEqual(instance.age, self.person_data['age']) + +# def test_invalid_read_only_fields(self): +# """ +# Regression test for #652. +# """ +# self.assertRaises(AssertionError, PersonSerializerInvalidReadOnly, []) + +# def test_serializer_data_is_cleared_on_save(self): +# """ +# Check _data attribute is cleared on `save()` + +# Regression test for #1116 +# — id field is not populated if `data` is accessed prior to `save()` +# """ +# serializer = ActionItemSerializer(self.actionitem) +# self.assertIsNone(serializer.data.get('id', None), 'New instance. `id` should not be set.') +# serializer.save() +# self.assertIsNotNone(serializer.data.get('id', None), 'Model is saved. `id` should be set.') + +# def test_fields_marked_as_not_required_are_excluded_from_validation(self): +# """ +# Check that fields with `required=False` are included in list of exclusions. +# """ +# serializer = ActionItemSerializerOptionalFields(self.actionitem) +# exclusions = serializer.get_validation_exclusions() +# self.assertTrue('title' in exclusions, '`title` field was marked `required=False` and should be excluded') + + +# class DictStyleSerializer(serializers.Serializer): +# """ +# Note that we don't have any `restore_object` method, so the default +# case of simply returning a dict will apply. +# """ +# email = serializers.EmailField() + + +# class DictStyleSerializerTests(TestCase): +# def test_dict_style_deserialize(self): +# """ +# Ensure serializers can deserialize into a dict. +# """ +# data = {'email': 'foo@example.com'} +# serializer = DictStyleSerializer(data=data) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.data, data) + +# def test_dict_style_serialize(self): +# """ +# Ensure serializers can serialize dict objects. +# """ +# data = {'email': 'foo@example.com'} +# serializer = DictStyleSerializer(data) +# self.assertEqual(serializer.data, data) + + +# class ValidationTests(TestCase): +# def setUp(self): +# self.comment = Comment( +# 'tom@example.com', +# 'Happy new year!', +# datetime.datetime(2012, 1, 1) +# ) +# self.data = { +# 'email': 'tom@example.com', +# 'content': 'x' * 1001, +# 'created': datetime.datetime(2012, 1, 1) +# } +# self.actionitem = ActionItem(title='Some to do item',) + +# def test_create(self): +# serializer = CommentSerializer(data=self.data) +# self.assertEqual(serializer.is_valid(), False) +# self.assertEqual(serializer.errors, {'content': ['Ensure this value has at most 1000 characters (it has 1001).']}) + +# def test_update(self): +# serializer = CommentSerializer(self.comment, data=self.data) +# self.assertEqual(serializer.is_valid(), False) +# self.assertEqual(serializer.errors, {'content': ['Ensure this value has at most 1000 characters (it has 1001).']}) + +# def test_update_missing_field(self): +# data = { +# 'content': 'xxx', +# 'created': datetime.datetime(2012, 1, 1) +# } +# serializer = CommentSerializer(self.comment, data=data) +# self.assertEqual(serializer.is_valid(), False) +# self.assertEqual(serializer.errors, {'email': ['This field is required.']}) + +# def test_missing_bool_with_default(self): +# """Make sure that a boolean value with a 'False' value is not +# mistaken for not having a default.""" +# data = { +# 'title': 'Some action item', +# # No 'done' value. +# } +# serializer = ActionItemSerializer(self.actionitem, data=data) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.errors, {}) + +# def test_cross_field_validation(self): + +# class CommentSerializerWithCrossFieldValidator(CommentSerializer): + +# def validate(self, attrs): +# if attrs["email"] not in attrs["content"]: +# raise serializers.ValidationError("Email address not in content") +# return attrs + +# data = { +# 'email': 'tom@example.com', +# 'content': 'A comment from tom@example.com', +# 'created': datetime.datetime(2012, 1, 1) +# } + +# serializer = CommentSerializerWithCrossFieldValidator(data=data) +# self.assertTrue(serializer.is_valid()) + +# data['content'] = 'A comment from foo@bar.com' + +# serializer = CommentSerializerWithCrossFieldValidator(data=data) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'non_field_errors': ['Email address not in content']}) + +# def test_null_is_true_fields(self): +# """ +# Omitting a value for null-field should validate. +# """ +# serializer = PersonSerializer(data={'name': 'marko'}) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.errors, {}) + +# def test_modelserializer_max_length_exceeded(self): +# data = { +# 'title': 'x' * 201, +# } +# serializer = ActionItemSerializer(data=data) +# self.assertEqual(serializer.is_valid(), False) +# self.assertEqual(serializer.errors, {'title': ['Ensure this value has at most 200 characters (it has 201).']}) + +# def test_modelserializer_max_length_exceeded_with_custom_restore(self): +# """ +# When overriding ModelSerializer.restore_object, validation tests should still apply. +# Regression test for #623. + +# https://github.com/tomchristie/django-rest-framework/pull/623 +# """ +# data = { +# 'title': 'x' * 201, +# } +# serializer = ActionItemSerializerCustomRestore(data=data) +# self.assertEqual(serializer.is_valid(), False) +# self.assertEqual(serializer.errors, {'title': ['Ensure this value has at most 200 characters (it has 201).']}) + +# def test_default_modelfield_max_length_exceeded(self): +# data = { +# 'title': 'Testing "info" field...', +# 'info': 'x' * 13, +# } +# serializer = ActionItemSerializer(data=data) +# self.assertEqual(serializer.is_valid(), False) +# self.assertEqual(serializer.errors, {'info': ['Ensure this value has at most 12 characters (it has 13).']}) + +# def test_datetime_validation_failure(self): +# """ +# Test DateTimeField validation errors on non-str values. +# Regression test for #669. + +# https://github.com/tomchristie/django-rest-framework/issues/669 +# """ +# data = self.data +# data['created'] = 0 + +# serializer = CommentSerializer(data=data) +# self.assertEqual(serializer.is_valid(), False) + +# self.assertIn('created', serializer.errors) + +# def test_missing_model_field_exception_msg(self): +# """ +# Assert that a meaningful exception message is outputted when the model +# field is missing (e.g. when mistyping ``model``). +# """ +# class BrokenModelSerializer(serializers.ModelSerializer): +# class Meta: +# fields = ['some_field'] + +# try: +# BrokenModelSerializer() +# except AssertionError as e: +# self.assertEqual(e.args[0], "Serializer class 'BrokenModelSerializer' is missing 'model' Meta option") +# except: +# self.fail('Wrong exception type thrown.') + +# def test_writable_star_source_on_nested_serializer(self): +# """ +# Assert that a nested serializer instantiated with source='*' correctly +# expands the data into the outer serializer. +# """ +# serializer = ModelSerializerWithNestedSerializer(data={ +# 'name': 'marko', +# 'nested': {'info': 'hi'}}, +# ) +# self.assertEqual(serializer.is_valid(), True) + +# def test_writable_star_source_on_nested_serializer_with_parent_object(self): +# class TitleSerializer(serializers.Serializer): +# title = serializers.WritableField(source='title') + +# class AlbumSerializer(serializers.ModelSerializer): +# nested = TitleSerializer(source='*') + +# class Meta: +# model = Album +# fields = ('nested',) + +# class PhotoSerializer(serializers.ModelSerializer): +# album = AlbumSerializer(source='album') + +# class Meta: +# model = Photo +# fields = ('album', ) + +# photo = Photo(album=Album()) + +# data = {'album': {'nested': {'title': 'test'}}} + +# serializer = PhotoSerializer(photo, data=data) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.data, data) + +# def test_writable_star_source_with_inner_source_fields(self): +# """ +# Tests that a serializer with source="*" correctly expands the +# it's fields into the outer serializer even if they have their +# own 'source' parameters. +# """ + +# serializer = ModelSerializerWithNestedSerializerWithRenamedField(data={ +# 'name': 'marko', +# 'nested': {'renamed_info': 'hi'}}, +# ) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.errors, {}) + + +# class CustomValidationTests(TestCase): +# class CommentSerializerWithFieldValidator(CommentSerializer): + +# def validate_email(self, attrs, source): +# attrs[source] +# return attrs + +# def validate_content(self, attrs, source): +# value = attrs[source] +# if "test" not in value: +# raise serializers.ValidationError("Test not in value") +# return attrs + +# def test_field_validation(self): +# data = { +# 'email': 'tom@example.com', +# 'content': 'A test comment', +# 'created': datetime.datetime(2012, 1, 1) +# } + +# serializer = self.CommentSerializerWithFieldValidator(data=data) +# self.assertTrue(serializer.is_valid()) + +# data['content'] = 'This should not validate' + +# serializer = self.CommentSerializerWithFieldValidator(data=data) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'content': ['Test not in value']}) + +# def test_missing_data(self): +# """ +# Make sure that validate_content isn't called if the field is missing +# """ +# incomplete_data = { +# 'email': 'tom@example.com', +# 'created': datetime.datetime(2012, 1, 1) +# } +# serializer = self.CommentSerializerWithFieldValidator(data=incomplete_data) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'content': ['This field is required.']}) + +# def test_wrong_data(self): +# """ +# Make sure that validate_content isn't called if the field input is wrong +# """ +# wrong_data = { +# 'email': 'not an email', +# 'content': 'A test comment', +# 'created': datetime.datetime(2012, 1, 1) +# } +# serializer = self.CommentSerializerWithFieldValidator(data=wrong_data) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'email': ['Enter a valid email address.']}) + +# def test_partial_update(self): +# """ +# Make sure that validate_email isn't called when partial=True and email +# isn't found in data. +# """ +# initial_data = { +# 'email': 'tom@example.com', +# 'content': 'A test comment', +# 'created': datetime.datetime(2012, 1, 1) +# } + +# serializer = self.CommentSerializerWithFieldValidator(data=initial_data) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.object + +# new_content = 'An *updated* test comment' +# partial_data = { +# 'content': new_content +# } + +# serializer = self.CommentSerializerWithFieldValidator(instance=instance, +# data=partial_data, +# partial=True) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.object +# self.assertEqual(instance.content, new_content) + + +# class PositiveIntegerAsChoiceTests(TestCase): +# def test_positive_integer_in_json_is_correctly_parsed(self): +# data = {'some_integer': 1} +# serializer = PositiveIntegerAsChoiceSerializer(data=data) +# self.assertEqual(serializer.is_valid(), True) + + +# class ModelValidationTests(TestCase): +# def test_validate_unique(self): +# """ +# Just check if serializers.ModelSerializer handles unique checks via .full_clean() +# """ +# serializer = AlbumsSerializer(data={'title': 'a', 'ref': '1'}) +# serializer.is_valid() +# serializer.save() +# second_serializer = AlbumsSerializer(data={'title': 'a'}) +# self.assertFalse(second_serializer.is_valid()) +# self.assertEqual(second_serializer.errors, {'title': ['Album with this Title already exists.']}) +# third_serializer = AlbumsSerializer(data=[{'title': 'b', 'ref': '1'}, {'title': 'c'}], many=True) +# self.assertFalse(third_serializer.is_valid()) +# self.assertEqual(third_serializer.errors, [{'ref': ['Album with this Ref already exists.']}, {}]) + +# def test_foreign_key_is_null_with_partial(self): +# """ +# Test ModelSerializer validation with partial=True + +# Specifically test that a null foreign key does not pass validation +# """ +# album = Album(title='test') +# album.save() + +# class PhotoSerializer(serializers.ModelSerializer): +# class Meta: +# model = Photo + +# photo_serializer = PhotoSerializer(data={'description': 'test', 'album': album.pk}) +# self.assertTrue(photo_serializer.is_valid()) +# photo = photo_serializer.save() + +# # Updating only the album (foreign key) +# photo_serializer = PhotoSerializer(instance=photo, data={'album': ''}, partial=True) +# self.assertFalse(photo_serializer.is_valid()) +# self.assertTrue('album' in photo_serializer.errors) +# self.assertEqual(photo_serializer.errors['album'], [photo_serializer.error_messages['required']]) + +# def test_foreign_key_with_partial(self): +# """ +# Test ModelSerializer validation with partial=True + +# Specifically test foreign key validation. +# """ + +# album = Album(title='test') +# album.save() + +# class PhotoSerializer(serializers.ModelSerializer): +# class Meta: +# model = Photo + +# photo_serializer = PhotoSerializer(data={'description': 'test', 'album': album.pk}) +# self.assertTrue(photo_serializer.is_valid()) +# photo = photo_serializer.save() + +# # Updating only the album (foreign key) +# photo_serializer = PhotoSerializer(instance=photo, data={'album': album.pk}, partial=True) +# self.assertTrue(photo_serializer.is_valid()) +# self.assertTrue(photo_serializer.save()) + +# # Updating only the description +# photo_serializer = PhotoSerializer(instance=photo, +# data={'description': 'new'}, +# partial=True) + +# self.assertTrue(photo_serializer.is_valid()) +# self.assertTrue(photo_serializer.save()) + + +# class RegexValidationTest(TestCase): +# def test_create_failed(self): +# serializer = BookSerializer(data={'isbn': '1234567890'}) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'isbn': ['isbn has to be exact 13 numbers']}) + +# serializer = BookSerializer(data={'isbn': '12345678901234'}) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'isbn': ['isbn has to be exact 13 numbers']}) + +# serializer = BookSerializer(data={'isbn': 'abcdefghijklm'}) +# self.assertFalse(serializer.is_valid()) +# self.assertEqual(serializer.errors, {'isbn': ['isbn has to be exact 13 numbers']}) + +# def test_create_success(self): +# serializer = BookSerializer(data={'isbn': '1234567890123'}) +# self.assertTrue(serializer.is_valid()) + + +# class MetadataTests(TestCase): +# def test_empty(self): +# serializer = CommentSerializer() +# expected = { +# 'email': serializers.CharField, +# 'content': serializers.CharField, +# 'created': serializers.DateTimeField +# } +# for field_name, field in expected.items(): +# self.assertTrue(isinstance(serializer.data.fields[field_name], field)) + + +# class ManyToManyTests(TestCase): +# def setUp(self): +# class ManyToManySerializer(serializers.ModelSerializer): +# class Meta: +# model = ManyToManyModel + +# self.serializer_class = ManyToManySerializer + +# # An anchor instance to use for the relationship +# self.anchor = Anchor() +# self.anchor.save() + +# # A model instance with a many to many relationship to the anchor +# self.instance = ManyToManyModel() +# self.instance.save() +# self.instance.rel.add(self.anchor) + +# # A serialized representation of the model instance +# self.data = {'id': 1, 'rel': [self.anchor.id]} + +# def test_retrieve(self): +# """ +# Serialize an instance of a model with a ManyToMany relationship. +# """ +# serializer = self.serializer_class(instance=self.instance) +# expected = self.data +# self.assertEqual(serializer.data, expected) + +# def test_create(self): +# """ +# Create an instance of a model with a ManyToMany relationship. +# """ +# data = {'rel': [self.anchor.id]} +# serializer = self.serializer_class(data=data) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() +# self.assertEqual(len(ManyToManyModel.objects.all()), 2) +# self.assertEqual(instance.pk, 2) +# self.assertEqual(list(instance.rel.all()), [self.anchor]) + +# def test_update(self): +# """ +# Update an instance of a model with a ManyToMany relationship. +# """ +# new_anchor = Anchor() +# new_anchor.save() +# data = {'rel': [self.anchor.id, new_anchor.id]} +# serializer = self.serializer_class(self.instance, data=data) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() +# self.assertEqual(len(ManyToManyModel.objects.all()), 1) +# self.assertEqual(instance.pk, 1) +# self.assertEqual(list(instance.rel.all()), [self.anchor, new_anchor]) + +# def test_create_empty_relationship(self): +# """ +# Create an instance of a model with a ManyToMany relationship, +# containing no items. +# """ +# data = {'rel': []} +# serializer = self.serializer_class(data=data) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() +# self.assertEqual(len(ManyToManyModel.objects.all()), 2) +# self.assertEqual(instance.pk, 2) +# self.assertEqual(list(instance.rel.all()), []) + +# def test_update_empty_relationship(self): +# """ +# Update an instance of a model with a ManyToMany relationship, +# containing no items. +# """ +# new_anchor = Anchor() +# new_anchor.save() +# data = {'rel': []} +# serializer = self.serializer_class(self.instance, data=data) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() +# self.assertEqual(len(ManyToManyModel.objects.all()), 1) +# self.assertEqual(instance.pk, 1) +# self.assertEqual(list(instance.rel.all()), []) + +# def test_create_empty_relationship_flat_data(self): +# """ +# Create an instance of a model with a ManyToMany relationship, +# containing no items, using a representation that does not support +# lists (eg form data). +# """ +# data = MultiValueDict() +# data.setlist('rel', ['']) +# serializer = self.serializer_class(data=data) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() +# self.assertEqual(len(ManyToManyModel.objects.all()), 2) +# self.assertEqual(instance.pk, 2) +# self.assertEqual(list(instance.rel.all()), []) + + +# class ReadOnlyManyToManyTests(TestCase): +# def setUp(self): +# class ReadOnlyManyToManySerializer(serializers.ModelSerializer): +# rel = serializers.RelatedField(many=True, read_only=True) + +# class Meta: +# model = ReadOnlyManyToManyModel + +# self.serializer_class = ReadOnlyManyToManySerializer + +# # An anchor instance to use for the relationship +# self.anchor = Anchor() +# self.anchor.save() + +# # A model instance with a many to many relationship to the anchor +# self.instance = ReadOnlyManyToManyModel() +# self.instance.save() +# self.instance.rel.add(self.anchor) + +# # A serialized representation of the model instance +# self.data = {'rel': [self.anchor.id], 'id': 1, 'text': 'anchor'} + +# def test_update(self): +# """ +# Attempt to update an instance of a model with a ManyToMany +# relationship. Not updated due to read_only=True +# """ +# new_anchor = Anchor() +# new_anchor.save() +# data = {'rel': [self.anchor.id, new_anchor.id]} +# serializer = self.serializer_class(self.instance, data=data) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() +# self.assertEqual(len(ReadOnlyManyToManyModel.objects.all()), 1) +# self.assertEqual(instance.pk, 1) +# # rel is still as original (1 entry) +# self.assertEqual(list(instance.rel.all()), [self.anchor]) + +# def test_update_without_relationship(self): +# """ +# Attempt to update an instance of a model where many to ManyToMany +# relationship is not supplied. Not updated due to read_only=True +# """ +# new_anchor = Anchor() +# new_anchor.save() +# data = {} +# serializer = self.serializer_class(self.instance, data=data) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() +# self.assertEqual(len(ReadOnlyManyToManyModel.objects.all()), 1) +# self.assertEqual(instance.pk, 1) +# # rel is still as original (1 entry) +# self.assertEqual(list(instance.rel.all()), [self.anchor]) + + +# class DefaultValueTests(TestCase): +# def setUp(self): +# class DefaultValueSerializer(serializers.ModelSerializer): +# class Meta: +# model = DefaultValueModel + +# self.serializer_class = DefaultValueSerializer +# self.objects = DefaultValueModel.objects + +# def test_create_using_default(self): +# data = {} +# serializer = self.serializer_class(data=data) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() +# self.assertEqual(len(self.objects.all()), 1) +# self.assertEqual(instance.pk, 1) +# self.assertEqual(instance.text, 'foobar') + +# def test_create_overriding_default(self): +# data = {'text': 'overridden'} +# serializer = self.serializer_class(data=data) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() +# self.assertEqual(len(self.objects.all()), 1) +# self.assertEqual(instance.pk, 1) +# self.assertEqual(instance.text, 'overridden') + +# def test_partial_update_default(self): +# """ Regression test for issue #532 """ +# data = {'text': 'overridden'} +# serializer = self.serializer_class(data=data, partial=True) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() + +# data = {'extra': 'extra_value'} +# serializer = self.serializer_class(instance=instance, data=data, partial=True) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() + +# self.assertEqual(instance.extra, 'extra_value') +# self.assertEqual(instance.text, 'overridden') + + +# class WritableFieldDefaultValueTests(TestCase): + +# def setUp(self): +# self.expected = {'default': 'value'} +# self.create_field = fields.WritableField + +# def test_get_default_value_with_noncallable(self): +# field = self.create_field(default=self.expected) +# got = field.get_default_value() +# self.assertEqual(got, self.expected) + +# def test_get_default_value_with_callable(self): +# field = self.create_field(default=lambda: self.expected) +# got = field.get_default_value() +# self.assertEqual(got, self.expected) + +# def test_get_default_value_when_not_required(self): +# field = self.create_field(default=self.expected, required=False) +# got = field.get_default_value() +# self.assertEqual(got, self.expected) + +# def test_get_default_value_returns_None(self): +# field = self.create_field() +# got = field.get_default_value() +# self.assertIsNone(got) + +# def test_get_default_value_returns_non_True_values(self): +# values = [None, '', False, 0, [], (), {}] # values that assumed as 'False' in the 'if' clause +# for expected in values: +# field = self.create_field(default=expected) +# got = field.get_default_value() +# self.assertEqual(got, expected) + + +# class RelatedFieldDefaultValueTests(WritableFieldDefaultValueTests): + +# def setUp(self): +# self.expected = {'foo': 'bar'} +# self.create_field = relations.RelatedField + +# def test_get_default_value_returns_empty_list(self): +# field = self.create_field(many=True) +# got = field.get_default_value() +# self.assertListEqual(got, []) + +# def test_get_default_value_returns_expected(self): +# expected = [1, 2, 3] +# field = self.create_field(many=True, default=expected) +# got = field.get_default_value() +# self.assertListEqual(got, expected) + + +# class CallableDefaultValueTests(TestCase): +# def setUp(self): +# class CallableDefaultValueSerializer(serializers.ModelSerializer): +# class Meta: +# model = CallableDefaultValueModel + +# self.serializer_class = CallableDefaultValueSerializer +# self.objects = CallableDefaultValueModel.objects + +# def test_create_using_default(self): +# data = {} +# serializer = self.serializer_class(data=data) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() +# self.assertEqual(len(self.objects.all()), 1) +# self.assertEqual(instance.pk, 1) +# self.assertEqual(instance.text, 'foobar') + +# def test_create_overriding_default(self): +# data = {'text': 'overridden'} +# serializer = self.serializer_class(data=data) +# self.assertEqual(serializer.is_valid(), True) +# instance = serializer.save() +# self.assertEqual(len(self.objects.all()), 1) +# self.assertEqual(instance.pk, 1) +# self.assertEqual(instance.text, 'overridden') + + +# class ManyRelatedTests(TestCase): +# def test_reverse_relations(self): +# post = BlogPost.objects.create(title="Test blog post") +# post.blogpostcomment_set.create(text="I hate this blog post") +# post.blogpostcomment_set.create(text="I love this blog post") + +# class BlogPostCommentSerializer(serializers.Serializer): +# text = serializers.CharField() + +# class BlogPostSerializer(serializers.Serializer): +# title = serializers.CharField() +# comments = BlogPostCommentSerializer(source='blogpostcomment_set') + +# serializer = BlogPostSerializer(instance=post) +# expected = { +# 'title': 'Test blog post', +# 'comments': [ +# {'text': 'I hate this blog post'}, +# {'text': 'I love this blog post'} +# ] +# } + +# self.assertEqual(serializer.data, expected) + +# def test_include_reverse_relations(self): +# post = BlogPost.objects.create(title="Test blog post") +# post.blogpostcomment_set.create(text="I hate this blog post") +# post.blogpostcomment_set.create(text="I love this blog post") + +# class BlogPostSerializer(serializers.ModelSerializer): +# class Meta: +# model = BlogPost +# fields = ('id', 'title', 'blogpostcomment_set') + +# serializer = BlogPostSerializer(instance=post) +# expected = { +# 'id': 1, 'title': 'Test blog post', 'blogpostcomment_set': [1, 2] +# } +# self.assertEqual(serializer.data, expected) + +# def test_depth_include_reverse_relations(self): +# post = BlogPost.objects.create(title="Test blog post") +# post.blogpostcomment_set.create(text="I hate this blog post") +# post.blogpostcomment_set.create(text="I love this blog post") + +# class BlogPostSerializer(serializers.ModelSerializer): +# class Meta: +# model = BlogPost +# fields = ('id', 'title', 'blogpostcomment_set') +# depth = 1 + +# serializer = BlogPostSerializer(instance=post) +# expected = { +# 'id': 1, 'title': 'Test blog post', +# 'blogpostcomment_set': [ +# {'id': 1, 'text': 'I hate this blog post', 'blog_post': 1}, +# {'id': 2, 'text': 'I love this blog post', 'blog_post': 1} +# ] +# } +# self.assertEqual(serializer.data, expected) + +# def test_callable_source(self): +# post = BlogPost.objects.create(title="Test blog post") +# post.blogpostcomment_set.create(text="I love this blog post") + +# class BlogPostCommentSerializer(serializers.Serializer): +# text = serializers.CharField() + +# class BlogPostSerializer(serializers.Serializer): +# title = serializers.CharField() +# first_comment = BlogPostCommentSerializer(source='get_first_comment') + +# serializer = BlogPostSerializer(post) + +# expected = { +# 'title': 'Test blog post', +# 'first_comment': {'text': 'I love this blog post'} +# } +# self.assertEqual(serializer.data, expected) + + +# class RelatedTraversalTest(TestCase): +# def test_nested_traversal(self): +# """ +# Source argument should support dotted.source notation. +# """ +# user = Person.objects.create(name="django") +# post = BlogPost.objects.create(title="Test blog post", writer=user) +# post.blogpostcomment_set.create(text="I love this blog post") - class PersonSerializer(serializers.ModelSerializer): - class Meta: - model = Person - fields = ("name", "age") +# class PersonSerializer(serializers.ModelSerializer): +# class Meta: +# model = Person +# fields = ("name", "age") - class BlogPostCommentSerializer(serializers.ModelSerializer): - class Meta: - model = BlogPostComment - fields = ("text", "post_owner") +# class BlogPostCommentSerializer(serializers.ModelSerializer): +# class Meta: +# model = BlogPostComment +# fields = ("text", "post_owner") - text = serializers.CharField() - post_owner = PersonSerializer(source='blog_post.writer') +# text = serializers.CharField() +# post_owner = PersonSerializer(source='blog_post.writer') - class BlogPostSerializer(serializers.Serializer): - title = serializers.CharField() - comments = BlogPostCommentSerializer(source='blogpostcomment_set') +# class BlogPostSerializer(serializers.Serializer): +# title = serializers.CharField() +# comments = BlogPostCommentSerializer(source='blogpostcomment_set') - serializer = BlogPostSerializer(instance=post) +# serializer = BlogPostSerializer(instance=post) - expected = { - 'title': 'Test blog post', - 'comments': [{ - 'text': 'I love this blog post', - 'post_owner': { - "name": "django", - "age": None - } - }] - } - - self.assertEqual(serializer.data, expected) +# expected = { +# 'title': 'Test blog post', +# 'comments': [{ +# 'text': 'I love this blog post', +# 'post_owner': { +# "name": "django", +# "age": None +# } +# }] +# } + +# self.assertEqual(serializer.data, expected) - def test_nested_traversal_with_none(self): - """ - If a component of the dotted.source is None, return None for the field. - """ - from tests.models import NullableForeignKeySource - instance = NullableForeignKeySource.objects.create(name='Source with null FK') - - class NullableSourceSerializer(serializers.Serializer): - target_name = serializers.Field(source='target.name') - - serializer = NullableSourceSerializer(instance=instance) - - expected = { - 'target_name': None, - } - - self.assertEqual(serializer.data, expected) - - -class SerializerMethodFieldTests(TestCase): - def setUp(self): - - class BoopSerializer(serializers.Serializer): - beep = serializers.SerializerMethodField('get_beep') - boop = serializers.Field() - boop_count = serializers.SerializerMethodField('get_boop_count') - - def get_beep(self, obj): - return 'hello!' - - def get_boop_count(self, obj): - return len(obj.boop) - - self.serializer_class = BoopSerializer - - def test_serializer_method_field(self): - - class MyModel(object): - boop = ['a', 'b', 'c'] - - source_data = MyModel() - - serializer = self.serializer_class(source_data) - - expected = { - 'beep': 'hello!', - 'boop': ['a', 'b', 'c'], - 'boop_count': 3, - } - - self.assertEqual(serializer.data, expected) - - -# Test for issue #324 -class BlankFieldTests(TestCase): - def setUp(self): - - class BlankFieldModelSerializer(serializers.ModelSerializer): - class Meta: - model = BlankFieldModel - - class BlankFieldSerializer(serializers.Serializer): - title = serializers.CharField(required=False) - - class NotBlankFieldModelSerializer(serializers.ModelSerializer): - class Meta: - model = BasicModel - - class NotBlankFieldSerializer(serializers.Serializer): - title = serializers.CharField() - - self.model_serializer_class = BlankFieldModelSerializer - self.serializer_class = BlankFieldSerializer - self.not_blank_model_serializer_class = NotBlankFieldModelSerializer - self.not_blank_serializer_class = NotBlankFieldSerializer - self.data = {'title': ''} - - def test_create_blank_field(self): - serializer = self.serializer_class(data=self.data) - self.assertEqual(serializer.is_valid(), True) - - def test_create_model_blank_field(self): - serializer = self.model_serializer_class(data=self.data) - self.assertEqual(serializer.is_valid(), True) - - def test_create_model_null_field(self): - serializer = self.model_serializer_class(data={'title': None}) - self.assertEqual(serializer.is_valid(), True) - serializer.save() - self.assertIsNot(serializer.object.pk, None) - self.assertEqual(serializer.object.title, '') - - def test_create_not_blank_field(self): - """ - Test to ensure blank data in a field not marked as blank=True - is considered invalid in a non-model serializer - """ - serializer = self.not_blank_serializer_class(data=self.data) - self.assertEqual(serializer.is_valid(), False) - - def test_create_model_not_blank_field(self): - """ - Test to ensure blank data in a field not marked as blank=True - is considered invalid in a model serializer - """ - serializer = self.not_blank_model_serializer_class(data=self.data) - self.assertEqual(serializer.is_valid(), False) - - def test_create_model_empty_field(self): - serializer = self.model_serializer_class(data={}) - self.assertEqual(serializer.is_valid(), True) - - def test_create_model_null_field_save(self): - """ - Regression test for #1330. - - https://github.com/tomchristie/django-rest-framework/pull/1330 - """ - serializer = self.model_serializer_class(data={'title': None}) - self.assertEqual(serializer.is_valid(), True) - - try: - serializer.save() - except Exception: - self.fail('Exception raised on save() after validation passes') - - -# Test for issue #460 -class SerializerPickleTests(TestCase): - """ - Test pickleability of the output of Serializers - """ - def test_pickle_simple_model_serializer_data(self): - """ - Test simple serializer - """ - pickle.dumps(PersonSerializer(Person(name="Methusela", age=969)).data) - - def test_pickle_inner_serializer(self): - """ - Test pickling a serializer whose resulting .data (a SortedDictWithMetadata) will - have unpickleable meta data--in order to make sure metadata doesn't get pulled into the pickle. - See DictWithMetadata.__getstate__ - """ - class InnerPersonSerializer(serializers.ModelSerializer): - class Meta: - model = Person - fields = ('name', 'age') - pickle.dumps(InnerPersonSerializer(Person(name="Noah", age=950)).data, 0) - - def test_getstate_method_should_not_return_none(self): - """ - Regression test for #645. - """ - data = serializers.DictWithMetadata({1: 1}) - self.assertEqual(data.__getstate__(), serializers.SortedDict({1: 1})) - - def test_serializer_data_is_pickleable(self): - """ - Another regression test for #645. - """ - data = serializers.SortedDictWithMetadata({1: 1}) - repr(pickle.loads(pickle.dumps(data, 0))) - - -# test for issue #725 -class SeveralChoicesModel(models.Model): - color = models.CharField( - max_length=10, - choices=[('red', 'Red'), ('green', 'Green'), ('blue', 'Blue')], - blank=False - ) - drink = models.CharField( - max_length=10, - choices=[('beer', 'Beer'), ('wine', 'Wine'), ('cider', 'Cider')], - blank=False, - default='beer' - ) - os = models.CharField( - max_length=10, - choices=[('linux', 'Linux'), ('osx', 'OSX'), ('windows', 'Windows')], - blank=True - ) - music_genre = models.CharField( - max_length=10, - choices=[('rock', 'Rock'), ('metal', 'Metal'), ('grunge', 'Grunge')], - blank=True, - default='metal' - ) - - -class SerializerChoiceFields(TestCase): - - def setUp(self): - super(SerializerChoiceFields, self).setUp() - - class SeveralChoicesSerializer(serializers.ModelSerializer): - class Meta: - model = SeveralChoicesModel - fields = ('color', 'drink', 'os', 'music_genre') - - self.several_choices_serializer = SeveralChoicesSerializer - - def test_choices_blank_false_not_default(self): - serializer = self.several_choices_serializer() - self.assertEqual( - serializer.fields['color'].choices, - [('red', 'Red'), ('green', 'Green'), ('blue', 'Blue')] - ) - - def test_choices_blank_false_with_default(self): - serializer = self.several_choices_serializer() - self.assertEqual( - serializer.fields['drink'].choices, - [('beer', 'Beer'), ('wine', 'Wine'), ('cider', 'Cider')] - ) - - def test_choices_blank_true_not_default(self): - serializer = self.several_choices_serializer() - self.assertEqual( - serializer.fields['os'].choices, - BLANK_CHOICE_DASH + [('linux', 'Linux'), ('osx', 'OSX'), ('windows', 'Windows')] - ) - - def test_choices_blank_true_with_default(self): - serializer = self.several_choices_serializer() - self.assertEqual( - serializer.fields['music_genre'].choices, - BLANK_CHOICE_DASH + [('rock', 'Rock'), ('metal', 'Metal'), ('grunge', 'Grunge')] - ) - - -# Regression tests for #675 -class Ticket(models.Model): - assigned = models.ForeignKey( - Person, related_name='assigned_tickets') - reviewer = models.ForeignKey( - Person, blank=True, null=True, related_name='reviewed_tickets') - - -class SerializerRelatedChoicesTest(TestCase): - - def setUp(self): - super(SerializerRelatedChoicesTest, self).setUp() - - class RelatedChoicesSerializer(serializers.ModelSerializer): - class Meta: - model = Ticket - fields = ('assigned', 'reviewer') - - self.related_fields_serializer = RelatedChoicesSerializer - - def test_empty_queryset_required(self): - serializer = self.related_fields_serializer() - self.assertEqual(serializer.fields['assigned'].queryset.count(), 0) - self.assertEqual( - [x for x in serializer.fields['assigned'].widget.choices], - [] - ) - - def test_empty_queryset_not_required(self): - serializer = self.related_fields_serializer() - self.assertEqual(serializer.fields['reviewer'].queryset.count(), 0) - self.assertEqual( - [x for x in serializer.fields['reviewer'].widget.choices], - [('', '---------')] - ) - - def test_with_some_persons_required(self): - Person.objects.create(name="Lionel Messi") - Person.objects.create(name="Xavi Hernandez") - serializer = self.related_fields_serializer() - self.assertEqual(serializer.fields['assigned'].queryset.count(), 2) - self.assertEqual( - [x for x in serializer.fields['assigned'].widget.choices], - [(1, 'Person object - 1'), (2, 'Person object - 2')] - ) - - def test_with_some_persons_not_required(self): - Person.objects.create(name="Lionel Messi") - Person.objects.create(name="Xavi Hernandez") - serializer = self.related_fields_serializer() - self.assertEqual(serializer.fields['reviewer'].queryset.count(), 2) - self.assertEqual( - [x for x in serializer.fields['reviewer'].widget.choices], - [('', '---------'), (1, 'Person object - 1'), (2, 'Person object - 2')] - ) +# def test_nested_traversal_with_none(self): +# """ +# If a component of the dotted.source is None, return None for the field. +# """ +# from tests.models import NullableForeignKeySource +# instance = NullableForeignKeySource.objects.create(name='Source with null FK') + +# class NullableSourceSerializer(serializers.Serializer): +# target_name = serializers.Field(source='target.name') + +# serializer = NullableSourceSerializer(instance=instance) + +# expected = { +# 'target_name': None, +# } + +# self.assertEqual(serializer.data, expected) + + +# class SerializerMethodFieldTests(TestCase): +# def setUp(self): + +# class BoopSerializer(serializers.Serializer): +# beep = serializers.SerializerMethodField('get_beep') +# boop = serializers.Field() +# boop_count = serializers.SerializerMethodField('get_boop_count') + +# def get_beep(self, obj): +# return 'hello!' + +# def get_boop_count(self, obj): +# return len(obj.boop) + +# self.serializer_class = BoopSerializer + +# def test_serializer_method_field(self): + +# class MyModel(object): +# boop = ['a', 'b', 'c'] + +# source_data = MyModel() + +# serializer = self.serializer_class(source_data) + +# expected = { +# 'beep': 'hello!', +# 'boop': ['a', 'b', 'c'], +# 'boop_count': 3, +# } + +# self.assertEqual(serializer.data, expected) + + +# # Test for issue #324 +# class BlankFieldTests(TestCase): +# def setUp(self): + +# class BlankFieldModelSerializer(serializers.ModelSerializer): +# class Meta: +# model = BlankFieldModel + +# class BlankFieldSerializer(serializers.Serializer): +# title = serializers.CharField(required=False) + +# class NotBlankFieldModelSerializer(serializers.ModelSerializer): +# class Meta: +# model = BasicModel + +# class NotBlankFieldSerializer(serializers.Serializer): +# title = serializers.CharField() + +# self.model_serializer_class = BlankFieldModelSerializer +# self.serializer_class = BlankFieldSerializer +# self.not_blank_model_serializer_class = NotBlankFieldModelSerializer +# self.not_blank_serializer_class = NotBlankFieldSerializer +# self.data = {'title': ''} + +# def test_create_blank_field(self): +# serializer = self.serializer_class(data=self.data) +# self.assertEqual(serializer.is_valid(), True) + +# def test_create_model_blank_field(self): +# serializer = self.model_serializer_class(data=self.data) +# self.assertEqual(serializer.is_valid(), True) + +# def test_create_model_null_field(self): +# serializer = self.model_serializer_class(data={'title': None}) +# self.assertEqual(serializer.is_valid(), True) +# serializer.save() +# self.assertIsNot(serializer.object.pk, None) +# self.assertEqual(serializer.object.title, '') + +# def test_create_not_blank_field(self): +# """ +# Test to ensure blank data in a field not marked as blank=True +# is considered invalid in a non-model serializer +# """ +# serializer = self.not_blank_serializer_class(data=self.data) +# self.assertEqual(serializer.is_valid(), False) + +# def test_create_model_not_blank_field(self): +# """ +# Test to ensure blank data in a field not marked as blank=True +# is considered invalid in a model serializer +# """ +# serializer = self.not_blank_model_serializer_class(data=self.data) +# self.assertEqual(serializer.is_valid(), False) + +# def test_create_model_empty_field(self): +# serializer = self.model_serializer_class(data={}) +# self.assertEqual(serializer.is_valid(), True) + +# def test_create_model_null_field_save(self): +# """ +# Regression test for #1330. + +# https://github.com/tomchristie/django-rest-framework/pull/1330 +# """ +# serializer = self.model_serializer_class(data={'title': None}) +# self.assertEqual(serializer.is_valid(), True) + +# try: +# serializer.save() +# except Exception: +# self.fail('Exception raised on save() after validation passes') + + +# # Test for issue #460 +# class SerializerPickleTests(TestCase): +# """ +# Test pickleability of the output of Serializers +# """ +# def test_pickle_simple_model_serializer_data(self): +# """ +# Test simple serializer +# """ +# pickle.dumps(PersonSerializer(Person(name="Methusela", age=969)).data) + +# def test_pickle_inner_serializer(self): +# """ +# Test pickling a serializer whose resulting .data (a SortedDictWithMetadata) will +# have unpickleable meta data--in order to make sure metadata doesn't get pulled into the pickle. +# See DictWithMetadata.__getstate__ +# """ +# class InnerPersonSerializer(serializers.ModelSerializer): +# class Meta: +# model = Person +# fields = ('name', 'age') +# pickle.dumps(InnerPersonSerializer(Person(name="Noah", age=950)).data, 0) + +# def test_getstate_method_should_not_return_none(self): +# """ +# Regression test for #645. +# """ +# data = serializers.DictWithMetadata({1: 1}) +# self.assertEqual(data.__getstate__(), serializers.SortedDict({1: 1})) + +# def test_serializer_data_is_pickleable(self): +# """ +# Another regression test for #645. +# """ +# data = serializers.SortedDictWithMetadata({1: 1}) +# repr(pickle.loads(pickle.dumps(data, 0))) + + +# # test for issue #725 +# class SeveralChoicesModel(models.Model): +# color = models.CharField( +# max_length=10, +# choices=[('red', 'Red'), ('green', 'Green'), ('blue', 'Blue')], +# blank=False +# ) +# drink = models.CharField( +# max_length=10, +# choices=[('beer', 'Beer'), ('wine', 'Wine'), ('cider', 'Cider')], +# blank=False, +# default='beer' +# ) +# os = models.CharField( +# max_length=10, +# choices=[('linux', 'Linux'), ('osx', 'OSX'), ('windows', 'Windows')], +# blank=True +# ) +# music_genre = models.CharField( +# max_length=10, +# choices=[('rock', 'Rock'), ('metal', 'Metal'), ('grunge', 'Grunge')], +# blank=True, +# default='metal' +# ) + + +# class SerializerChoiceFields(TestCase): + +# def setUp(self): +# super(SerializerChoiceFields, self).setUp() + +# class SeveralChoicesSerializer(serializers.ModelSerializer): +# class Meta: +# model = SeveralChoicesModel +# fields = ('color', 'drink', 'os', 'music_genre') + +# self.several_choices_serializer = SeveralChoicesSerializer + +# def test_choices_blank_false_not_default(self): +# serializer = self.several_choices_serializer() +# self.assertEqual( +# serializer.fields['color'].choices, +# [('red', 'Red'), ('green', 'Green'), ('blue', 'Blue')] +# ) + +# def test_choices_blank_false_with_default(self): +# serializer = self.several_choices_serializer() +# self.assertEqual( +# serializer.fields['drink'].choices, +# [('beer', 'Beer'), ('wine', 'Wine'), ('cider', 'Cider')] +# ) + +# def test_choices_blank_true_not_default(self): +# serializer = self.several_choices_serializer() +# self.assertEqual( +# serializer.fields['os'].choices, +# BLANK_CHOICE_DASH + [('linux', 'Linux'), ('osx', 'OSX'), ('windows', 'Windows')] +# ) + +# def test_choices_blank_true_with_default(self): +# serializer = self.several_choices_serializer() +# self.assertEqual( +# serializer.fields['music_genre'].choices, +# BLANK_CHOICE_DASH + [('rock', 'Rock'), ('metal', 'Metal'), ('grunge', 'Grunge')] +# ) + + +# # Regression tests for #675 +# class Ticket(models.Model): +# assigned = models.ForeignKey( +# Person, related_name='assigned_tickets') +# reviewer = models.ForeignKey( +# Person, blank=True, null=True, related_name='reviewed_tickets') + + +# class SerializerRelatedChoicesTest(TestCase): + +# def setUp(self): +# super(SerializerRelatedChoicesTest, self).setUp() + +# class RelatedChoicesSerializer(serializers.ModelSerializer): +# class Meta: +# model = Ticket +# fields = ('assigned', 'reviewer') + +# self.related_fields_serializer = RelatedChoicesSerializer + +# def test_empty_queryset_required(self): +# serializer = self.related_fields_serializer() +# self.assertEqual(serializer.fields['assigned'].queryset.count(), 0) +# self.assertEqual( +# [x for x in serializer.fields['assigned'].widget.choices], +# [] +# ) + +# def test_empty_queryset_not_required(self): +# serializer = self.related_fields_serializer() +# self.assertEqual(serializer.fields['reviewer'].queryset.count(), 0) +# self.assertEqual( +# [x for x in serializer.fields['reviewer'].widget.choices], +# [('', '---------')] +# ) + +# def test_with_some_persons_required(self): +# Person.objects.create(name="Lionel Messi") +# Person.objects.create(name="Xavi Hernandez") +# serializer = self.related_fields_serializer() +# self.assertEqual(serializer.fields['assigned'].queryset.count(), 2) +# self.assertEqual( +# [x for x in serializer.fields['assigned'].widget.choices], +# [(1, 'Person object - 1'), (2, 'Person object - 2')] +# ) + +# def test_with_some_persons_not_required(self): +# Person.objects.create(name="Lionel Messi") +# Person.objects.create(name="Xavi Hernandez") +# serializer = self.related_fields_serializer() +# self.assertEqual(serializer.fields['reviewer'].queryset.count(), 2) +# self.assertEqual( +# [x for x in serializer.fields['reviewer'].widget.choices], +# [('', '---------'), (1, 'Person object - 1'), (2, 'Person object - 2')] +# ) -class DepthTest(TestCase): - def test_implicit_nesting(self): - - writer = Person.objects.create(name="django", age=1) - post = BlogPost.objects.create(title="Test blog post", writer=writer) - comment = BlogPostComment.objects.create(text="Test blog post comment", blog_post=post) - - class BlogPostCommentSerializer(serializers.ModelSerializer): - class Meta: - model = BlogPostComment - depth = 2 - - serializer = BlogPostCommentSerializer(instance=comment) - expected = {'id': 1, 'text': 'Test blog post comment', 'blog_post': {'id': 1, 'title': 'Test blog post', - 'writer': {'id': 1, 'name': 'django', 'age': 1}}} - - self.assertEqual(serializer.data, expected) - - def test_explicit_nesting(self): - writer = Person.objects.create(name="django", age=1) - post = BlogPost.objects.create(title="Test blog post", writer=writer) - comment = BlogPostComment.objects.create(text="Test blog post comment", blog_post=post) - - class PersonSerializer(serializers.ModelSerializer): - class Meta: - model = Person - - class BlogPostSerializer(serializers.ModelSerializer): - writer = PersonSerializer() - - class Meta: - model = BlogPost - - class BlogPostCommentSerializer(serializers.ModelSerializer): - blog_post = BlogPostSerializer() - - class Meta: - model = BlogPostComment +# class DepthTest(TestCase): +# def test_implicit_nesting(self): + +# writer = Person.objects.create(name="django", age=1) +# post = BlogPost.objects.create(title="Test blog post", writer=writer) +# comment = BlogPostComment.objects.create(text="Test blog post comment", blog_post=post) + +# class BlogPostCommentSerializer(serializers.ModelSerializer): +# class Meta: +# model = BlogPostComment +# depth = 2 + +# serializer = BlogPostCommentSerializer(instance=comment) +# expected = {'id': 1, 'text': 'Test blog post comment', 'blog_post': {'id': 1, 'title': 'Test blog post', +# 'writer': {'id': 1, 'name': 'django', 'age': 1}}} + +# self.assertEqual(serializer.data, expected) + +# def test_explicit_nesting(self): +# writer = Person.objects.create(name="django", age=1) +# post = BlogPost.objects.create(title="Test blog post", writer=writer) +# comment = BlogPostComment.objects.create(text="Test blog post comment", blog_post=post) + +# class PersonSerializer(serializers.ModelSerializer): +# class Meta: +# model = Person + +# class BlogPostSerializer(serializers.ModelSerializer): +# writer = PersonSerializer() + +# class Meta: +# model = BlogPost + +# class BlogPostCommentSerializer(serializers.ModelSerializer): +# blog_post = BlogPostSerializer() + +# class Meta: +# model = BlogPostComment - serializer = BlogPostCommentSerializer(instance=comment) - expected = {'id': 1, 'text': 'Test blog post comment', 'blog_post': {'id': 1, 'title': 'Test blog post', - 'writer': {'id': 1, 'name': 'django', 'age': 1}}} +# serializer = BlogPostCommentSerializer(instance=comment) +# expected = {'id': 1, 'text': 'Test blog post comment', 'blog_post': {'id': 1, 'title': 'Test blog post', +# 'writer': {'id': 1, 'name': 'django', 'age': 1}}} - self.assertEqual(serializer.data, expected) +# self.assertEqual(serializer.data, expected) -class NestedSerializerContextTests(TestCase): +# class NestedSerializerContextTests(TestCase): - def test_nested_serializer_context(self): - """ - Regression for #497 - - https://github.com/tomchristie/django-rest-framework/issues/497 - """ - class PhotoSerializer(serializers.ModelSerializer): - class Meta: - model = Photo - fields = ("description", "callable") +# def test_nested_serializer_context(self): +# """ +# Regression for #497 + +# https://github.com/tomchristie/django-rest-framework/issues/497 +# """ +# class PhotoSerializer(serializers.ModelSerializer): +# class Meta: +# model = Photo +# fields = ("description", "callable") - callable = serializers.SerializerMethodField('_callable') +# callable = serializers.SerializerMethodField('_callable') - def _callable(self, instance): - if 'context_item' not in self.context: - raise RuntimeError("context isn't getting passed into 2nd level nested serializer") - return "success" - - class AlbumSerializer(serializers.ModelSerializer): - class Meta: - model = Album - fields = ("photo_set", "callable") +# def _callable(self, instance): +# if 'context_item' not in self.context: +# raise RuntimeError("context isn't getting passed into 2nd level nested serializer") +# return "success" + +# class AlbumSerializer(serializers.ModelSerializer): +# class Meta: +# model = Album +# fields = ("photo_set", "callable") - photo_set = PhotoSerializer(source="photo_set", many=True) - callable = serializers.SerializerMethodField("_callable") +# photo_set = PhotoSerializer(source="photo_set", many=True) +# callable = serializers.SerializerMethodField("_callable") - def _callable(self, instance): - if 'context_item' not in self.context: - raise RuntimeError("context isn't getting passed into 1st level nested serializer") - return "success" +# def _callable(self, instance): +# if 'context_item' not in self.context: +# raise RuntimeError("context isn't getting passed into 1st level nested serializer") +# return "success" - class AlbumCollection(object): - albums = None +# class AlbumCollection(object): +# albums = None - class AlbumCollectionSerializer(serializers.Serializer): - albums = AlbumSerializer(source="albums", many=True) +# class AlbumCollectionSerializer(serializers.Serializer): +# albums = AlbumSerializer(source="albums", many=True) - album1 = Album.objects.create(title="album 1") - album2 = Album.objects.create(title="album 2") - Photo.objects.create(description="Bigfoot", album=album1) - Photo.objects.create(description="Unicorn", album=album1) - Photo.objects.create(description="Yeti", album=album2) - Photo.objects.create(description="Sasquatch", album=album2) - album_collection = AlbumCollection() - album_collection.albums = [album1, album2] +# album1 = Album.objects.create(title="album 1") +# album2 = Album.objects.create(title="album 2") +# Photo.objects.create(description="Bigfoot", album=album1) +# Photo.objects.create(description="Unicorn", album=album1) +# Photo.objects.create(description="Yeti", album=album2) +# Photo.objects.create(description="Sasquatch", album=album2) +# album_collection = AlbumCollection() +# album_collection.albums = [album1, album2] - # This will raise RuntimeError if context doesn't get passed correctly to the nested Serializers - AlbumCollectionSerializer(album_collection, context={'context_item': 'album context'}).data +# # This will raise RuntimeError if context doesn't get passed correctly to the nested Serializers +# AlbumCollectionSerializer(album_collection, context={'context_item': 'album context'}).data -class DeserializeListTestCase(TestCase): +# class DeserializeListTestCase(TestCase): - def setUp(self): - self.data = { - 'email': 'nobody@nowhere.com', - 'content': 'This is some test content', - 'created': datetime.datetime(2013, 3, 7), - } +# def setUp(self): +# self.data = { +# 'email': 'nobody@nowhere.com', +# 'content': 'This is some test content', +# 'created': datetime.datetime(2013, 3, 7), +# } - def test_no_errors(self): - data = [self.data.copy() for x in range(0, 3)] - serializer = CommentSerializer(data=data, many=True) - self.assertTrue(serializer.is_valid()) - self.assertTrue(isinstance(serializer.object, list)) - self.assertTrue( - all((isinstance(item, Comment) for item in serializer.object)) - ) +# def test_no_errors(self): +# data = [self.data.copy() for x in range(0, 3)] +# serializer = CommentSerializer(data=data, many=True) +# self.assertTrue(serializer.is_valid()) +# self.assertTrue(isinstance(serializer.object, list)) +# self.assertTrue( +# all((isinstance(item, Comment) for item in serializer.object)) +# ) - def test_errors_return_as_list(self): - invalid_item = self.data.copy() - invalid_item['email'] = '' - data = [self.data.copy(), invalid_item, self.data.copy()] +# def test_errors_return_as_list(self): +# invalid_item = self.data.copy() +# invalid_item['email'] = '' +# data = [self.data.copy(), invalid_item, self.data.copy()] - serializer = CommentSerializer(data=data, many=True) - self.assertFalse(serializer.is_valid()) - expected = [{}, {'email': ['This field is required.']}, {}] - self.assertEqual(serializer.errors, expected) +# serializer = CommentSerializer(data=data, many=True) +# self.assertFalse(serializer.is_valid()) +# expected = [{}, {'email': ['This field is required.']}, {}] +# self.assertEqual(serializer.errors, expected) -# Test for issue 747 +# # Test for issue 747 -class LazyStringModel(object): - def __init__(self, lazystring): - self.lazystring = lazystring +# class LazyStringModel(object): +# def __init__(self, lazystring): +# self.lazystring = lazystring -class LazyStringSerializer(serializers.Serializer): - lazystring = serializers.Field() - - def restore_object(self, attrs, instance=None): - if instance is not None: - instance.lazystring = attrs.get('lazystring', instance.lazystring) - return instance - return LazyStringModel(**attrs) - - -class LazyStringsTestCase(TestCase): - def setUp(self): - self.model = LazyStringModel(lazystring=_('lazystring')) - - def test_lazy_strings_are_translated(self): - serializer = LazyStringSerializer(self.model) - self.assertEqual(type(serializer.data['lazystring']), - type('lazystring')) - - -# Test for issue #467 - -class FieldLabelTest(TestCase): - def setUp(self): - self.serializer_class = BasicModelSerializer - - def test_label_from_model(self): - """ - Validates that label and help_text are correctly copied from the model class. - """ - serializer = self.serializer_class() - text_field = serializer.fields['text'] - - self.assertEqual('Text comes here', text_field.label) - self.assertEqual('Text description.', text_field.help_text) - - def test_field_ctor(self): - """ - This is check that ctor supports both label and help_text. - """ - self.assertEqual('Label', fields.Field(label='Label', help_text='Help').label) - self.assertEqual('Help', fields.CharField(label='Label', help_text='Help').help_text) - self.assertEqual('Label', relations.HyperlinkedRelatedField(view_name='fake', label='Label', help_text='Help', many=True).label) - - -# Test for issue #961 - -class ManyFieldHelpTextTest(TestCase): - def test_help_text_no_hold_down_control_msg(self): - """ - Validate that help_text doesn't contain the 'Hold down "Control" ...' - message that Django appends to choice fields. - """ - rel_field = fields.Field(help_text=ManyToManyModel._meta.get_field('rel').help_text) - self.assertEqual('Some help text.', rel_field.help_text) - - -class AttributeMappingOnAutogeneratedRelatedFields(TestCase): - - def test_primary_key_related_field(self): - serializer = ForeignKeySourceSerializer() - self.assertEqual(serializer.fields['target'].help_text, 'Target') - self.assertEqual(serializer.fields['target'].label, 'Target') - - def test_hyperlinked_related_field(self): - serializer = HyperlinkedForeignKeySourceSerializer() - self.assertEqual(serializer.fields['target'].help_text, 'Target') - self.assertEqual(serializer.fields['target'].label, 'Target') - - -@unittest.skipUnless(PIL is not None, 'PIL is not installed') -class AttributeMappingOnAutogeneratedFieldsTests(TestCase): - - def setUp(self): - - class AMOAFSerializer(serializers.ModelSerializer): - class Meta: - model = AMOAFModel - - self.serializer_class = AMOAFSerializer - self.fields_attributes = { - 'char_field': [ - ('max_length', 1024), - ], - 'comma_separated_integer_field': [ - ('max_length', 1024), - ], - 'decimal_field': [ - ('max_digits', 64), - ('decimal_places', 32), - ], - 'email_field': [ - ('max_length', 1024), - ], - 'file_field': [ - ('max_length', 1024), - ], - 'image_field': [ - ('max_length', 1024), - ], - 'slug_field': [ - ('max_length', 1024), - ], - 'url_field': [ - ('max_length', 1024), - ], - 'nullable_char_field': [ - ('max_length', 1024), - ('allow_none', True), - ], - } - - def field_test(self, field): - serializer = self.serializer_class(data={}) - self.assertEqual(serializer.is_valid(), True) - - for attribute in self.fields_attributes[field]: - self.assertEqual( - getattr(serializer.fields[field], attribute[0]), - attribute[1] - ) - - def test_char_field(self): - self.field_test('char_field') - - def test_comma_separated_integer_field(self): - self.field_test('comma_separated_integer_field') - - def test_decimal_field(self): - self.field_test('decimal_field') - - def test_email_field(self): - self.field_test('email_field') - - def test_file_field(self): - self.field_test('file_field') - - def test_image_field(self): - self.field_test('image_field') - - def test_slug_field(self): - self.field_test('slug_field') - - def test_url_field(self): - self.field_test('url_field') - - def test_nullable_char_field(self): - self.field_test('nullable_char_field') - - -@unittest.skipUnless(PIL is not None, 'PIL is not installed') -class DefaultValuesOnAutogeneratedFieldsTests(TestCase): - - def setUp(self): - - class DVOAFSerializer(serializers.ModelSerializer): - class Meta: - model = DVOAFModel - - self.serializer_class = DVOAFSerializer - self.fields_attributes = { - 'positive_integer_field': [ - ('min_value', 0), - ], - 'positive_small_integer_field': [ - ('min_value', 0), - ], - 'email_field': [ - ('max_length', 75), - ], - 'file_field': [ - ('max_length', 100), - ], - 'image_field': [ - ('max_length', 100), - ], - 'slug_field': [ - ('max_length', 50), - ], - 'url_field': [ - ('max_length', 200), - ], - } - - def field_test(self, field): - serializer = self.serializer_class(data={}) - self.assertEqual(serializer.is_valid(), True) - - for attribute in self.fields_attributes[field]: - self.assertEqual( - getattr(serializer.fields[field], attribute[0]), - attribute[1] - ) +# class LazyStringSerializer(serializers.Serializer): +# lazystring = serializers.Field() + +# def restore_object(self, attrs, instance=None): +# if instance is not None: +# instance.lazystring = attrs.get('lazystring', instance.lazystring) +# return instance +# return LazyStringModel(**attrs) + + +# class LazyStringsTestCase(TestCase): +# def setUp(self): +# self.model = LazyStringModel(lazystring=_('lazystring')) + +# def test_lazy_strings_are_translated(self): +# serializer = LazyStringSerializer(self.model) +# self.assertEqual(type(serializer.data['lazystring']), +# type('lazystring')) + + +# # Test for issue #467 + +# class FieldLabelTest(TestCase): +# def setUp(self): +# self.serializer_class = BasicModelSerializer + +# def test_label_from_model(self): +# """ +# Validates that label and help_text are correctly copied from the model class. +# """ +# serializer = self.serializer_class() +# text_field = serializer.fields['text'] + +# self.assertEqual('Text comes here', text_field.label) +# self.assertEqual('Text description.', text_field.help_text) + +# def test_field_ctor(self): +# """ +# This is check that ctor supports both label and help_text. +# """ +# self.assertEqual('Label', fields.Field(label='Label', help_text='Help').label) +# self.assertEqual('Help', fields.CharField(label='Label', help_text='Help').help_text) +# self.assertEqual('Label', relations.HyperlinkedRelatedField(view_name='fake', label='Label', help_text='Help', many=True).label) + + +# # Test for issue #961 + +# class ManyFieldHelpTextTest(TestCase): +# def test_help_text_no_hold_down_control_msg(self): +# """ +# Validate that help_text doesn't contain the 'Hold down "Control" ...' +# message that Django appends to choice fields. +# """ +# rel_field = fields.Field(help_text=ManyToManyModel._meta.get_field('rel').help_text) +# self.assertEqual('Some help text.', rel_field.help_text) + + +# class AttributeMappingOnAutogeneratedRelatedFields(TestCase): + +# def test_primary_key_related_field(self): +# serializer = ForeignKeySourceSerializer() +# self.assertEqual(serializer.fields['target'].help_text, 'Target') +# self.assertEqual(serializer.fields['target'].label, 'Target') + +# def test_hyperlinked_related_field(self): +# serializer = HyperlinkedForeignKeySourceSerializer() +# self.assertEqual(serializer.fields['target'].help_text, 'Target') +# self.assertEqual(serializer.fields['target'].label, 'Target') + + +# @unittest.skipUnless(PIL is not None, 'PIL is not installed') +# class AttributeMappingOnAutogeneratedFieldsTests(TestCase): + +# def setUp(self): + +# class AMOAFSerializer(serializers.ModelSerializer): +# class Meta: +# model = AMOAFModel + +# self.serializer_class = AMOAFSerializer +# self.fields_attributes = { +# 'char_field': [ +# ('max_length', 1024), +# ], +# 'comma_separated_integer_field': [ +# ('max_length', 1024), +# ], +# 'decimal_field': [ +# ('max_digits', 64), +# ('decimal_places', 32), +# ], +# 'email_field': [ +# ('max_length', 1024), +# ], +# 'file_field': [ +# ('max_length', 1024), +# ], +# 'image_field': [ +# ('max_length', 1024), +# ], +# 'slug_field': [ +# ('max_length', 1024), +# ], +# 'url_field': [ +# ('max_length', 1024), +# ], +# 'nullable_char_field': [ +# ('max_length', 1024), +# ('allow_none', True), +# ], +# } + +# def field_test(self, field): +# serializer = self.serializer_class(data={}) +# self.assertEqual(serializer.is_valid(), True) + +# for attribute in self.fields_attributes[field]: +# self.assertEqual( +# getattr(serializer.fields[field], attribute[0]), +# attribute[1] +# ) + +# def test_char_field(self): +# self.field_test('char_field') + +# def test_comma_separated_integer_field(self): +# self.field_test('comma_separated_integer_field') + +# def test_decimal_field(self): +# self.field_test('decimal_field') + +# def test_email_field(self): +# self.field_test('email_field') + +# def test_file_field(self): +# self.field_test('file_field') + +# def test_image_field(self): +# self.field_test('image_field') + +# def test_slug_field(self): +# self.field_test('slug_field') + +# def test_url_field(self): +# self.field_test('url_field') + +# def test_nullable_char_field(self): +# self.field_test('nullable_char_field') + + +# @unittest.skipUnless(PIL is not None, 'PIL is not installed') +# class DefaultValuesOnAutogeneratedFieldsTests(TestCase): + +# def setUp(self): + +# class DVOAFSerializer(serializers.ModelSerializer): +# class Meta: +# model = DVOAFModel + +# self.serializer_class = DVOAFSerializer +# self.fields_attributes = { +# 'positive_integer_field': [ +# ('min_value', 0), +# ], +# 'positive_small_integer_field': [ +# ('min_value', 0), +# ], +# 'email_field': [ +# ('max_length', 75), +# ], +# 'file_field': [ +# ('max_length', 100), +# ], +# 'image_field': [ +# ('max_length', 100), +# ], +# 'slug_field': [ +# ('max_length', 50), +# ], +# 'url_field': [ +# ('max_length', 200), +# ], +# } + +# def field_test(self, field): +# serializer = self.serializer_class(data={}) +# self.assertEqual(serializer.is_valid(), True) + +# for attribute in self.fields_attributes[field]: +# self.assertEqual( +# getattr(serializer.fields[field], attribute[0]), +# attribute[1] +# ) - def test_positive_integer_field(self): - self.field_test('positive_integer_field') +# def test_positive_integer_field(self): +# self.field_test('positive_integer_field') - def test_positive_small_integer_field(self): - self.field_test('positive_small_integer_field') +# def test_positive_small_integer_field(self): +# self.field_test('positive_small_integer_field') - def test_email_field(self): - self.field_test('email_field') +# def test_email_field(self): +# self.field_test('email_field') - def test_file_field(self): - self.field_test('file_field') +# def test_file_field(self): +# self.field_test('file_field') - def test_image_field(self): - self.field_test('image_field') +# def test_image_field(self): +# self.field_test('image_field') - def test_slug_field(self): - self.field_test('slug_field') +# def test_slug_field(self): +# self.field_test('slug_field') - def test_url_field(self): - self.field_test('url_field') +# def test_url_field(self): +# self.field_test('url_field') -class MetadataSerializer(serializers.Serializer): - field1 = serializers.CharField(max_length=3, required=True) - field2 = serializers.CharField(max_length=10, required=False) +# class MetadataSerializer(serializers.Serializer): +# field1 = serializers.CharField(max_length=3, required=True) +# field2 = serializers.CharField(max_length=10, required=False) -class MetadataSerializerTestCase(TestCase): - def setUp(self): - self.serializer = MetadataSerializer() +# class MetadataSerializerTestCase(TestCase): +# def setUp(self): +# self.serializer = MetadataSerializer() - def test_serializer_metadata(self): - metadata = self.serializer.metadata() - expected = { - 'field1': { - 'required': True, - 'max_length': 3, - 'type': 'string', - 'read_only': False - }, - 'field2': { - 'required': False, - 'max_length': 10, - 'type': 'string', - 'read_only': False - } - } - self.assertEqual(expected, metadata) +# def test_serializer_metadata(self): +# metadata = self.serializer.metadata() +# expected = { +# 'field1': { +# 'required': True, +# 'max_length': 3, +# 'type': 'string', +# 'read_only': False +# }, +# 'field2': { +# 'required': False, +# 'max_length': 10, +# 'type': 'string', +# 'read_only': False +# } +# } +# self.assertEqual(expected, metadata) -# Regression test for #840 +# # Regression test for #840 -class SimpleModel(models.Model): - text = models.CharField(max_length=100) +# class SimpleModel(models.Model): +# text = models.CharField(max_length=100) - -class SimpleModelSerializer(serializers.ModelSerializer): - text = serializers.CharField() - other = serializers.CharField() - - class Meta: - model = SimpleModel - - def validate_other(self, attrs, source): - del attrs['other'] - return attrs + +# class SimpleModelSerializer(serializers.ModelSerializer): +# text = serializers.CharField() +# other = serializers.CharField() + +# class Meta: +# model = SimpleModel + +# def validate_other(self, attrs, source): +# del attrs['other'] +# return attrs -class FieldValidationRemovingAttr(TestCase): - def test_removing_non_model_field_in_validation(self): - """ - Removing an attr during field valiation should ensure that it is not - passed through when restoring the object. +# class FieldValidationRemovingAttr(TestCase): +# def test_removing_non_model_field_in_validation(self): +# """ +# Removing an attr during field valiation should ensure that it is not +# passed through when restoring the object. - This allows additional non-model fields to be supported. +# This allows additional non-model fields to be supported. - Regression test for #840. - """ - serializer = SimpleModelSerializer(data={'text': 'foo', 'other': 'bar'}) - self.assertTrue(serializer.is_valid()) - serializer.save() - self.assertEqual(serializer.object.text, 'foo') +# Regression test for #840. +# """ +# serializer = SimpleModelSerializer(data={'text': 'foo', 'other': 'bar'}) +# self.assertTrue(serializer.is_valid()) +# serializer.save() +# self.assertEqual(serializer.object.text, 'foo') -# Regression test for #878 +# # Regression test for #878 -class SimpleTargetModel(models.Model): - text = models.CharField(max_length=100) +# class SimpleTargetModel(models.Model): +# text = models.CharField(max_length=100) -class SimplePKSourceModelSerializer(serializers.Serializer): - targets = serializers.PrimaryKeyRelatedField(queryset=SimpleTargetModel.objects.all(), many=True) - text = serializers.CharField() +# class SimplePKSourceModelSerializer(serializers.Serializer): +# targets = serializers.PrimaryKeyRelatedField(queryset=SimpleTargetModel.objects.all(), many=True) +# text = serializers.CharField() -class SimpleSlugSourceModelSerializer(serializers.Serializer): - targets = serializers.SlugRelatedField(queryset=SimpleTargetModel.objects.all(), many=True, slug_field='pk') - text = serializers.CharField() +# class SimpleSlugSourceModelSerializer(serializers.Serializer): +# targets = serializers.SlugRelatedField(queryset=SimpleTargetModel.objects.all(), many=True, slug_field='pk') +# text = serializers.CharField() -class SerializerSupportsManyRelationships(TestCase): - def setUp(self): - SimpleTargetModel.objects.create(text='foo') - SimpleTargetModel.objects.create(text='bar') +# class SerializerSupportsManyRelationships(TestCase): +# def setUp(self): +# SimpleTargetModel.objects.create(text='foo') +# SimpleTargetModel.objects.create(text='bar') - def test_serializer_supports_pk_many_relationships(self): - """ - Regression test for #878. +# def test_serializer_supports_pk_many_relationships(self): +# """ +# Regression test for #878. - Note that pk behavior has a different code path to usual cases, - for performance reasons. - """ - serializer = SimplePKSourceModelSerializer(data={'text': 'foo', 'targets': [1, 2]}) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.data, {'text': 'foo', 'targets': [1, 2]}) +# Note that pk behavior has a different code path to usual cases, +# for performance reasons. +# """ +# serializer = SimplePKSourceModelSerializer(data={'text': 'foo', 'targets': [1, 2]}) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.data, {'text': 'foo', 'targets': [1, 2]}) - def test_serializer_supports_slug_many_relationships(self): - """ - Regression test for #878. - """ - serializer = SimpleSlugSourceModelSerializer(data={'text': 'foo', 'targets': [1, 2]}) - self.assertTrue(serializer.is_valid()) - self.assertEqual(serializer.data, {'text': 'foo', 'targets': [1, 2]}) +# def test_serializer_supports_slug_many_relationships(self): +# """ +# Regression test for #878. +# """ +# serializer = SimpleSlugSourceModelSerializer(data={'text': 'foo', 'targets': [1, 2]}) +# self.assertTrue(serializer.is_valid()) +# self.assertEqual(serializer.data, {'text': 'foo', 'targets': [1, 2]}) -class TransformMethodsSerializer(serializers.Serializer): - a = serializers.CharField() - b_renamed = serializers.CharField(source='b') - - def transform_a(self, obj, value): - return value.lower() - - def transform_b_renamed(self, obj, value): - if value is not None: - return 'and ' + value +# class TransformMethodsSerializer(serializers.Serializer): +# a = serializers.CharField() +# b_renamed = serializers.CharField(source='b') + +# def transform_a(self, obj, value): +# return value.lower() + +# def transform_b_renamed(self, obj, value): +# if value is not None: +# return 'and ' + value -class TestSerializerTransformMethods(TestCase): - def setUp(self): - self.s = TransformMethodsSerializer() +# class TestSerializerTransformMethods(TestCase): +# def setUp(self): +# self.s = TransformMethodsSerializer() - def test_transform_methods(self): - self.assertEqual( - self.s.to_native({'a': 'GREEN EGGS', 'b': 'HAM'}), - { - 'a': 'green eggs', - 'b_renamed': 'and HAM', - } - ) +# def test_transform_methods(self): +# self.assertEqual( +# self.s.to_native({'a': 'GREEN EGGS', 'b': 'HAM'}), +# { +# 'a': 'green eggs', +# 'b_renamed': 'and HAM', +# } +# ) - def test_missing_fields(self): - self.assertEqual( - self.s.to_native({'a': 'GREEN EGGS'}), - { - 'a': 'green eggs', - 'b_renamed': None, - } - ) +# def test_missing_fields(self): +# self.assertEqual( +# self.s.to_native({'a': 'GREEN EGGS'}), +# { +# 'a': 'green eggs', +# 'b_renamed': None, +# } +# ) -class DefaultTrueBooleanModel(models.Model): - cat = models.BooleanField(default=True) - dog = models.BooleanField(default=False) +# class DefaultTrueBooleanModel(models.Model): +# cat = models.BooleanField(default=True) +# dog = models.BooleanField(default=False) -class SerializerDefaultTrueBoolean(TestCase): +# class SerializerDefaultTrueBoolean(TestCase): - def setUp(self): - super(SerializerDefaultTrueBoolean, self).setUp() - - class DefaultTrueBooleanSerializer(serializers.ModelSerializer): - class Meta: - model = DefaultTrueBooleanModel - fields = ('cat', 'dog') - - self.default_true_boolean_serializer = DefaultTrueBooleanSerializer - - def test_enabled_as_false(self): - serializer = self.default_true_boolean_serializer(data={'cat': False, - 'dog': False}) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.data['cat'], False) - self.assertEqual(serializer.data['dog'], False) +# def setUp(self): +# super(SerializerDefaultTrueBoolean, self).setUp() + +# class DefaultTrueBooleanSerializer(serializers.ModelSerializer): +# class Meta: +# model = DefaultTrueBooleanModel +# fields = ('cat', 'dog') + +# self.default_true_boolean_serializer = DefaultTrueBooleanSerializer + +# def test_enabled_as_false(self): +# serializer = self.default_true_boolean_serializer(data={'cat': False, +# 'dog': False}) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.data['cat'], False) +# self.assertEqual(serializer.data['dog'], False) - def test_enabled_as_true(self): - serializer = self.default_true_boolean_serializer(data={'cat': True, - 'dog': True}) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.data['cat'], True) - self.assertEqual(serializer.data['dog'], True) - - def test_enabled_partial(self): - serializer = self.default_true_boolean_serializer(data={'cat': False}, - partial=True) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.data['cat'], False) - self.assertEqual(serializer.data['dog'], False) - - -class BoolenFieldTypeTest(TestCase): - ''' - Ensure the various Boolean based model fields are rendered as the proper - field type - - ''' - - def setUp(self): - ''' - Setup an ActionItemSerializer for BooleanTesting - ''' - data = { - 'title': 'b' * 201, - } - self.serializer = ActionItemSerializer(data=data) - - def test_booleanfield_type(self): - ''' - Test that BooleanField is infered from models.BooleanField - ''' - bfield = self.serializer.get_fields()['done'] - self.assertEqual(type(bfield), fields.BooleanField) - - def test_nullbooleanfield_type(self): - ''' - Test that BooleanField is infered from models.NullBooleanField - - https://groups.google.com/forum/#!topic/django-rest-framework/D9mXEftpuQ8 - ''' - bfield = self.serializer.get_fields()['started'] - self.assertEqual(type(bfield), fields.BooleanField) +# def test_enabled_as_true(self): +# serializer = self.default_true_boolean_serializer(data={'cat': True, +# 'dog': True}) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.data['cat'], True) +# self.assertEqual(serializer.data['dog'], True) + +# def test_enabled_partial(self): +# serializer = self.default_true_boolean_serializer(data={'cat': False}, +# partial=True) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.data['cat'], False) +# self.assertEqual(serializer.data['dog'], False) + + +# class BoolenFieldTypeTest(TestCase): +# ''' +# Ensure the various Boolean based model fields are rendered as the proper +# field type + +# ''' + +# def setUp(self): +# ''' +# Setup an ActionItemSerializer for BooleanTesting +# ''' +# data = { +# 'title': 'b' * 201, +# } +# self.serializer = ActionItemSerializer(data=data) + +# def test_booleanfield_type(self): +# ''' +# Test that BooleanField is infered from models.BooleanField +# ''' +# bfield = self.serializer.get_fields()['done'] +# self.assertEqual(type(bfield), fields.BooleanField) + +# def test_nullbooleanfield_type(self): +# ''' +# Test that BooleanField is infered from models.NullBooleanField + +# https://groups.google.com/forum/#!topic/django-rest-framework/D9mXEftpuQ8 +# ''' +# bfield = self.serializer.get_fields()['started'] +# self.assertEqual(type(bfield), fields.BooleanField) diff --git a/tests/test_serializer_bulk_update.py b/tests/test_serializer_bulk_update.py index 67a8ed0dc..3341ce590 100644 --- a/tests/test_serializer_bulk_update.py +++ b/tests/test_serializer_bulk_update.py @@ -1,278 +1,278 @@ -""" -Tests to cover bulk create and update using serializers. -""" -from __future__ import unicode_literals -from django.test import TestCase -from rest_framework import serializers +# """ +# Tests to cover bulk create and update using serializers. +# """ +# from __future__ import unicode_literals +# from django.test import TestCase +# from rest_framework import serializers -class BulkCreateSerializerTests(TestCase): - """ - Creating multiple instances using serializers. - """ +# class BulkCreateSerializerTests(TestCase): +# """ +# Creating multiple instances using serializers. +# """ - def setUp(self): - class BookSerializer(serializers.Serializer): - id = serializers.IntegerField() - title = serializers.CharField(max_length=100) - author = serializers.CharField(max_length=100) +# def setUp(self): +# class BookSerializer(serializers.Serializer): +# id = serializers.IntegerField() +# title = serializers.CharField(max_length=100) +# author = serializers.CharField(max_length=100) - self.BookSerializer = BookSerializer +# self.BookSerializer = BookSerializer - def test_bulk_create_success(self): - """ - Correct bulk update serialization should return the input data. - """ +# def test_bulk_create_success(self): +# """ +# Correct bulk update serialization should return the input data. +# """ - data = [ - { - 'id': 0, - 'title': 'The electric kool-aid acid test', - 'author': 'Tom Wolfe' - }, { - 'id': 1, - 'title': 'If this is a man', - 'author': 'Primo Levi' - }, { - 'id': 2, - 'title': 'The wind-up bird chronicle', - 'author': 'Haruki Murakami' - } - ] +# data = [ +# { +# 'id': 0, +# 'title': 'The electric kool-aid acid test', +# 'author': 'Tom Wolfe' +# }, { +# 'id': 1, +# 'title': 'If this is a man', +# 'author': 'Primo Levi' +# }, { +# 'id': 2, +# 'title': 'The wind-up bird chronicle', +# 'author': 'Haruki Murakami' +# } +# ] - serializer = self.BookSerializer(data=data, many=True) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.object, data) +# serializer = self.BookSerializer(data=data, many=True) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.object, data) - def test_bulk_create_errors(self): - """ - Correct bulk update serialization should return the input data. - """ +# def test_bulk_create_errors(self): +# """ +# Correct bulk update serialization should return the input data. +# """ - data = [ - { - 'id': 0, - 'title': 'The electric kool-aid acid test', - 'author': 'Tom Wolfe' - }, { - 'id': 1, - 'title': 'If this is a man', - 'author': 'Primo Levi' - }, { - 'id': 'foo', - 'title': 'The wind-up bird chronicle', - 'author': 'Haruki Murakami' - } - ] - expected_errors = [ - {}, - {}, - {'id': ['Enter a whole number.']} - ] +# data = [ +# { +# 'id': 0, +# 'title': 'The electric kool-aid acid test', +# 'author': 'Tom Wolfe' +# }, { +# 'id': 1, +# 'title': 'If this is a man', +# 'author': 'Primo Levi' +# }, { +# 'id': 'foo', +# 'title': 'The wind-up bird chronicle', +# 'author': 'Haruki Murakami' +# } +# ] +# expected_errors = [ +# {}, +# {}, +# {'id': ['Enter a whole number.']} +# ] - serializer = self.BookSerializer(data=data, many=True) - self.assertEqual(serializer.is_valid(), False) - self.assertEqual(serializer.errors, expected_errors) +# serializer = self.BookSerializer(data=data, many=True) +# self.assertEqual(serializer.is_valid(), False) +# self.assertEqual(serializer.errors, expected_errors) - def test_invalid_list_datatype(self): - """ - Data containing list of incorrect data type should return errors. - """ - data = ['foo', 'bar', 'baz'] - serializer = self.BookSerializer(data=data, many=True) - self.assertEqual(serializer.is_valid(), False) +# def test_invalid_list_datatype(self): +# """ +# Data containing list of incorrect data type should return errors. +# """ +# data = ['foo', 'bar', 'baz'] +# serializer = self.BookSerializer(data=data, many=True) +# self.assertEqual(serializer.is_valid(), False) - expected_errors = [ - {'non_field_errors': ['Invalid data']}, - {'non_field_errors': ['Invalid data']}, - {'non_field_errors': ['Invalid data']} - ] +# expected_errors = [ +# {'non_field_errors': ['Invalid data']}, +# {'non_field_errors': ['Invalid data']}, +# {'non_field_errors': ['Invalid data']} +# ] - self.assertEqual(serializer.errors, expected_errors) +# self.assertEqual(serializer.errors, expected_errors) - def test_invalid_single_datatype(self): - """ - Data containing a single incorrect data type should return errors. - """ - data = 123 - serializer = self.BookSerializer(data=data, many=True) - self.assertEqual(serializer.is_valid(), False) +# def test_invalid_single_datatype(self): +# """ +# Data containing a single incorrect data type should return errors. +# """ +# data = 123 +# serializer = self.BookSerializer(data=data, many=True) +# self.assertEqual(serializer.is_valid(), False) - expected_errors = {'non_field_errors': ['Expected a list of items.']} +# expected_errors = {'non_field_errors': ['Expected a list of items.']} - self.assertEqual(serializer.errors, expected_errors) +# self.assertEqual(serializer.errors, expected_errors) - def test_invalid_single_object(self): - """ - Data containing only a single object, instead of a list of objects - should return errors. - """ - data = { - 'id': 0, - 'title': 'The electric kool-aid acid test', - 'author': 'Tom Wolfe' - } - serializer = self.BookSerializer(data=data, many=True) - self.assertEqual(serializer.is_valid(), False) +# def test_invalid_single_object(self): +# """ +# Data containing only a single object, instead of a list of objects +# should return errors. +# """ +# data = { +# 'id': 0, +# 'title': 'The electric kool-aid acid test', +# 'author': 'Tom Wolfe' +# } +# serializer = self.BookSerializer(data=data, many=True) +# self.assertEqual(serializer.is_valid(), False) - expected_errors = {'non_field_errors': ['Expected a list of items.']} +# expected_errors = {'non_field_errors': ['Expected a list of items.']} - self.assertEqual(serializer.errors, expected_errors) +# self.assertEqual(serializer.errors, expected_errors) -class BulkUpdateSerializerTests(TestCase): - """ - Updating multiple instances using serializers. - """ +# class BulkUpdateSerializerTests(TestCase): +# """ +# Updating multiple instances using serializers. +# """ - def setUp(self): - class Book(object): - """ - A data type that can be persisted to a mock storage backend - with `.save()` and `.delete()`. - """ - object_map = {} +# def setUp(self): +# class Book(object): +# """ +# A data type that can be persisted to a mock storage backend +# with `.save()` and `.delete()`. +# """ +# object_map = {} - def __init__(self, id, title, author): - self.id = id - self.title = title - self.author = author +# def __init__(self, id, title, author): +# self.id = id +# self.title = title +# self.author = author - def save(self): - Book.object_map[self.id] = self +# def save(self): +# Book.object_map[self.id] = self - def delete(self): - del Book.object_map[self.id] +# def delete(self): +# del Book.object_map[self.id] - class BookSerializer(serializers.Serializer): - id = serializers.IntegerField() - title = serializers.CharField(max_length=100) - author = serializers.CharField(max_length=100) +# class BookSerializer(serializers.Serializer): +# id = serializers.IntegerField() +# title = serializers.CharField(max_length=100) +# author = serializers.CharField(max_length=100) - def restore_object(self, attrs, instance=None): - if instance: - instance.id = attrs['id'] - instance.title = attrs['title'] - instance.author = attrs['author'] - return instance - return Book(**attrs) +# def restore_object(self, attrs, instance=None): +# if instance: +# instance.id = attrs['id'] +# instance.title = attrs['title'] +# instance.author = attrs['author'] +# return instance +# return Book(**attrs) - self.Book = Book - self.BookSerializer = BookSerializer +# self.Book = Book +# self.BookSerializer = BookSerializer - data = [ - { - 'id': 0, - 'title': 'The electric kool-aid acid test', - 'author': 'Tom Wolfe' - }, { - 'id': 1, - 'title': 'If this is a man', - 'author': 'Primo Levi' - }, { - 'id': 2, - 'title': 'The wind-up bird chronicle', - 'author': 'Haruki Murakami' - } - ] +# data = [ +# { +# 'id': 0, +# 'title': 'The electric kool-aid acid test', +# 'author': 'Tom Wolfe' +# }, { +# 'id': 1, +# 'title': 'If this is a man', +# 'author': 'Primo Levi' +# }, { +# 'id': 2, +# 'title': 'The wind-up bird chronicle', +# 'author': 'Haruki Murakami' +# } +# ] - for item in data: - book = Book(item['id'], item['title'], item['author']) - book.save() +# for item in data: +# book = Book(item['id'], item['title'], item['author']) +# book.save() - def books(self): - """ - Return all the objects in the mock storage backend. - """ - return self.Book.object_map.values() +# def books(self): +# """ +# Return all the objects in the mock storage backend. +# """ +# return self.Book.object_map.values() - def test_bulk_update_success(self): - """ - Correct bulk update serialization should return the input data. - """ - data = [ - { - 'id': 0, - 'title': 'The electric kool-aid acid test', - 'author': 'Tom Wolfe' - }, { - 'id': 2, - 'title': 'Kafka on the shore', - 'author': 'Haruki Murakami' - } - ] - serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.data, data) - serializer.save() - new_data = self.BookSerializer(self.books(), many=True).data +# def test_bulk_update_success(self): +# """ +# Correct bulk update serialization should return the input data. +# """ +# data = [ +# { +# 'id': 0, +# 'title': 'The electric kool-aid acid test', +# 'author': 'Tom Wolfe' +# }, { +# 'id': 2, +# 'title': 'Kafka on the shore', +# 'author': 'Haruki Murakami' +# } +# ] +# serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.data, data) +# serializer.save() +# new_data = self.BookSerializer(self.books(), many=True).data - self.assertEqual(data, new_data) +# self.assertEqual(data, new_data) - def test_bulk_update_and_create(self): - """ - Bulk update serialization may also include created items. - """ - data = [ - { - 'id': 0, - 'title': 'The electric kool-aid acid test', - 'author': 'Tom Wolfe' - }, { - 'id': 3, - 'title': 'Kafka on the shore', - 'author': 'Haruki Murakami' - } - ] - serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.data, data) - serializer.save() - new_data = self.BookSerializer(self.books(), many=True).data - self.assertEqual(data, new_data) +# def test_bulk_update_and_create(self): +# """ +# Bulk update serialization may also include created items. +# """ +# data = [ +# { +# 'id': 0, +# 'title': 'The electric kool-aid acid test', +# 'author': 'Tom Wolfe' +# }, { +# 'id': 3, +# 'title': 'Kafka on the shore', +# 'author': 'Haruki Murakami' +# } +# ] +# serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.data, data) +# serializer.save() +# new_data = self.BookSerializer(self.books(), many=True).data +# self.assertEqual(data, new_data) - def test_bulk_update_invalid_create(self): - """ - Bulk update serialization without allow_add_remove may not create items. - """ - data = [ - { - 'id': 0, - 'title': 'The electric kool-aid acid test', - 'author': 'Tom Wolfe' - }, { - 'id': 3, - 'title': 'Kafka on the shore', - 'author': 'Haruki Murakami' - } - ] - expected_errors = [ - {}, - {'non_field_errors': ['Cannot create a new item, only existing items may be updated.']} - ] - serializer = self.BookSerializer(self.books(), data=data, many=True) - self.assertEqual(serializer.is_valid(), False) - self.assertEqual(serializer.errors, expected_errors) +# def test_bulk_update_invalid_create(self): +# """ +# Bulk update serialization without allow_add_remove may not create items. +# """ +# data = [ +# { +# 'id': 0, +# 'title': 'The electric kool-aid acid test', +# 'author': 'Tom Wolfe' +# }, { +# 'id': 3, +# 'title': 'Kafka on the shore', +# 'author': 'Haruki Murakami' +# } +# ] +# expected_errors = [ +# {}, +# {'non_field_errors': ['Cannot create a new item, only existing items may be updated.']} +# ] +# serializer = self.BookSerializer(self.books(), data=data, many=True) +# self.assertEqual(serializer.is_valid(), False) +# self.assertEqual(serializer.errors, expected_errors) - def test_bulk_update_error(self): - """ - Incorrect bulk update serialization should return error data. - """ - data = [ - { - 'id': 0, - 'title': 'The electric kool-aid acid test', - 'author': 'Tom Wolfe' - }, { - 'id': 'foo', - 'title': 'Kafka on the shore', - 'author': 'Haruki Murakami' - } - ] - expected_errors = [ - {}, - {'id': ['Enter a whole number.']} - ] - serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True) - self.assertEqual(serializer.is_valid(), False) - self.assertEqual(serializer.errors, expected_errors) +# def test_bulk_update_error(self): +# """ +# Incorrect bulk update serialization should return error data. +# """ +# data = [ +# { +# 'id': 0, +# 'title': 'The electric kool-aid acid test', +# 'author': 'Tom Wolfe' +# }, { +# 'id': 'foo', +# 'title': 'Kafka on the shore', +# 'author': 'Haruki Murakami' +# } +# ] +# expected_errors = [ +# {}, +# {'id': ['Enter a whole number.']} +# ] +# serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True) +# self.assertEqual(serializer.is_valid(), False) +# self.assertEqual(serializer.errors, expected_errors) diff --git a/tests/test_serializer_empty.py b/tests/test_serializer_empty.py index 30cff3615..d0006ad38 100644 --- a/tests/test_serializer_empty.py +++ b/tests/test_serializer_empty.py @@ -1,15 +1,15 @@ -from django.test import TestCase -from rest_framework import serializers +# from django.test import TestCase +# from rest_framework import serializers -class EmptySerializerTestCase(TestCase): - def test_empty_serializer(self): - class FooBarSerializer(serializers.Serializer): - foo = serializers.IntegerField() - bar = serializers.SerializerMethodField('get_bar') +# class EmptySerializerTestCase(TestCase): +# def test_empty_serializer(self): +# class FooBarSerializer(serializers.Serializer): +# foo = serializers.IntegerField() +# bar = serializers.SerializerMethodField('get_bar') - def get_bar(self, obj): - return 'bar' +# def get_bar(self, obj): +# return 'bar' - serializer = FooBarSerializer() - self.assertEquals(serializer.data, {'foo': 0}) +# serializer = FooBarSerializer() +# self.assertEquals(serializer.data, {'foo': 0}) diff --git a/tests/test_serializer_import.py b/tests/test_serializer_import.py index 3b8ff4b3c..d029c3c55 100644 --- a/tests/test_serializer_import.py +++ b/tests/test_serializer_import.py @@ -1,19 +1,19 @@ -from django.test import TestCase +# from django.test import TestCase -from rest_framework import serializers -from tests.accounts.serializers import AccountSerializer +# from rest_framework import serializers +# from tests.accounts.serializers import AccountSerializer -class ImportingModelSerializerTests(TestCase): - """ - In some situations like, GH #1225, it is possible, especially in - testing, to import a serializer who's related models have not yet - been resolved by Django. `AccountSerializer` is an example of such - a serializer (imported at the top of this file). - """ - def test_import_model_serializer(self): - """ - The serializer at the top of this file should have been - imported successfully, and we should be able to instantiate it. - """ - self.assertIsInstance(AccountSerializer(), serializers.ModelSerializer) +# class ImportingModelSerializerTests(TestCase): +# """ +# In some situations like, GH #1225, it is possible, especially in +# testing, to import a serializer who's related models have not yet +# been resolved by Django. `AccountSerializer` is an example of such +# a serializer (imported at the top of this file). +# """ +# def test_import_model_serializer(self): +# """ +# The serializer at the top of this file should have been +# imported successfully, and we should be able to instantiate it. +# """ +# self.assertIsInstance(AccountSerializer(), serializers.ModelSerializer) diff --git a/tests/test_serializer_nested.py b/tests/test_serializer_nested.py index c09c24db2..b0f64ca77 100644 --- a/tests/test_serializer_nested.py +++ b/tests/test_serializer_nested.py @@ -1,349 +1,349 @@ -""" -Tests to cover nested serializers. +# """ +# Tests to cover nested serializers. -Doesn't cover model serializers. -""" -from __future__ import unicode_literals -from django.test import TestCase -from rest_framework import serializers -from . import models +# Doesn't cover model serializers. +# """ +# from __future__ import unicode_literals +# from django.test import TestCase +# from rest_framework import serializers +# from . import models -class WritableNestedSerializerBasicTests(TestCase): - """ - Tests for deserializing nested entities. - Basic tests that use serializers that simply restore to dicts. - """ +# class WritableNestedSerializerBasicTests(TestCase): +# """ +# Tests for deserializing nested entities. +# Basic tests that use serializers that simply restore to dicts. +# """ - def setUp(self): - class TrackSerializer(serializers.Serializer): - order = serializers.IntegerField() - title = serializers.CharField(max_length=100) - duration = serializers.IntegerField() +# def setUp(self): +# class TrackSerializer(serializers.Serializer): +# order = serializers.IntegerField() +# title = serializers.CharField(max_length=100) +# duration = serializers.IntegerField() - class AlbumSerializer(serializers.Serializer): - album_name = serializers.CharField(max_length=100) - artist = serializers.CharField(max_length=100) - tracks = TrackSerializer(many=True) +# class AlbumSerializer(serializers.Serializer): +# album_name = serializers.CharField(max_length=100) +# artist = serializers.CharField(max_length=100) +# tracks = TrackSerializer(many=True) - self.AlbumSerializer = AlbumSerializer +# self.AlbumSerializer = AlbumSerializer - def test_nested_validation_success(self): - """ - Correct nested serialization should return the input data. - """ +# def test_nested_validation_success(self): +# """ +# Correct nested serialization should return the input data. +# """ - data = { - 'album_name': 'Discovery', - 'artist': 'Daft Punk', - 'tracks': [ - {'order': 1, 'title': 'One More Time', 'duration': 235}, - {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, - {'order': 3, 'title': 'Digital Love', 'duration': 239} - ] - } +# data = { +# 'album_name': 'Discovery', +# 'artist': 'Daft Punk', +# 'tracks': [ +# {'order': 1, 'title': 'One More Time', 'duration': 235}, +# {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, +# {'order': 3, 'title': 'Digital Love', 'duration': 239} +# ] +# } - serializer = self.AlbumSerializer(data=data) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.object, data) +# serializer = self.AlbumSerializer(data=data) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.object, data) - def test_nested_validation_error(self): - """ - Incorrect nested serialization should return appropriate error data. - """ +# def test_nested_validation_error(self): +# """ +# Incorrect nested serialization should return appropriate error data. +# """ - data = { - 'album_name': 'Discovery', - 'artist': 'Daft Punk', - 'tracks': [ - {'order': 1, 'title': 'One More Time', 'duration': 235}, - {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, - {'order': 3, 'title': 'Digital Love', 'duration': 'foobar'} - ] - } - expected_errors = { - 'tracks': [ - {}, - {}, - {'duration': ['Enter a whole number.']} - ] - } +# data = { +# 'album_name': 'Discovery', +# 'artist': 'Daft Punk', +# 'tracks': [ +# {'order': 1, 'title': 'One More Time', 'duration': 235}, +# {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, +# {'order': 3, 'title': 'Digital Love', 'duration': 'foobar'} +# ] +# } +# expected_errors = { +# 'tracks': [ +# {}, +# {}, +# {'duration': ['Enter a whole number.']} +# ] +# } - serializer = self.AlbumSerializer(data=data) - self.assertEqual(serializer.is_valid(), False) - self.assertEqual(serializer.errors, expected_errors) +# serializer = self.AlbumSerializer(data=data) +# self.assertEqual(serializer.is_valid(), False) +# self.assertEqual(serializer.errors, expected_errors) - def test_many_nested_validation_error(self): - """ - Incorrect nested serialization should return appropriate error data - when multiple entities are being deserialized. - """ +# def test_many_nested_validation_error(self): +# """ +# Incorrect nested serialization should return appropriate error data +# when multiple entities are being deserialized. +# """ - data = [ - { - 'album_name': 'Russian Red', - 'artist': 'I Love Your Glasses', - 'tracks': [ - {'order': 1, 'title': 'Cigarettes', 'duration': 121}, - {'order': 2, 'title': 'No Past Land', 'duration': 198}, - {'order': 3, 'title': 'They Don\'t Believe', 'duration': 191} - ] - }, - { - 'album_name': 'Discovery', - 'artist': 'Daft Punk', - 'tracks': [ - {'order': 1, 'title': 'One More Time', 'duration': 235}, - {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, - {'order': 3, 'title': 'Digital Love', 'duration': 'foobar'} - ] - } - ] - expected_errors = [ - {}, - { - 'tracks': [ - {}, - {}, - {'duration': ['Enter a whole number.']} - ] - } - ] +# data = [ +# { +# 'album_name': 'Russian Red', +# 'artist': 'I Love Your Glasses', +# 'tracks': [ +# {'order': 1, 'title': 'Cigarettes', 'duration': 121}, +# {'order': 2, 'title': 'No Past Land', 'duration': 198}, +# {'order': 3, 'title': 'They Don\'t Believe', 'duration': 191} +# ] +# }, +# { +# 'album_name': 'Discovery', +# 'artist': 'Daft Punk', +# 'tracks': [ +# {'order': 1, 'title': 'One More Time', 'duration': 235}, +# {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, +# {'order': 3, 'title': 'Digital Love', 'duration': 'foobar'} +# ] +# } +# ] +# expected_errors = [ +# {}, +# { +# 'tracks': [ +# {}, +# {}, +# {'duration': ['Enter a whole number.']} +# ] +# } +# ] - serializer = self.AlbumSerializer(data=data, many=True) - self.assertEqual(serializer.is_valid(), False) - self.assertEqual(serializer.errors, expected_errors) +# serializer = self.AlbumSerializer(data=data, many=True) +# self.assertEqual(serializer.is_valid(), False) +# self.assertEqual(serializer.errors, expected_errors) -class WritableNestedSerializerObjectTests(TestCase): - """ - Tests for deserializing nested entities. - These tests use serializers that restore to concrete objects. - """ +# class WritableNestedSerializerObjectTests(TestCase): +# """ +# Tests for deserializing nested entities. +# These tests use serializers that restore to concrete objects. +# """ - def setUp(self): - # Couple of concrete objects that we're going to deserialize into - class Track(object): - def __init__(self, order, title, duration): - self.order, self.title, self.duration = order, title, duration +# def setUp(self): +# # Couple of concrete objects that we're going to deserialize into +# class Track(object): +# def __init__(self, order, title, duration): +# self.order, self.title, self.duration = order, title, duration - def __eq__(self, other): - return ( - self.order == other.order and - self.title == other.title and - self.duration == other.duration - ) +# def __eq__(self, other): +# return ( +# self.order == other.order and +# self.title == other.title and +# self.duration == other.duration +# ) - class Album(object): - def __init__(self, album_name, artist, tracks): - self.album_name, self.artist, self.tracks = album_name, artist, tracks +# class Album(object): +# def __init__(self, album_name, artist, tracks): +# self.album_name, self.artist, self.tracks = album_name, artist, tracks - def __eq__(self, other): - return ( - self.album_name == other.album_name and - self.artist == other.artist and - self.tracks == other.tracks - ) +# def __eq__(self, other): +# return ( +# self.album_name == other.album_name and +# self.artist == other.artist and +# self.tracks == other.tracks +# ) - # And their corresponding serializers - class TrackSerializer(serializers.Serializer): - order = serializers.IntegerField() - title = serializers.CharField(max_length=100) - duration = serializers.IntegerField() +# # And their corresponding serializers +# class TrackSerializer(serializers.Serializer): +# order = serializers.IntegerField() +# title = serializers.CharField(max_length=100) +# duration = serializers.IntegerField() - def restore_object(self, attrs, instance=None): - return Track(attrs['order'], attrs['title'], attrs['duration']) +# def restore_object(self, attrs, instance=None): +# return Track(attrs['order'], attrs['title'], attrs['duration']) - class AlbumSerializer(serializers.Serializer): - album_name = serializers.CharField(max_length=100) - artist = serializers.CharField(max_length=100) - tracks = TrackSerializer(many=True) +# class AlbumSerializer(serializers.Serializer): +# album_name = serializers.CharField(max_length=100) +# artist = serializers.CharField(max_length=100) +# tracks = TrackSerializer(many=True) - def restore_object(self, attrs, instance=None): - return Album(attrs['album_name'], attrs['artist'], attrs['tracks']) +# def restore_object(self, attrs, instance=None): +# return Album(attrs['album_name'], attrs['artist'], attrs['tracks']) - self.Album, self.Track = Album, Track - self.AlbumSerializer = AlbumSerializer +# self.Album, self.Track = Album, Track +# self.AlbumSerializer = AlbumSerializer - def test_nested_validation_success(self): - """ - Correct nested serialization should return a restored object - that corresponds to the input data. - """ +# def test_nested_validation_success(self): +# """ +# Correct nested serialization should return a restored object +# that corresponds to the input data. +# """ - data = { - 'album_name': 'Discovery', - 'artist': 'Daft Punk', - 'tracks': [ - {'order': 1, 'title': 'One More Time', 'duration': 235}, - {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, - {'order': 3, 'title': 'Digital Love', 'duration': 239} - ] - } - expected_object = self.Album( - album_name='Discovery', - artist='Daft Punk', - tracks=[ - self.Track(order=1, title='One More Time', duration=235), - self.Track(order=2, title='Aerodynamic', duration=184), - self.Track(order=3, title='Digital Love', duration=239), - ] - ) +# data = { +# 'album_name': 'Discovery', +# 'artist': 'Daft Punk', +# 'tracks': [ +# {'order': 1, 'title': 'One More Time', 'duration': 235}, +# {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, +# {'order': 3, 'title': 'Digital Love', 'duration': 239} +# ] +# } +# expected_object = self.Album( +# album_name='Discovery', +# artist='Daft Punk', +# tracks=[ +# self.Track(order=1, title='One More Time', duration=235), +# self.Track(order=2, title='Aerodynamic', duration=184), +# self.Track(order=3, title='Digital Love', duration=239), +# ] +# ) - serializer = self.AlbumSerializer(data=data) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.object, expected_object) +# serializer = self.AlbumSerializer(data=data) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.object, expected_object) - def test_many_nested_validation_success(self): - """ - Correct nested serialization should return multiple restored objects - that corresponds to the input data when multiple objects are - being deserialized. - """ +# def test_many_nested_validation_success(self): +# """ +# Correct nested serialization should return multiple restored objects +# that corresponds to the input data when multiple objects are +# being deserialized. +# """ - data = [ - { - 'album_name': 'Russian Red', - 'artist': 'I Love Your Glasses', - 'tracks': [ - {'order': 1, 'title': 'Cigarettes', 'duration': 121}, - {'order': 2, 'title': 'No Past Land', 'duration': 198}, - {'order': 3, 'title': 'They Don\'t Believe', 'duration': 191} - ] - }, - { - 'album_name': 'Discovery', - 'artist': 'Daft Punk', - 'tracks': [ - {'order': 1, 'title': 'One More Time', 'duration': 235}, - {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, - {'order': 3, 'title': 'Digital Love', 'duration': 239} - ] - } - ] - expected_object = [ - self.Album( - album_name='Russian Red', - artist='I Love Your Glasses', - tracks=[ - self.Track(order=1, title='Cigarettes', duration=121), - self.Track(order=2, title='No Past Land', duration=198), - self.Track(order=3, title='They Don\'t Believe', duration=191), - ] - ), - self.Album( - album_name='Discovery', - artist='Daft Punk', - tracks=[ - self.Track(order=1, title='One More Time', duration=235), - self.Track(order=2, title='Aerodynamic', duration=184), - self.Track(order=3, title='Digital Love', duration=239), - ] - ) - ] +# data = [ +# { +# 'album_name': 'Russian Red', +# 'artist': 'I Love Your Glasses', +# 'tracks': [ +# {'order': 1, 'title': 'Cigarettes', 'duration': 121}, +# {'order': 2, 'title': 'No Past Land', 'duration': 198}, +# {'order': 3, 'title': 'They Don\'t Believe', 'duration': 191} +# ] +# }, +# { +# 'album_name': 'Discovery', +# 'artist': 'Daft Punk', +# 'tracks': [ +# {'order': 1, 'title': 'One More Time', 'duration': 235}, +# {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, +# {'order': 3, 'title': 'Digital Love', 'duration': 239} +# ] +# } +# ] +# expected_object = [ +# self.Album( +# album_name='Russian Red', +# artist='I Love Your Glasses', +# tracks=[ +# self.Track(order=1, title='Cigarettes', duration=121), +# self.Track(order=2, title='No Past Land', duration=198), +# self.Track(order=3, title='They Don\'t Believe', duration=191), +# ] +# ), +# self.Album( +# album_name='Discovery', +# artist='Daft Punk', +# tracks=[ +# self.Track(order=1, title='One More Time', duration=235), +# self.Track(order=2, title='Aerodynamic', duration=184), +# self.Track(order=3, title='Digital Love', duration=239), +# ] +# ) +# ] - serializer = self.AlbumSerializer(data=data, many=True) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.object, expected_object) +# serializer = self.AlbumSerializer(data=data, many=True) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.object, expected_object) -class ForeignKeyNestedSerializerUpdateTests(TestCase): - def setUp(self): - class Artist(object): - def __init__(self, name): - self.name = name +# class ForeignKeyNestedSerializerUpdateTests(TestCase): +# def setUp(self): +# class Artist(object): +# def __init__(self, name): +# self.name = name - def __eq__(self, other): - return self.name == other.name +# def __eq__(self, other): +# return self.name == other.name - class Album(object): - def __init__(self, name, artist): - self.name, self.artist = name, artist +# class Album(object): +# def __init__(self, name, artist): +# self.name, self.artist = name, artist - def __eq__(self, other): - return self.name == other.name and self.artist == other.artist +# def __eq__(self, other): +# return self.name == other.name and self.artist == other.artist - class ArtistSerializer(serializers.Serializer): - name = serializers.CharField() +# class ArtistSerializer(serializers.Serializer): +# name = serializers.CharField() - def restore_object(self, attrs, instance=None): - if instance: - instance.name = attrs['name'] - else: - instance = Artist(attrs['name']) - return instance +# def restore_object(self, attrs, instance=None): +# if instance: +# instance.name = attrs['name'] +# else: +# instance = Artist(attrs['name']) +# return instance - class AlbumSerializer(serializers.Serializer): - name = serializers.CharField() - by = ArtistSerializer(source='artist') +# class AlbumSerializer(serializers.Serializer): +# name = serializers.CharField() +# by = ArtistSerializer(source='artist') - def restore_object(self, attrs, instance=None): - if instance: - instance.name = attrs['name'] - instance.artist = attrs['artist'] - else: - instance = Album(attrs['name'], attrs['artist']) - return instance +# def restore_object(self, attrs, instance=None): +# if instance: +# instance.name = attrs['name'] +# instance.artist = attrs['artist'] +# else: +# instance = Album(attrs['name'], attrs['artist']) +# return instance - self.Artist = Artist - self.Album = Album - self.AlbumSerializer = AlbumSerializer +# self.Artist = Artist +# self.Album = Album +# self.AlbumSerializer = AlbumSerializer - def test_create_via_foreign_key_with_source(self): - """ - Check that we can both *create* and *update* into objects across - ForeignKeys that have a `source` specified. - Regression test for #1170 - """ - data = { - 'name': 'Discovery', - 'by': {'name': 'Daft Punk'}, - } +# def test_create_via_foreign_key_with_source(self): +# """ +# Check that we can both *create* and *update* into objects across +# ForeignKeys that have a `source` specified. +# Regression test for #1170 +# """ +# data = { +# 'name': 'Discovery', +# 'by': {'name': 'Daft Punk'}, +# } - expected = self.Album(artist=self.Artist('Daft Punk'), name='Discovery') +# expected = self.Album(artist=self.Artist('Daft Punk'), name='Discovery') - # create - serializer = self.AlbumSerializer(data=data) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.object, expected) +# # create +# serializer = self.AlbumSerializer(data=data) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.object, expected) - # update - original = self.Album(artist=self.Artist('The Bats'), name='Free All the Monsters') - serializer = self.AlbumSerializer(instance=original, data=data) - self.assertEqual(serializer.is_valid(), True) - self.assertEqual(serializer.object, expected) +# # update +# original = self.Album(artist=self.Artist('The Bats'), name='Free All the Monsters') +# serializer = self.AlbumSerializer(instance=original, data=data) +# self.assertEqual(serializer.is_valid(), True) +# self.assertEqual(serializer.object, expected) -class NestedModelSerializerUpdateTests(TestCase): - def test_second_nested_level(self): - john = models.Person.objects.create(name="john") +# class NestedModelSerializerUpdateTests(TestCase): +# def test_second_nested_level(self): +# john = models.Person.objects.create(name="john") - post = john.blogpost_set.create(title="Test blog post") - post.blogpostcomment_set.create(text="I hate this blog post") - post.blogpostcomment_set.create(text="I love this blog post") +# post = john.blogpost_set.create(title="Test blog post") +# post.blogpostcomment_set.create(text="I hate this blog post") +# post.blogpostcomment_set.create(text="I love this blog post") - class BlogPostCommentSerializer(serializers.ModelSerializer): - class Meta: - model = models.BlogPostComment +# class BlogPostCommentSerializer(serializers.ModelSerializer): +# class Meta: +# model = models.BlogPostComment - class BlogPostSerializer(serializers.ModelSerializer): - comments = BlogPostCommentSerializer(many=True, source='blogpostcomment_set') +# class BlogPostSerializer(serializers.ModelSerializer): +# comments = BlogPostCommentSerializer(many=True, source='blogpostcomment_set') - class Meta: - model = models.BlogPost - fields = ('id', 'title', 'comments') +# class Meta: +# model = models.BlogPost +# fields = ('id', 'title', 'comments') - class PersonSerializer(serializers.ModelSerializer): - posts = BlogPostSerializer(many=True, source='blogpost_set') +# class PersonSerializer(serializers.ModelSerializer): +# posts = BlogPostSerializer(many=True, source='blogpost_set') - class Meta: - model = models.Person - fields = ('id', 'name', 'age', 'posts') +# class Meta: +# model = models.Person +# fields = ('id', 'name', 'age', 'posts') - serialize = PersonSerializer(instance=john) - deserialize = PersonSerializer(data=serialize.data, instance=john) - self.assertTrue(deserialize.is_valid()) +# serialize = PersonSerializer(instance=john) +# deserialize = PersonSerializer(data=serialize.data, instance=john) +# self.assertTrue(deserialize.is_valid()) - result = deserialize.object - result.save() - self.assertEqual(result.id, john.id) +# result = deserialize.object +# result.save() +# self.assertEqual(result.id, john.id) diff --git a/tests/test_serializers.py b/tests/test_serializers.py index 31c417306..0a105e8e8 100644 --- a/tests/test_serializers.py +++ b/tests/test_serializers.py @@ -1,31 +1,31 @@ -from django.test import TestCase -from django.utils import six -from rest_framework.serializers import _resolve_model -from tests.models import BasicModel +# from django.test import TestCase +# from django.utils import six +# from rest_framework.serializers import _resolve_model +# from tests.models import BasicModel -class ResolveModelTests(TestCase): - """ - `_resolve_model` should return a Django model class given the - provided argument is a Django model class itself, or a properly - formatted string representation of one. - """ - def test_resolve_django_model(self): - resolved_model = _resolve_model(BasicModel) - self.assertEqual(resolved_model, BasicModel) +# class ResolveModelTests(TestCase): +# """ +# `_resolve_model` should return a Django model class given the +# provided argument is a Django model class itself, or a properly +# formatted string representation of one. +# """ +# def test_resolve_django_model(self): +# resolved_model = _resolve_model(BasicModel) +# self.assertEqual(resolved_model, BasicModel) - def test_resolve_string_representation(self): - resolved_model = _resolve_model('tests.BasicModel') - self.assertEqual(resolved_model, BasicModel) +# def test_resolve_string_representation(self): +# resolved_model = _resolve_model('tests.BasicModel') +# self.assertEqual(resolved_model, BasicModel) - def test_resolve_unicode_representation(self): - resolved_model = _resolve_model(six.text_type('tests.BasicModel')) - self.assertEqual(resolved_model, BasicModel) +# def test_resolve_unicode_representation(self): +# resolved_model = _resolve_model(six.text_type('tests.BasicModel')) +# self.assertEqual(resolved_model, BasicModel) - def test_resolve_non_django_model(self): - with self.assertRaises(ValueError): - _resolve_model(TestCase) +# def test_resolve_non_django_model(self): +# with self.assertRaises(ValueError): +# _resolve_model(TestCase) - def test_resolve_improper_string_representation(self): - with self.assertRaises(ValueError): - _resolve_model('BasicModel') +# def test_resolve_improper_string_representation(self): +# with self.assertRaises(ValueError): +# _resolve_model('BasicModel') From d934824bff21e4a11226af61efba319be227f4f0 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 5 Sep 2014 16:29:46 +0100 Subject: [PATCH 018/249] Workin on --- rest_framework/exceptions.py | 9 +++- rest_framework/fields.py | 26 +++++++++-- rest_framework/generics.py | 30 +----------- rest_framework/mixins.py | 83 +++++++++++++++++++-------------- rest_framework/serializers.py | 64 ++++++++++++++++--------- tests/test_generics.py | 41 ++-------------- tests/test_validation.py | 5 +- tests/test_write_only_fields.py | 69 ++++++++++++++------------- 8 files changed, 159 insertions(+), 168 deletions(-) diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py index ad52d1726..852a08b1a 100644 --- a/rest_framework/exceptions.py +++ b/rest_framework/exceptions.py @@ -15,7 +15,7 @@ class APIException(Exception): Subclasses should provide `.status_code` and `.default_detail` properties. """ status_code = status.HTTP_500_INTERNAL_SERVER_ERROR - default_detail = '' + default_detail = 'A server error occured' def __init__(self, detail=None): self.detail = detail or self.default_detail @@ -29,6 +29,11 @@ class ParseError(APIException): default_detail = 'Malformed request.' +class ValidationError(APIException): + status_code = status.HTTP_400_BAD_REQUEST + default_detail = 'Invalid data in request.' + + class AuthenticationFailed(APIException): status_code = status.HTTP_401_UNAUTHORIZED default_detail = 'Incorrect authentication credentials.' @@ -54,7 +59,7 @@ class MethodNotAllowed(APIException): class NotAcceptable(APIException): status_code = status.HTTP_406_NOT_ACCEPTABLE - default_detail = "Could not satisfy the request's Accept header" + default_detail = "Could not satisfy the request Accept header" def __init__(self, detail=None, available_renderers=None): self.detail = detail or self.default_detail diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 838aa3b0c..d18551b37 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1,3 +1,4 @@ +from rest_framework.exceptions import ValidationError from rest_framework.utils import html import inspect @@ -59,10 +60,6 @@ def set_value(dictionary, keys, value): dictionary[keys[-1]] = value -class ValidationError(Exception): - pass - - class SkipField(Exception): pass @@ -204,6 +201,22 @@ class Field(object): msg = self._MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key) raise AssertionError(msg) + def __new__(cls, *args, **kwargs): + instance = super(Field, cls).__new__(cls) + instance._args = args + instance._kwargs = kwargs + return instance + + def __repr__(self): + arg_string = ', '.join([repr(val) for val in self._args]) + kwarg_string = ', '.join([ + '%s=%s' % (key, repr(val)) for key, val in self._kwargs.items() + ]) + if arg_string and kwarg_string: + arg_string += ', ' + class_name = self.__class__.__name__ + return "%s(%s%s)" % (class_name, arg_string, kwarg_string) + class BooleanField(Field): MESSAGES = { @@ -308,6 +321,11 @@ class IntegerField(Field): 'invalid_integer': 'A valid integer is required.' } + def __init__(self, **kwargs): + self.max_value = kwargs.pop('max_value') + self.min_value = kwargs.pop('min_value') + super(CharField, self).__init__(**kwargs) + def to_native(self, data): try: data = int(str(data)) diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 6705cbb2f..c2c59154a 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -27,7 +27,7 @@ def strict_positive_int(integer_string, cutoff=None): def get_object_or_404(queryset, *filter_args, **filter_kwargs): """ - Same as Django's standard shortcut, but make sure to raise 404 + Same as Django's standard shortcut, but make sure to also raise 404 if the filter_kwargs don't match the required types. """ try: @@ -249,34 +249,6 @@ class GenericAPIView(views.APIView): # # The are not called by GenericAPIView directly, # but are used by the mixin methods. - - def pre_save(self, obj): - """ - Placeholder method for calling before saving an object. - - May be used to set attributes on the object that are implicit - in either the request, or the url. - """ - pass - - def post_save(self, obj, created=False): - """ - Placeholder method for calling after saving an object. - """ - pass - - def pre_delete(self, obj): - """ - Placeholder method for calling before deleting an object. - """ - pass - - def post_delete(self, obj): - """ - Placeholder method for calling after deleting an object. - """ - pass - def metadata(self, request): """ Return a dictionary of metadata about the view. diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index 359740cee..14a6b44b1 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -19,14 +19,10 @@ class CreateModelMixin(object): """ def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.DATA) - - if serializer.is_valid(): - self.object = serializer.save() - headers = self.get_success_headers(serializer.data) - return Response(serializer.data, status=status.HTTP_201_CREATED, - headers=headers) - - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + serializer.is_valid(raise_exception=True) + serializer.save() + headers = self.get_success_headers(serializer.data) + return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def get_success_headers(self, data): try: @@ -40,15 +36,12 @@ class ListModelMixin(object): List a queryset. """ def list(self, request, *args, **kwargs): - self.object_list = self.filter_queryset(self.get_queryset()) - - # Switch between paginated or standard style responses - page = self.paginate_queryset(self.object_list) + instance = self.filter_queryset(self.get_queryset()) + page = self.paginate_queryset(instance) if page is not None: serializer = self.get_pagination_serializer(page) else: - serializer = self.get_serializer(self.object_list, many=True) - + serializer = self.get_serializer(instance, many=True) return Response(serializer.data) @@ -57,8 +50,8 @@ class RetrieveModelMixin(object): Retrieve a model instance. """ def retrieve(self, request, *args, **kwargs): - self.object = self.get_object() - serializer = self.get_serializer(self.object) + instance = self.get_object() + serializer = self.get_serializer(instance) return Response(serializer.data) @@ -68,22 +61,52 @@ class UpdateModelMixin(object): """ def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) - self.object = self.get_object_or_none() + instance = self.get_object() + serializer = self.get_serializer(instance, data=request.DATA, partial=partial) + serializer.is_valid(raise_exception=True) + serializer.save() + return Response(serializer.data) - serializer = self.get_serializer(self.object, data=request.DATA, partial=partial) + def partial_update(self, request, *args, **kwargs): + kwargs['partial'] = True + return self.update(request, *args, **kwargs) - if not serializer.is_valid(): - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - if self.object is None: +class DestroyModelMixin(object): + """ + Destroy a model instance. + """ + def destroy(self, request, *args, **kwargs): + instance = self.get_object() + instance.delete() + return Response(status=status.HTTP_204_NO_CONTENT) + + +# The AllowPUTAsCreateMixin was previously the default behaviour +# for PUT requests. This has now been removed and must be *explictly* +# included if it is the behavior that you want. +# For more info see: ... + +class AllowPUTAsCreateMixin(object): + """ + The following mixin class may be used in order to support PUT-as-create + behavior for incoming requests. + """ + def update(self, request, *args, **kwargs): + partial = kwargs.pop('partial', False) + instance = self.get_object_or_none() + serializer = self.get_serializer(instance, data=request.DATA, partial=partial) + serializer.is_valid(raise_exception=True) + + if instance is None: lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field lookup_value = self.kwargs[lookup_url_kwarg] extras = {self.lookup_field: lookup_value} - self.object = serializer.save(extras=extras) + serializer.save(extras=extras) return Response(serializer.data, status=status.HTTP_201_CREATED) - self.object = serializer.save() - return Response(serializer.data, status=status.HTTP_200_OK) + serializer.save() + return Response(serializer.data) def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True @@ -103,15 +126,3 @@ class UpdateModelMixin(object): # PATCH requests where the object does not exist should still # return a 404 response. raise - - -class DestroyModelMixin(object): - """ - Destroy a model instance. - """ - def destroy(self, request, *args, **kwargs): - obj = self.get_object() - self.pre_delete(obj) - obj.delete() - self.post_delete(obj) - return Response(status=status.HTTP_204_NO_CONTENT) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index c38d89682..49eb6ce91 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -13,7 +13,8 @@ response content is handled by parsers and renderers. from django.db import models from django.utils import six from collections import namedtuple, OrderedDict -from rest_framework.fields import empty, set_value, Field, SkipField, ValidationError +from rest_framework.exceptions import ValidationError +from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.settings import api_settings from rest_framework.utils import html import copy @@ -34,43 +35,53 @@ FieldResult = namedtuple('FieldResult', ['field', 'value', 'error']) class BaseSerializer(Field): + """ + The BaseSerializer class provides a minimal class which may be used + for writing custom serializer implementations. + """ + def __init__(self, instance=None, data=None, **kwargs): super(BaseSerializer, self).__init__(**kwargs) self.instance = instance self._initial_data = data def to_native(self, data): - raise NotImplementedError() + raise NotImplementedError('`to_native()` must be implemented.') def to_primative(self, instance): - raise NotImplementedError() + raise NotImplementedError('`to_primative()` must be implemented.') - def update(self, instance): - raise NotImplementedError() + def update(self, instance, attrs): + raise NotImplementedError('`update()` must be implemented.') - def create(self): - raise NotImplementedError() + def create(self, attrs): + raise NotImplementedError('`create()` must be implemented.') def save(self, extras=None): if extras is not None: - self._validated_data.update(extras) + self.validated_data.update(extras) if self.instance is not None: - self.update(self.instance) + self.update(self.instance, self._validated_data) else: - self.instance = self.create() + self.instance = self.create(self._validated_data) return self.instance - def is_valid(self): - try: - self._validated_data = self.to_native(self._initial_data) - except ValidationError as exc: - self._validated_data = {} - self._errors = exc.args[0] - return False - self._errors = {} - return True + def is_valid(self, raise_exception=False): + if not hasattr(self, '_validated_data'): + try: + self._validated_data = self.to_native(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) @property def data(self): @@ -184,14 +195,20 @@ class Serializer(BaseSerializer): """ Dict of native values <- Dict of primitive datatypes. """ + if not isinstance(data, dict): + raise ValidationError({'non_field_errors': ['Invalid data']}) + ret = {} errors = {} fields = [field for field in self.fields.values() if not field.read_only] for field in fields: + validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.validate(primitive_value) + if validate_method is not None: + validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = str(exc) except SkipField: @@ -202,6 +219,7 @@ class Serializer(BaseSerializer): if errors: raise ValidationError(errors) + # TODO: 'Non field errors' return self.validate(ret) def to_primative(self, instance): @@ -340,12 +358,12 @@ class ModelSerializer(Serializer): self.opts = self._options_class(self.Meta) super(ModelSerializer, self).__init__(*args, **kwargs) - def create(self): + def create(self, attrs): ModelClass = self.opts.model - return ModelClass.objects.create(**self.validated_data) + return ModelClass.objects.create(**attrs) - def update(self, obj): - for attr, value in self.validated_data.items(): + def update(self, obj, attrs): + for attr, value in attrs.items(): setattr(obj, attr, value) obj.save() diff --git a/tests/test_generics.py b/tests/test_generics.py index 55f361b24..1b00c351a 100644 --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -360,18 +360,15 @@ class TestInstanceView(TestCase): def test_put_to_deleted_instance(self): """ - PUT requests to RetrieveUpdateDestroyAPIView should create an object - if it does not currently exist. + PUT requests to RetrieveUpdateDestroyAPIView should return 404 if + an object does not currently exist. """ self.objects.get(id=1).delete() data = {'text': 'foobar'} request = factory.put('/1', data, format='json') - with self.assertNumQueries(2): + with self.assertNumQueries(1): response = self.view(request, pk=1).render() - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - self.assertEqual(response.data, {'id': 1, 'text': 'foobar'}) - updated = self.objects.get(id=1) - self.assertEqual(updated.text, 'foobar') + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_put_to_filtered_out_instance(self): """ @@ -382,35 +379,7 @@ class TestInstanceView(TestCase): filtered_out_pk = BasicModel.objects.filter(text='filtered out')[0].pk request = factory.put('/{0}'.format(filtered_out_pk), data, format='json') response = self.view(request, pk=filtered_out_pk).render() - self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) - - def test_put_as_create_on_id_based_url(self): - """ - PUT requests to RetrieveUpdateDestroyAPIView should create an object - at the requested url if it doesn't exist. - """ - data = {'text': 'foobar'} - # pk fields can not be created on demand, only the database can set the pk for a new object - request = factory.put('/5', data, format='json') - with self.assertNumQueries(2): - response = self.view(request, pk=5).render() - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - new_obj = self.objects.get(pk=5) - self.assertEqual(new_obj.text, 'foobar') - - def test_put_as_create_on_slug_based_url(self): - """ - PUT requests to RetrieveUpdateDestroyAPIView should create an object - at the requested url if possible, else return HTTP_403_FORBIDDEN error-response. - """ - data = {'text': 'foobar'} - request = factory.put('/test_slug', data, format='json') - with self.assertNumQueries(2): - response = self.slug_based_view(request, slug='test_slug').render() - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - self.assertEqual(response.data, {'slug': 'test_slug', 'text': 'foobar'}) - new_obj = SlugBasedModel.objects.get(slug='test_slug') - self.assertEqual(new_obj.text, 'foobar') + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_patch_cannot_create_an_object(self): """ diff --git a/tests/test_validation.py b/tests/test_validation.py index f62d9068b..fcfc853dc 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -48,11 +48,10 @@ class ShouldValidateModel(models.Model): class ShouldValidateModelSerializer(serializers.ModelSerializer): renamed = serializers.CharField(source='should_validate_field', required=False) - def validate_renamed(self, attrs, source): - value = attrs[source] + def validate_renamed(self, value): if len(value) < 3: raise serializers.ValidationError('Minimum 3 characters.') - return attrs + return value class Meta: model = ShouldValidateModel diff --git a/tests/test_write_only_fields.py b/tests/test_write_only_fields.py index aabb18d6a..367048ace 100644 --- a/tests/test_write_only_fields.py +++ b/tests/test_write_only_fields.py @@ -1,42 +1,41 @@ -from django.db import models -from django.test import TestCase -from rest_framework import serializers +# from django.db import models +# from django.test import TestCase +# from rest_framework import serializers -class ExampleModel(models.Model): - email = models.EmailField(max_length=100) - password = models.CharField(max_length=100) +# class ExampleModel(models.Model): +# email = models.EmailField(max_length=100) +# password = models.CharField(max_length=100) -class WriteOnlyFieldTests(TestCase): - def test_write_only_fields(self): - class ExampleSerializer(serializers.Serializer): - email = serializers.EmailField() - password = serializers.CharField(write_only=True) +# class WriteOnlyFieldTests(TestCase): +# def test_write_only_fields(self): +# class ExampleSerializer(serializers.Serializer): +# email = serializers.EmailField() +# password = serializers.CharField(write_only=True) - data = { - 'email': 'foo@example.com', - 'password': '123' - } - serializer = ExampleSerializer(data=data) - self.assertTrue(serializer.is_valid()) - self.assertEquals(serializer.object, data) - self.assertEquals(serializer.data, {'email': 'foo@example.com'}) +# data = { +# 'email': 'foo@example.com', +# 'password': '123' +# } +# serializer = ExampleSerializer(data=data) +# self.assertTrue(serializer.is_valid()) +# self.assertEquals(serializer.validated_data, data) +# self.assertEquals(serializer.data, {'email': 'foo@example.com'}) - def test_write_only_fields_meta(self): - class ExampleSerializer(serializers.ModelSerializer): - class Meta: - model = ExampleModel - fields = ('email', 'password') - write_only_fields = ('password',) +# def test_write_only_fields_meta(self): +# class ExampleSerializer(serializers.ModelSerializer): +# class Meta: +# model = ExampleModel +# fields = ('email', 'password') +# write_only_fields = ('password',) - data = { - 'email': 'foo@example.com', - 'password': '123' - } - serializer = ExampleSerializer(data=data) - self.assertTrue(serializer.is_valid()) - self.assertTrue(isinstance(serializer.object, ExampleModel)) - self.assertEquals(serializer.object.email, data['email']) - self.assertEquals(serializer.object.password, data['password']) - self.assertEquals(serializer.data, {'email': 'foo@example.com'}) +# data = { +# 'email': 'foo@example.com', +# 'password': '123' +# } +# serializer = ExampleSerializer(data=data) +# self.assertTrue(serializer.is_valid()) +# self.assertTrue(isinstance(serializer.object, ExampleModel)) +# self.assertEquals(serializer.validated_data, data) +# self.assertEquals(serializer.data, {'email': 'foo@example.com'}) From 21980b800d04a1d82a6003823abfdf4ab80ae979 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 8 Sep 2014 14:24:05 +0100 Subject: [PATCH 019/249] More test sorting --- rest_framework/exceptions.py | 5 -- rest_framework/fields.py | 85 ++++++++++++++++++++++++++++--- rest_framework/serializers.py | 25 +++++---- rest_framework/views.py | 9 +++- tests/put_as_create_workspace.txt | 33 ++++++++++++ tests/test_permissions.py | 13 ----- tests/test_response.py | 12 ++--- tests/test_serializers.py | 50 +++++++++--------- tests/test_validation.py | 13 ----- tests/test_write_only_fields.py | 60 +++++++++------------- 10 files changed, 190 insertions(+), 115 deletions(-) create mode 100644 tests/put_as_create_workspace.txt diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py index 852a08b1a..06b5e8a27 100644 --- a/rest_framework/exceptions.py +++ b/rest_framework/exceptions.py @@ -29,11 +29,6 @@ class ParseError(APIException): default_detail = 'Malformed request.' -class ValidationError(APIException): - status_code = status.HTTP_400_BAD_REQUEST - default_detail = 'Invalid data in request.' - - class AuthenticationFailed(APIException): status_code = status.HTTP_401_UNAUTHORIZED default_detail = 'Incorrect authentication credentials.' diff --git a/rest_framework/fields.py b/rest_framework/fields.py index d18551b37..250c05799 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1,4 +1,6 @@ -from rest_framework.exceptions import ValidationError +from django.core import validators +from django.core.exceptions import ValidationError +from django.utils.encoding import is_protected_type from rest_framework.utils import html import inspect @@ -33,9 +35,14 @@ def get_attribute(instance, attrs): """ Similar to Python's built in `getattr(instance, attr)`, but takes a list of nested attributes, instead of a single attribute. + + Also accepts either attribute lookup on objects or dictionary lookups. """ for attr in attrs: - instance = getattr(instance, attr) + try: + instance = getattr(instance, attr) + except AttributeError: + return instance[attr] return instance @@ -80,9 +87,11 @@ class Field(object): 'not exist in the `MESSAGES` dictionary.' ) + default_validators = [] + def __init__(self, read_only=False, write_only=False, required=None, default=empty, initial=None, source=None, - label=None, style=None, error_messages=None): + label=None, style=None, error_messages=None, validators=[]): self._creation_counter = Field._creation_counter Field._creation_counter += 1 @@ -104,6 +113,7 @@ class Field(object): self.initial = initial self.label = label self.style = {} if style is None else style + self.validators = self.default_validators + validators def bind(self, field_name, parent, root): """ @@ -176,8 +186,21 @@ class Field(object): self.fail('required') return self.get_default() + self.run_validators(data) return self.to_native(data) + def run_validators(self, value): + if value in validators.EMPTY_VALUES: + return + errors = [] + for validator in self.validators: + try: + validator(value) + except ValidationError as exc: + errors.extend(exc.messages) + if errors: + raise ValidationError(errors) + def to_native(self, data): """ Transform the *incoming* primative data into a native value. @@ -322,9 +345,13 @@ class IntegerField(Field): } def __init__(self, **kwargs): - self.max_value = kwargs.pop('max_value') - self.min_value = kwargs.pop('min_value') - super(CharField, self).__init__(**kwargs) + max_value = kwargs.pop('max_value', None) + min_value = kwargs.pop('min_value', None) + super(IntegerField, self).__init__(**kwargs) + if max_value is not None: + self.validators.append(validators.MaxValueValidator(max_value)) + if min_value is not None: + self.validators.append(validators.MinValueValidator(min_value)) def to_native(self, data): try: @@ -392,3 +419,49 @@ class MethodField(Field): attr = 'get_{field_name}'.format(field_name=self.field_name) method = getattr(self.parent, attr) return method(value) + + +class ModelField(Field): + """ + A generic field that can be used against an arbitrary model field. + """ + def __init__(self, *args, **kwargs): + try: + self.model_field = kwargs.pop('model_field') + except KeyError: + raise ValueError("ModelField requires 'model_field' kwarg") + + self.min_length = kwargs.pop('min_length', + getattr(self.model_field, 'min_length', None)) + self.max_length = kwargs.pop('max_length', + getattr(self.model_field, 'max_length', None)) + self.min_value = kwargs.pop('min_value', + getattr(self.model_field, 'min_value', None)) + self.max_value = kwargs.pop('max_value', + getattr(self.model_field, 'max_value', None)) + + super(ModelField, self).__init__(*args, **kwargs) + + if self.min_length is not None: + self.validators.append(validators.MinLengthValidator(self.min_length)) + if self.max_length is not None: + self.validators.append(validators.MaxLengthValidator(self.max_length)) + if self.min_value is not None: + self.validators.append(validators.MinValueValidator(self.min_value)) + if self.max_value is not None: + self.validators.append(validators.MaxValueValidator(self.max_value)) + + def get_attribute(self, instance): + return get_attribute(instance, self.source_attrs[:-1]) + + def to_native(self, data): + rel = getattr(self.model_field, 'rel', None) + if rel is not None: + return rel.to._meta.get_field(rel.field_name).to_python(data) + return self.model_field.to_python(data) + + def to_primative(self, obj): + value = self.model_field._get_val_from_obj(obj) + if is_protected_type(value): + return value + return self.model_field.value_to_string(obj) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 49eb6ce91..93226d322 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -10,10 +10,10 @@ python primitives. 2. The process of marshalling between python primitives and request and response content is handled by parsers and renderers. """ +from django.core.exceptions import ValidationError from django.db import models from django.utils import six from collections import namedtuple, OrderedDict -from rest_framework.exceptions import ValidationError from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.settings import api_settings from rest_framework.utils import html @@ -58,13 +58,14 @@ class BaseSerializer(Field): raise NotImplementedError('`create()` must be implemented.') def save(self, extras=None): + attrs = self.validated_data if extras is not None: - self.validated_data.update(extras) + attrs = dict(list(attrs.items()) + list(extras.items())) if self.instance is not None: - self.update(self.instance, self._validated_data) + self.update(self.instance, attrs) else: - self.instance = self.create(self._validated_data) + self.instance = self.create(attrs) return self.instance @@ -74,7 +75,7 @@ class BaseSerializer(Field): self._validated_data = self.to_native(self._initial_data) except ValidationError as exc: self._validated_data = {} - self._errors = exc.detail + self._errors = exc.message_dict else: self._errors = {} @@ -210,7 +211,7 @@ class Serializer(BaseSerializer): if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: - errors[field.field_name] = str(exc) + errors[field.field_name] = exc.messages except SkipField: pass else: @@ -219,8 +220,10 @@ class Serializer(BaseSerializer): if errors: raise ValidationError(errors) - # TODO: 'Non field errors' - return self.validate(ret) + try: + return self.validate(ret) + except ValidationError, exc: + raise ValidationError({'non_field_errors': exc.messages}) def to_primative(self, instance): """ @@ -539,6 +542,9 @@ class ModelSerializer(Serializer): if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name + if model_field.validators is not None: + kwargs['validators'] = model_field.validators + # if model_field.help_text is not None: # kwargs['help_text'] = model_field.help_text @@ -577,8 +583,7 @@ class ModelSerializer(Serializer): try: return self.field_mapping[model_field.__class__](**kwargs) except KeyError: - # TODO: Change this to `return ModelField(model_field=model_field, **kwargs)` - return CharField(**kwargs) + return ModelField(model_field=model_field, **kwargs) class HyperlinkedModelSerializerOptions(ModelSerializerOptions): diff --git a/rest_framework/views.py b/rest_framework/views.py index 23df3443f..079e9285b 100644 --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -3,7 +3,7 @@ Provides an APIView class that is the base of all views in REST framework. """ from __future__ import unicode_literals -from django.core.exceptions import PermissionDenied +from django.core.exceptions import PermissionDenied, ValidationError from django.http import Http404 from django.utils.datastructures import SortedDict from django.views.decorators.csrf import csrf_exempt @@ -51,7 +51,8 @@ def exception_handler(exc): Returns the response that should be used for any given exception. By default we handle the REST framework `APIException`, and also - Django's builtin `Http404` and `PermissionDenied` exceptions. + Django's built-in `ValidationError`, `Http404` and `PermissionDenied` + exceptions. Any unhandled exceptions may return `None`, which will cause a 500 error to be raised. @@ -68,6 +69,10 @@ def exception_handler(exc): status=exc.status_code, headers=headers) + elif isinstance(exc, ValidationError): + return Response(exc.message_dict, + status=status.HTTP_400_BAD_REQUEST) + elif isinstance(exc, Http404): return Response({'detail': 'Not found'}, status=status.HTTP_404_NOT_FOUND) diff --git a/tests/put_as_create_workspace.txt b/tests/put_as_create_workspace.txt new file mode 100644 index 000000000..6bc5218eb --- /dev/null +++ b/tests/put_as_create_workspace.txt @@ -0,0 +1,33 @@ +# From test_validation... + +class TestPreSaveValidationExclusions(TestCase): + def test_pre_save_validation_exclusions(self): + """ + Somewhat weird test case to ensure that we don't perform model + validation on read only fields. + """ + obj = ValidationModel.objects.create(blank_validated_field='') + request = factory.put('/', {}, format='json') + view = UpdateValidationModel().as_view() + response = view(request, pk=obj.pk).render() + self.assertEqual(response.status_code, status.HTTP_200_OK) + + +# From test_permissions... + +class ModelPermissionsIntegrationTests(TestCase): + def setUp(...): + ... + + def test_has_put_as_create_permissions(self): + # User only has update permissions - should be able to update an entity. + request = factory.put('/1', {'text': 'foobar'}, format='json', + HTTP_AUTHORIZATION=self.updateonly_credentials) + response = instance_view(request, pk='1') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + # But if PUTing to a new entity, permission should be denied. + request = factory.put('/2', {'text': 'foobar'}, format='json', + HTTP_AUTHORIZATION=self.updateonly_credentials) + response = instance_view(request, pk='2') + self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) diff --git a/tests/test_permissions.py b/tests/test_permissions.py index d5568c551..ac398f80d 100644 --- a/tests/test_permissions.py +++ b/tests/test_permissions.py @@ -95,19 +95,6 @@ class ModelPermissionsIntegrationTests(TestCase): response = instance_view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) - def test_has_put_as_create_permissions(self): - # User only has update permissions - should be able to update an entity. - request = factory.put('/1', {'text': 'foobar'}, format='json', - HTTP_AUTHORIZATION=self.updateonly_credentials) - response = instance_view(request, pk='1') - self.assertEqual(response.status_code, status.HTTP_200_OK) - - # But if PUTing to a new entity, permission should be denied. - request = factory.put('/2', {'text': 'foobar'}, format='json', - HTTP_AUTHORIZATION=self.updateonly_credentials) - response = instance_view(request, pk='2') - self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) - # def test_options_permitted(self): # request = factory.options( # '/', diff --git a/tests/test_response.py b/tests/test_response.py index 004c565c9..67419a718 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -225,8 +225,8 @@ class Issue467Tests(TestCase): def test_form_has_label_and_help_text(self): resp = self.client.get('/html_new_model') self.assertEqual(resp['Content-Type'], 'text/html; charset=utf-8') - self.assertContains(resp, 'Text comes here') - self.assertContains(resp, 'Text description.') + # self.assertContains(resp, 'Text comes here') + # self.assertContains(resp, 'Text description.') class Issue807Tests(TestCase): @@ -270,11 +270,11 @@ class Issue807Tests(TestCase): ) resp = self.client.get('/html_new_model_viewset/' + param) self.assertEqual(resp['Content-Type'], 'text/html; charset=utf-8') - self.assertContains(resp, 'Text comes here') - self.assertContains(resp, 'Text description.') + # self.assertContains(resp, 'Text comes here') + # self.assertContains(resp, 'Text description.') def test_form_has_label_and_help_text(self): resp = self.client.get('/html_new_model') self.assertEqual(resp['Content-Type'], 'text/html; charset=utf-8') - self.assertContains(resp, 'Text comes here') - self.assertContains(resp, 'Text description.') + # self.assertContains(resp, 'Text comes here') + # self.assertContains(resp, 'Text description.') diff --git a/tests/test_serializers.py b/tests/test_serializers.py index 0a105e8e8..31c417306 100644 --- a/tests/test_serializers.py +++ b/tests/test_serializers.py @@ -1,31 +1,31 @@ -# from django.test import TestCase -# from django.utils import six -# from rest_framework.serializers import _resolve_model -# from tests.models import BasicModel +from django.test import TestCase +from django.utils import six +from rest_framework.serializers import _resolve_model +from tests.models import BasicModel -# class ResolveModelTests(TestCase): -# """ -# `_resolve_model` should return a Django model class given the -# provided argument is a Django model class itself, or a properly -# formatted string representation of one. -# """ -# def test_resolve_django_model(self): -# resolved_model = _resolve_model(BasicModel) -# self.assertEqual(resolved_model, BasicModel) +class ResolveModelTests(TestCase): + """ + `_resolve_model` should return a Django model class given the + provided argument is a Django model class itself, or a properly + formatted string representation of one. + """ + def test_resolve_django_model(self): + resolved_model = _resolve_model(BasicModel) + self.assertEqual(resolved_model, BasicModel) -# def test_resolve_string_representation(self): -# resolved_model = _resolve_model('tests.BasicModel') -# self.assertEqual(resolved_model, BasicModel) + def test_resolve_string_representation(self): + resolved_model = _resolve_model('tests.BasicModel') + self.assertEqual(resolved_model, BasicModel) -# def test_resolve_unicode_representation(self): -# resolved_model = _resolve_model(six.text_type('tests.BasicModel')) -# self.assertEqual(resolved_model, BasicModel) + def test_resolve_unicode_representation(self): + resolved_model = _resolve_model(six.text_type('tests.BasicModel')) + self.assertEqual(resolved_model, BasicModel) -# def test_resolve_non_django_model(self): -# with self.assertRaises(ValueError): -# _resolve_model(TestCase) + def test_resolve_non_django_model(self): + with self.assertRaises(ValueError): + _resolve_model(TestCase) -# def test_resolve_improper_string_representation(self): -# with self.assertRaises(ValueError): -# _resolve_model('BasicModel') + def test_resolve_improper_string_representation(self): + with self.assertRaises(ValueError): + _resolve_model('BasicModel') diff --git a/tests/test_validation.py b/tests/test_validation.py index fcfc853dc..40005486d 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -26,19 +26,6 @@ class UpdateValidationModel(generics.RetrieveUpdateDestroyAPIView): serializer_class = ValidationModelSerializer -class TestPreSaveValidationExclusions(TestCase): - def test_pre_save_validation_exclusions(self): - """ - Somewhat weird test case to ensure that we don't perform model - validation on read only fields. - """ - obj = ValidationModel.objects.create(blank_validated_field='') - request = factory.put('/', {}, format='json') - view = UpdateValidationModel().as_view() - response = view(request, pk=obj.pk).render() - self.assertEqual(response.status_code, status.HTTP_200_OK) - - # Regression for #653 class ShouldValidateModel(models.Model): diff --git a/tests/test_write_only_fields.py b/tests/test_write_only_fields.py index 367048ace..dd3bbd6e1 100644 --- a/tests/test_write_only_fields.py +++ b/tests/test_write_only_fields.py @@ -1,41 +1,31 @@ -# from django.db import models -# from django.test import TestCase -# from rest_framework import serializers +from django.test import TestCase +from rest_framework import serializers -# class ExampleModel(models.Model): -# email = models.EmailField(max_length=100) -# password = models.CharField(max_length=100) +class WriteOnlyFieldTests(TestCase): + def setUp(self): + class ExampleSerializer(serializers.Serializer): + email = serializers.EmailField() + password = serializers.CharField(write_only=True) + def create(self, attrs): + return attrs -# class WriteOnlyFieldTests(TestCase): -# def test_write_only_fields(self): -# class ExampleSerializer(serializers.Serializer): -# email = serializers.EmailField() -# password = serializers.CharField(write_only=True) + self.Serializer = ExampleSerializer -# data = { -# 'email': 'foo@example.com', -# 'password': '123' -# } -# serializer = ExampleSerializer(data=data) -# self.assertTrue(serializer.is_valid()) -# self.assertEquals(serializer.validated_data, data) -# self.assertEquals(serializer.data, {'email': 'foo@example.com'}) + def write_only_fields_are_present_on_input(self): + data = { + 'email': 'foo@example.com', + 'password': '123' + } + serializer = self.Serializer(data=data) + self.assertTrue(serializer.is_valid()) + self.assertEquals(serializer.validated_data, data) -# def test_write_only_fields_meta(self): -# class ExampleSerializer(serializers.ModelSerializer): -# class Meta: -# model = ExampleModel -# fields = ('email', 'password') -# write_only_fields = ('password',) - -# data = { -# 'email': 'foo@example.com', -# 'password': '123' -# } -# serializer = ExampleSerializer(data=data) -# self.assertTrue(serializer.is_valid()) -# self.assertTrue(isinstance(serializer.object, ExampleModel)) -# self.assertEquals(serializer.validated_data, data) -# self.assertEquals(serializer.data, {'email': 'foo@example.com'}) + def write_only_fields_are_not_present_on_output(self): + instance = { + 'email': 'foo@example.com', + 'password': '123' + } + serializer = self.Serializer(instance) + self.assertEquals(serializer.data, {'email': 'foo@example.com'}) From b1c07670ca65084c5fef2bbb63d1f4163763014b Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Tue, 9 Sep 2014 17:46:28 +0100 Subject: [PATCH 020/249] Fleshing out serializer fields --- rest_framework/fields.py | 607 ++++++++++++++---- rest_framework/serializers.py | 390 +++++------ rest_framework/utils/humanize_datetime.py | 47 ++ rest_framework/utils/modelinfo.py | 97 +++ rest_framework/utils/representation.py | 72 +++ tests/test_model_field_mappings.py | 160 +++++ ...{test_serializers.py => test_modelinfo.py} | 2 +- tests/test_relations.py | 12 +- tests/test_serializer_empty.py | 2 +- 9 files changed, 1053 insertions(+), 336 deletions(-) create mode 100644 rest_framework/utils/humanize_datetime.py create mode 100644 rest_framework/utils/modelinfo.py create mode 100644 rest_framework/utils/representation.py create mode 100644 tests/test_model_field_mappings.py rename tests/{test_serializers.py => test_modelinfo.py} (94%) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 250c05799..043a44edd 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1,8 +1,18 @@ +from django.conf import settings from django.core import validators from django.core.exceptions import ValidationError +from django.utils import timezone +from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.encoding import is_protected_type -from rest_framework.utils import html +from django.utils.translation import ugettext_lazy as _ +from rest_framework import ISO_8601 +from rest_framework.compat import smart_text +from rest_framework.settings import api_settings +from rest_framework.utils import html, representation, humanize_datetime +import datetime +import decimal import inspect +import warnings class empty: @@ -71,22 +81,22 @@ class SkipField(Exception): pass +NOT_READ_ONLY_WRITE_ONLY = 'May not set both `read_only` and `write_only`' +NOT_READ_ONLY_REQUIRED = 'May not set both `read_only` and `required`' +NOT_READ_ONLY_DEFAULT = 'May not set both `read_only` and `default`' +NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`' +MISSING_ERROR_MESSAGE = ( + 'ValidationError raised by `{class_name}`, but error key `{key}` does ' + 'not exist in the `error_messages` dictionary.' +) + + class Field(object): _creation_counter = 0 - MESSAGES = { - 'required': 'This field is required.' + default_error_messages = { + 'required': _('This field is required.') } - - _NOT_READ_ONLY_WRITE_ONLY = 'May not set both `read_only` and `write_only`' - _NOT_READ_ONLY_REQUIRED = 'May not set both `read_only` and `required`' - _NOT_READ_ONLY_DEFAULT = 'May not set both `read_only` and `default`' - _NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`' - _MISSING_ERROR_MESSAGE = ( - 'ValidationError raised by `{class_name}`, but error key `{key}` does ' - 'not exist in the `MESSAGES` dictionary.' - ) - default_validators = [] def __init__(self, read_only=False, write_only=False, @@ -100,10 +110,10 @@ class Field(object): required = default is empty and not read_only # Some combinations of keyword arguments do not make sense. - assert not (read_only and write_only), self._NOT_READ_ONLY_WRITE_ONLY - assert not (read_only and required), self._NOT_READ_ONLY_REQUIRED - assert not (read_only and default is not empty), self._NOT_READ_ONLY_DEFAULT - assert not (required and default is not empty), self._NOT_REQUIRED_DEFAULT + assert not (read_only and write_only), NOT_READ_ONLY_WRITE_ONLY + assert not (read_only and required), NOT_READ_ONLY_REQUIRED + assert not (read_only and default is not empty), NOT_READ_ONLY_DEFAULT + assert not (required and default is not empty), NOT_REQUIRED_DEFAULT self.read_only = read_only self.write_only = write_only @@ -113,7 +123,14 @@ class Field(object): self.initial = initial self.label = label self.style = {} if style is None else style - self.validators = self.default_validators + validators + self.validators = validators or self.default_validators[:] + + # Collect default error message from self and parent classes + messages = {} + for cls in reversed(self.__class__.__mro__): + messages.update(getattr(cls, 'default_error_messages', {})) + messages.update(error_messages or {}) + self.error_messages = messages def bind(self, field_name, parent, root): """ @@ -186,12 +203,14 @@ class Field(object): self.fail('required') return self.get_default() - self.run_validators(data) - return self.to_native(data) + value = self.to_native(data) + self.run_validators(value) + return value def run_validators(self, value): if value in validators.EMPTY_VALUES: return + errors = [] for validator in self.validators: try: @@ -218,33 +237,32 @@ class Field(object): A helper method that simply raises a validation error. """ try: - raise ValidationError(self.MESSAGES[key].format(**kwargs)) + msg = self.error_messages[key] except KeyError: class_name = self.__class__.__name__ - msg = self._MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key) + msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key) raise AssertionError(msg) + raise ValidationError(msg.format(**kwargs)) def __new__(cls, *args, **kwargs): + """ + When a field is instantiated, we store the arguments that were used, + so that we can present a helpful representation of the object. + """ instance = super(Field, cls).__new__(cls) instance._args = args instance._kwargs = kwargs return instance def __repr__(self): - arg_string = ', '.join([repr(val) for val in self._args]) - kwarg_string = ', '.join([ - '%s=%s' % (key, repr(val)) for key, val in self._kwargs.items() - ]) - if arg_string and kwarg_string: - arg_string += ', ' - class_name = self.__class__.__name__ - return "%s(%s%s)" % (class_name, arg_string, kwarg_string) + return representation.field_repr(self) +# Boolean types... + class BooleanField(Field): - MESSAGES = { - 'required': 'This field is required.', - 'invalid_value': '`{input}` is not a valid boolean.' + default_error_messages = { + 'invalid': _('`{input}` is not a valid boolean.') } TRUE_VALUES = {'t', 'T', 'true', 'True', 'TRUE', '1', 1, True} FALSE_VALUES = {'f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False} @@ -261,13 +279,23 @@ class BooleanField(Field): return True elif data in self.FALSE_VALUES: return False - self.fail('invalid_value', input=data) + self.fail('invalid', input=data) + def to_primative(self, value): + if value is None: + return None + if value in self.TRUE_VALUES: + return True + elif value in self.FALSE_VALUES: + return False + return bool(value) + + +# String types... class CharField(Field): - MESSAGES = { - 'required': 'This field is required.', - 'blank': 'This field may not be blank.' + default_error_messages = { + 'blank': _('This field may not be blank.') } def __init__(self, **kwargs): @@ -281,19 +309,364 @@ class CharField(Field): self.fail('blank') return str(data) + def to_primative(self, value): + if value is None: + return None + return str(value) -class ChoiceField(Field): - MESSAGES = { - 'required': 'This field is required.', - 'invalid_choice': '`{input}` is not a valid choice.' + +class EmailField(CharField): + default_error_messages = { + 'invalid': _('Enter a valid email address.') + } + default_validators = [validators.validate_email] + + def to_native(self, data): + ret = super(EmailField, self).to_native(data) + if ret is None: + return None + return ret.strip() + + def to_primative(self, value): + ret = super(EmailField, self).to_primative(value) + if ret is None: + return None + return ret.strip() + + +class RegexField(CharField): + def __init__(self, regex, **kwargs): + kwargs['validators'] = ( + [validators.RegexValidator(regex)] + + kwargs.get('validators', []) + ) + super(RegexField, self).__init__(**kwargs) + + +class SlugField(CharField): + default_error_messages = { + 'invalid': _("Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.") + } + default_validators = [validators.validate_slug] + + +class URLField(CharField): + default_error_messages = { + 'invalid': _("Enter a valid URL.") + } + default_validators = [validators.URLValidator()] + + +# Number types... + +class IntegerField(Field): + default_error_messages = { + 'invalid': _('A valid integer is required.') } - coerce_to_type = str def __init__(self, **kwargs): - choices = kwargs.pop('choices') + max_value = kwargs.pop('max_value', None) + min_value = kwargs.pop('min_value', None) + super(IntegerField, self).__init__(**kwargs) + if max_value is not None: + self.validators.append(validators.MaxValueValidator(max_value)) + if min_value is not None: + self.validators.append(validators.MinValueValidator(min_value)) + print self.__class__.__name__, self.validators - assert choices, '`choices` argument is required and may not be empty' + def to_native(self, data): + try: + data = int(str(data)) + except (ValueError, TypeError): + self.fail('invalid') + return data + def to_primative(self, value): + if value is None: + return None + return int(value) + + +class FloatField(Field): + default_error_messages = { + 'invalid': _("'%s' value must be a float."), + } + + def __init__(self, **kwargs): + max_value = kwargs.pop('max_value', None) + min_value = kwargs.pop('min_value', None) + super(FloatField, self).__init__(**kwargs) + if max_value is not None: + self.validators.append(validators.MaxValueValidator(max_value)) + if min_value is not None: + self.validators.append(validators.MinValueValidator(min_value)) + + def to_primative(self, value): + if value is None: + return None + try: + return float(value) + except (TypeError, ValueError): + self.fail('invalid', value=value) + + def to_native(self, value): + if value is None: + return None + return float(value) + + +class DecimalField(Field): + default_error_messages = { + 'invalid': _('Enter a number.'), + 'max_value': _('Ensure this value is less than or equal to {max_value}.'), + 'min_value': _('Ensure this value is greater than or equal to {min_value}.'), + 'max_digits': _('Ensure that there are no more than {max_digits} digits in total.'), + 'max_decimal_places': _('Ensure that there are no more than {max_decimal_places} decimal places.'), + 'max_whole_digits': _('Ensure that there are no more than {max_whole_digits} digits before the decimal point.') + } + + def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, **kwargs): + self.max_value, self.min_value = max_value, min_value + self.max_digits, self.max_decimal_places = max_digits, decimal_places + super(DecimalField, self).__init__(**kwargs) + if max_value is not None: + self.validators.append(validators.MaxValueValidator(max_value)) + if min_value is not None: + self.validators.append(validators.MinValueValidator(min_value)) + + def from_native(self, value): + """ + Validates that the input is a decimal number. Returns a Decimal + instance. Returns None for empty values. Ensures that there are no more + than max_digits in the number, and no more than decimal_places digits + after the decimal point. + """ + if value in validators.EMPTY_VALUES: + return None + + value = smart_text(value).strip() + try: + value = decimal.Decimal(value) + except decimal.DecimalException: + self.fail('invalid') + + # Check for NaN. It is the only value that isn't equal to itself, + # so we can use this to identify NaN values. + if value != value: + self.fail('invalid') + + # Check for infinity and negative infinity. + if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')): + self.fail('invalid') + + sign, digittuple, exponent = value.as_tuple() + decimals = abs(exponent) + # digittuple doesn't include any leading zeros. + digits = len(digittuple) + if decimals > digits: + # We have leading zeros up to or past the decimal point. Count + # everything past the decimal point as a digit. We do not count + # 0 before the decimal point as a digit since that would mean + # we would not allow max_digits = decimal_places. + digits = decimals + whole_digits = digits - decimals + + if self.max_digits is not None and digits > self.max_digits: + self.fail('max_digits', max_digits=self.max_digits) + if self.decimal_places is not None and decimals > self.decimal_places: + self.fail('max_decimal_places', max_decimal_places=self.max_decimal_places) + if self.max_digits is not None and self.decimal_places is not None and whole_digits > (self.max_digits - self.decimal_places): + self.fail('max_whole_digits', max_while_digits=self.max_digits - self.decimal_places) + + return value + + +# Date & time fields... + +class DateField(Field): + default_error_messages = { + 'invalid': _("Date has wrong format. Use one of these formats instead: %s"), + } + input_formats = api_settings.DATE_INPUT_FORMATS + format = api_settings.DATE_FORMAT + + def __init__(self, input_formats=None, format=None, *args, **kwargs): + self.input_formats = input_formats if input_formats is not None else self.input_formats + self.format = format if format is not None else self.format + super(DateField, self).__init__(*args, **kwargs) + + def from_native(self, value): + if value in validators.EMPTY_VALUES: + return None + + if isinstance(value, datetime.datetime): + if timezone and settings.USE_TZ and timezone.is_aware(value): + # Convert aware datetimes to the default time zone + # before casting them to dates (#17742). + default_timezone = timezone.get_default_timezone() + value = timezone.make_naive(value, default_timezone) + return value.date() + if isinstance(value, datetime.date): + return value + + for format in self.input_formats: + if format.lower() == ISO_8601: + try: + parsed = parse_date(value) + except (ValueError, TypeError): + pass + else: + if parsed is not None: + return parsed + else: + try: + parsed = datetime.datetime.strptime(value, format) + except (ValueError, TypeError): + pass + else: + return parsed.date() + + humanized_format = humanize_datetime.date_formats(self.input_formats) + msg = self.error_messages['invalid'] % humanized_format + raise ValidationError(msg) + + def to_primative(self, value): + if value is None or self.format is None: + return value + + if isinstance(value, datetime.datetime): + value = value.date() + + if self.format.lower() == ISO_8601: + return value.isoformat() + return value.strftime(self.format) + + +class DateTimeField(Field): + default_error_messages = { + 'invalid': _("Datetime has wrong format. Use one of these formats instead: %s"), + } + input_formats = api_settings.DATETIME_INPUT_FORMATS + format = api_settings.DATETIME_FORMAT + + def __init__(self, input_formats=None, format=None, *args, **kwargs): + self.input_formats = input_formats if input_formats is not None else self.input_formats + self.format = format if format is not None else self.format + super(DateTimeField, self).__init__(*args, **kwargs) + + def from_native(self, value): + if value in validators.EMPTY_VALUES: + return None + + if isinstance(value, datetime.datetime): + return value + if isinstance(value, datetime.date): + value = datetime.datetime(value.year, value.month, value.day) + if settings.USE_TZ: + # For backwards compatibility, interpret naive datetimes in + # local time. This won't work during DST change, but we can't + # do much about it, so we let the exceptions percolate up the + # call stack. + warnings.warn("DateTimeField received a naive datetime (%s)" + " while time zone support is active." % value, + RuntimeWarning) + default_timezone = timezone.get_default_timezone() + value = timezone.make_aware(value, default_timezone) + return value + + for format in self.input_formats: + if format.lower() == ISO_8601: + try: + parsed = parse_datetime(value) + except (ValueError, TypeError): + pass + else: + if parsed is not None: + return parsed + else: + try: + parsed = datetime.datetime.strptime(value, format) + except (ValueError, TypeError): + pass + else: + return parsed + + humanized_format = humanize_datetime.datetime_formats(self.input_formats) + msg = self.error_messages['invalid'] % humanized_format + raise ValidationError(msg) + + def to_primative(self, value): + if value is None or self.format is None: + return value + + if self.format.lower() == ISO_8601: + ret = value.isoformat() + if ret.endswith('+00:00'): + ret = ret[:-6] + 'Z' + return ret + return value.strftime(self.format) + + +class TimeField(Field): + default_error_messages = { + 'invalid': _("Time has wrong format. Use one of these formats instead: %s"), + } + input_formats = api_settings.TIME_INPUT_FORMATS + format = api_settings.TIME_FORMAT + + def __init__(self, input_formats=None, format=None, *args, **kwargs): + self.input_formats = input_formats if input_formats is not None else self.input_formats + self.format = format if format is not None else self.format + super(TimeField, self).__init__(*args, **kwargs) + + def from_native(self, value): + if value in validators.EMPTY_VALUES: + return None + + if isinstance(value, datetime.time): + return value + + for format in self.input_formats: + if format.lower() == ISO_8601: + try: + parsed = parse_time(value) + except (ValueError, TypeError): + pass + else: + if parsed is not None: + return parsed + else: + try: + parsed = datetime.datetime.strptime(value, format) + except (ValueError, TypeError): + pass + else: + return parsed.time() + + humanized_format = humanize_datetime.time_formats(self.input_formats) + msg = self.error_messages['invalid'] % humanized_format + raise ValidationError(msg) + + def to_primative(self, value): + if value is None or self.format is None: + return value + + if isinstance(value, datetime.datetime): + value = value.time() + + if self.format.lower() == ISO_8601: + return value.isoformat() + return value.strftime(self.format) + + +# Choice types... + +class ChoiceField(Field): + default_error_messages = { + 'invalid_choice': _('`{input}` is not a valid choice.') + } + + def __init__(self, choices, **kwargs): # Allow either single or paired choices style: # choices = [1, 2, 3] # choices = [(1, 'First'), (2, 'Second'), (3, 'Third')] @@ -321,12 +694,14 @@ class ChoiceField(Field): except KeyError: self.fail('invalid_choice', input=data) + def to_primative(self, value): + return value + class MultipleChoiceField(ChoiceField): - MESSAGES = { - 'required': 'This field is required.', - 'invalid_choice': '`{input}` is not a valid choice.', - 'not_a_list': 'Expected a list of items but got type `{input_type}`' + default_error_messages = { + 'invalid_choice': _('`{input}` is not a valid choice.'), + 'not_a_list': _('Expected a list of items but got type `{input_type}`') } def to_native(self, data): @@ -337,72 +712,42 @@ class MultipleChoiceField(ChoiceField): for item in data ]) - -class IntegerField(Field): - MESSAGES = { - 'required': 'This field is required.', - 'invalid_integer': 'A valid integer is required.' - } - - def __init__(self, **kwargs): - max_value = kwargs.pop('max_value', None) - min_value = kwargs.pop('min_value', None) - super(IntegerField, self).__init__(**kwargs) - if max_value is not None: - self.validators.append(validators.MaxValueValidator(max_value)) - if min_value is not None: - self.validators.append(validators.MinValueValidator(min_value)) - - def to_native(self, data): - try: - data = int(str(data)) - except (ValueError, TypeError): - self.fail('invalid_integer') - return data - def to_primative(self, value): - if value is None: - return None - return int(value) + return value -class EmailField(CharField): - pass # TODO - - -class URLField(CharField): - pass # TODO - - -class RegexField(CharField): - def __init__(self, **kwargs): - self.regex = kwargs.pop('regex') - super(CharField, self).__init__(**kwargs) - - -class DateField(CharField): - def __init__(self, **kwargs): - self.input_formats = kwargs.pop('input_formats', None) - super(DateField, self).__init__(**kwargs) - - -class TimeField(CharField): - def __init__(self, **kwargs): - self.input_formats = kwargs.pop('input_formats', None) - super(TimeField, self).__init__(**kwargs) - - -class DateTimeField(CharField): - def __init__(self, **kwargs): - self.input_formats = kwargs.pop('input_formats', None) - super(DateTimeField, self).__init__(**kwargs) - +# File types... class FileField(Field): pass # TODO +class ImageField(Field): + pass # TODO + + +# Advanced field types... + class ReadOnlyField(Field): + """ + A read-only field that simply returns the field value. + + If the field is a method with no parameters, the method will be called + and it's return value used as the representation. + + For example, the following would call `get_expiry_date()` on the object: + + class ExampleSerializer(self): + expiry_date = ReadOnlyField(source='get_expiry_date') + """ + + def __init__(self, **kwargs): + kwargs['read_only'] = True + super(ReadOnlyField, self).__init__(**kwargs) + + def to_native(self, data): + raise NotImplemented('.to_native() not supported.') + def to_primative(self, value): if is_simple_callable(value): return value() @@ -410,11 +755,28 @@ class ReadOnlyField(Field): class MethodField(Field): + """ + A read-only field that get its representation from calling a method on the + parent serializer class. The method called will be of the form + "get_{field_name}", and should take a single argument, which is the + object being serialized. + + For example: + + class ExampleSerializer(self): + extra_info = MethodField() + + def get_extra_info(self, obj): + return ... # Calculate some data to return. + """ def __init__(self, **kwargs): kwargs['source'] = '*' kwargs['read_only'] = True super(MethodField, self).__init__(**kwargs) + def to_native(self, data): + raise NotImplemented('.to_native() not supported.') + def to_primative(self, value): attr = 'get_{field_name}'.format(field_name=self.field_name) method = getattr(self.parent, attr) @@ -424,35 +786,14 @@ class MethodField(Field): class ModelField(Field): """ A generic field that can be used against an arbitrary model field. + + This is used by `ModelSerializer` when dealing with custom model fields, + that do not have a serializer field to be mapped to. """ - def __init__(self, *args, **kwargs): - try: - self.model_field = kwargs.pop('model_field') - except KeyError: - raise ValueError("ModelField requires 'model_field' kwarg") - - self.min_length = kwargs.pop('min_length', - getattr(self.model_field, 'min_length', None)) - self.max_length = kwargs.pop('max_length', - getattr(self.model_field, 'max_length', None)) - self.min_value = kwargs.pop('min_value', - getattr(self.model_field, 'min_value', None)) - self.max_value = kwargs.pop('max_value', - getattr(self.model_field, 'max_value', None)) - - super(ModelField, self).__init__(*args, **kwargs) - - if self.min_length is not None: - self.validators.append(validators.MinLengthValidator(self.min_length)) - if self.max_length is not None: - self.validators.append(validators.MaxLengthValidator(self.max_length)) - if self.min_value is not None: - self.validators.append(validators.MinValueValidator(self.min_value)) - if self.max_value is not None: - self.validators.append(validators.MaxValueValidator(self.max_value)) - - def get_attribute(self, instance): - return get_attribute(instance, self.source_attrs[:-1]) + def __init__(self, model_field, **kwargs): + self.model_field = model_field + kwargs['source'] = '*' + super(ModelField, self).__init__(**kwargs) def to_native(self, data): rel = getattr(self.model_field, 'rel', None) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 93226d322..8ca283876 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -10,15 +10,15 @@ python primitives. 2. The process of marshalling between python primitives and request and response content is handled by parsers and renderers. """ +from django.core import validators from django.core.exceptions import ValidationError from django.db import models from django.utils import six from collections import namedtuple, OrderedDict from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.settings import api_settings -from rest_framework.utils import html +from rest_framework.utils import html, modelinfo, representation import copy -import inspect # Note: We do the following so that users of the framework can use this style: # @@ -146,12 +146,10 @@ class SerializerMetaclass(type): class Serializer(BaseSerializer): def __new__(cls, *args, **kwargs): - many = kwargs.pop('many', False) - if many: - class DynamicListSerializer(ListSerializer): - child = cls() - return DynamicListSerializer(*args, **kwargs) - return super(Serializer, cls).__new__(cls) + if kwargs.pop('many', False): + kwargs['child'] = cls() + return ListSerializer(*args, **kwargs) + return super(Serializer, cls).__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): self.context = kwargs.pop('context', {}) @@ -248,6 +246,9 @@ class Serializer(BaseSerializer): error = errors.get(field.field_name) yield FieldResult(field, value, error) + def __repr__(self): + return representation.serializer_repr(self, indent=1) + class ListSerializer(BaseSerializer): child = None @@ -299,26 +300,8 @@ class ListSerializer(BaseSerializer): self.instance = self.create(self.validated_data) return self.instance - -def _resolve_model(obj): - """ - Resolve supplied `obj` to a Django model class. - - `obj` must be a Django model class itself, or a string - representation of one. Useful in situtations like GH #1225 where - Django may not have resolved a string-based reference to a model in - another model's foreign key definition. - - String representations should have the format: - 'appname.ModelName' - """ - if isinstance(obj, six.string_types) and len(obj.split('.')) == 2: - app_name, model_name = obj.split('.') - return models.get_model(app_name, model_name) - elif inspect.isclass(obj) and issubclass(obj, models.Model): - return obj - else: - raise ValueError("{0} is not a Django model".format(obj)) + def __repr__(self): + return representation.list_repr(self, indent=1) class ModelSerializerOptions(object): @@ -334,24 +317,25 @@ class ModelSerializerOptions(object): class ModelSerializer(Serializer): field_mapping = { models.AutoField: IntegerField, - # models.FloatField: FloatField, - models.IntegerField: IntegerField, - models.PositiveIntegerField: IntegerField, - models.SmallIntegerField: IntegerField, - models.PositiveSmallIntegerField: IntegerField, - models.DateTimeField: DateTimeField, - models.DateField: DateField, - models.TimeField: TimeField, - # models.DecimalField: DecimalField, - models.EmailField: EmailField, - models.CharField: CharField, - models.URLField: URLField, - # models.SlugField: SlugField, - models.TextField: CharField, - models.CommaSeparatedIntegerField: CharField, + models.BigIntegerField: IntegerField, models.BooleanField: BooleanField, - models.NullBooleanField: BooleanField, + models.CharField: CharField, + models.CommaSeparatedIntegerField: CharField, + models.DateField: DateField, + models.DateTimeField: DateTimeField, + models.DecimalField: DecimalField, + models.EmailField: EmailField, models.FileField: FileField, + models.FloatField: FloatField, + models.IntegerField: IntegerField, + models.NullBooleanField: BooleanField, + models.PositiveIntegerField: IntegerField, + models.PositiveSmallIntegerField: IntegerField, + models.SlugField: SlugField, + models.SmallIntegerField: IntegerField, + models.TextField: CharField, + models.TimeField: TimeField, + models.URLField: URLField, # models.ImageField: ImageField, } @@ -392,85 +376,31 @@ class ModelSerializer(Serializer): """ Return all the fields that should be serialized for the model. """ - cls = self.opts.model - opts = cls._meta.concrete_model._meta + info = modelinfo.get_field_info(self.opts.model) ret = OrderedDict() - nested = bool(self.opts.depth) - # Deal with adding the primary key field - pk_field = opts.pk - while pk_field.rel and pk_field.rel.parent_link: - # If model is a child via multitable inheritance, use parent's pk - pk_field = pk_field.rel.to._meta.pk - - serializer_pk_field = self.get_pk_field(pk_field) + serializer_pk_field = self.get_pk_field(info.pk) if serializer_pk_field: - ret[pk_field.name] = serializer_pk_field + ret[info.pk.name] = serializer_pk_field - # Deal with forward relationships - forward_rels = [field for field in opts.fields if field.serialize] - forward_rels += [field for field in opts.many_to_many if field.serialize] + # Regular fields + for field_name, field in info.fields.items(): + ret[field_name] = self.get_field(field) - for model_field in forward_rels: - has_through_model = False - - if model_field.rel: - to_many = isinstance(model_field, - models.fields.related.ManyToManyField) - related_model = _resolve_model(model_field.rel.to) - - if to_many and not model_field.rel.through._meta.auto_created: - has_through_model = True - - if model_field.rel and nested: - field = self.get_nested_field(model_field, related_model, to_many) - elif model_field.rel: - field = self.get_related_field(model_field, related_model, to_many) + # Forward relations + for field_name, relation_info in info.forward_relations.items(): + if self.opts.depth: + ret[field_name] = self.get_nested_field(*relation_info) else: - field = self.get_field(model_field) + ret[field_name] = self.get_related_field(*relation_info) - if field: - if has_through_model: - field.read_only = True - - ret[model_field.name] = field - - # Deal with reverse relationships - if not self.opts.fields: - reverse_rels = [] - else: - # Reverse relationships are only included if they are explicitly - # present in the `fields` option on the serializer - reverse_rels = opts.get_all_related_objects() - reverse_rels += opts.get_all_related_many_to_many_objects() - - for relation in reverse_rels: - accessor_name = relation.get_accessor_name() - if not self.opts.fields or accessor_name not in self.opts.fields: - continue - related_model = relation.model - to_many = relation.field.rel.multiple - has_through_model = False - is_m2m = isinstance(relation.field, - models.fields.related.ManyToManyField) - - if ( - is_m2m and - hasattr(relation.field.rel, 'through') and - not relation.field.rel.through._meta.auto_created - ): - has_through_model = True - - if nested: - field = self.get_nested_field(None, related_model, to_many) - else: - field = self.get_related_field(None, related_model, to_many) - - if field: - if has_through_model: - field.read_only = True - - ret[accessor_name] = field + # Reverse relations + for accessor_name, relation_info in info.reverse_relations.items(): + if accessor_name in self.opts.fields: + if self.opts.depth: + ret[field_name] = self.get_nested_field(*relation_info) + else: + ret[field_name] = self.get_related_field(*relation_info) return ret @@ -480,7 +410,7 @@ class ModelSerializer(Serializer): """ return self.get_field(model_field) - def get_nested_field(self, model_field, related_model, to_many): + def get_nested_field(self, model_field, related_model, to_many, has_through_model): """ Creates a default instance of a nested relational field. @@ -491,59 +421,148 @@ class ModelSerializer(Serializer): model = related_model depth = self.opts.depth - 1 - return NestedModelSerializer(many=to_many) + kwargs = {'read_only': True} + if to_many: + kwargs['many'] = True + return NestedModelSerializer(**kwargs) - def get_related_field(self, model_field, related_model, to_many): + def get_related_field(self, model_field, related_model, to_many, has_through_model): """ Creates a default instance of a flat relational field. Note that model_field will be `None` for reverse relationships. """ - # TODO: filter queryset using: - # .using(db).complex_filter(self.rel.limit_choices_to) + kwargs = { + 'queryset': related_model._default_manager, + } - kwargs = {} - # 'queryset': related_model._default_manager, - # 'many': to_many - # } + if to_many: + kwargs['many'] = True + + if has_through_model: + kwargs['read_only'] = True + kwargs.pop('queryset', None) if model_field: - kwargs['required'] = not(model_field.null or model_field.blank) + if model_field.null or model_field.blank: + kwargs['required'] = False # if model_field.help_text is not None: # kwargs['help_text'] = model_field.help_text if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name if not model_field.editable: kwargs['read_only'] = True - if model_field.verbose_name is not None: - kwargs['label'] = model_field.verbose_name + kwargs.pop('queryset', None) - return IntegerField(**kwargs) - # TODO: return PrimaryKeyRelatedField(**kwargs) + return PrimaryKeyRelatedField(**kwargs) def get_field(self, model_field): """ Creates a default instance of a basic non-relational field. """ kwargs = {} + validator_kwarg = model_field.validators if model_field.null or model_field.blank: kwargs['required'] = False - if isinstance(model_field, models.AutoField) or not model_field.editable: - kwargs['read_only'] = True - - if model_field.has_default(): - kwargs['default'] = model_field.get_default() - - if issubclass(model_field.__class__, models.TextField): - kwargs['widget'] = widgets.Textarea - if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name - if model_field.validators is not None: - kwargs['validators'] = model_field.validators + if isinstance(model_field, models.AutoField) or not model_field.editable: + kwargs['read_only'] = True + # Read only implies that the field is not required. + # We have a cleaner repr on the instance if we don't set it. + kwargs.pop('required', None) + + if model_field.has_default(): + kwargs['default'] = model_field.get_default() + # Having a default implies that the field is not required. + # We have a cleaner repr on the instance if we don't set it. + kwargs.pop('required', None) + + # 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: + kwargs['max_length'] = max_length + validator_kwarg = [ + validator for validator in validator_kwarg + if not isinstance(validator, validators.MaxLengthValidator) + ] + + # Ensure that min_length is passed explicitly as a keyword arg, + # rather than as a validator. + min_length = getattr(model_field, 'min_length', None) + if min_length is not None: + kwargs['min_length'] = min_length + validator_kwarg = [ + validator for validator in validator_kwarg + if not isinstance(validator, validators.MinLengthValidator) + ] + + # Ensure that max_value is passed explicitly as a keyword arg, + # rather than as a validator. + max_value = next(( + validator.limit_value for validator in validator_kwarg + if isinstance(validator, validators.MaxValueValidator) + ), None) + if max_value is not None: + kwargs['max_value'] = max_value + validator_kwarg = [ + validator for validator in validator_kwarg + if not isinstance(validator, validators.MaxValueValidator) + ] + + # Ensure that max_value is passed explicitly as a keyword arg, + # rather than as a validator. + min_value = next(( + validator.limit_value for validator in validator_kwarg + if isinstance(validator, validators.MinValueValidator) + ), None) + if min_value is not None: + kwargs['min_value'] = min_value + validator_kwarg = [ + validator for validator in validator_kwarg + if not isinstance(validator, validators.MinValueValidator) + ] + + # URLField does not need to include the URLValidator argument, + # as it is explicitly added in. + if isinstance(model_field, models.URLField): + validator_kwarg = [ + validator for validator in validator_kwarg + if not isinstance(validator, validators.URLValidator) + ] + + # EmailField does not need to include the validate_email argument, + # as it is explicitly added in. + if isinstance(model_field, models.EmailField): + validator_kwarg = [ + validator for validator in validator_kwarg + if validator is not validators.validate_email + ] + + # SlugField do not need to include the 'validate_slug' argument, + if isinstance(model_field, models.SlugField): + validator_kwarg = [ + validator for validator in validator_kwarg + if validator is not validators.validate_slug + ] + + max_digits = getattr(model_field, 'max_digits', None) + if max_digits is not None: + kwargs['max_digits'] = max_digits + + decimal_places = getattr(model_field, 'decimal_places', None) + if decimal_places is not None: + kwargs['decimal_places'] = decimal_places + + if validator_kwarg: + kwargs['validators'] = validator_kwarg + + # if issubclass(model_field.__class__, models.TextField): + # kwargs['widget'] = widgets.Textarea # if model_field.help_text is not None: # kwargs['help_text'] = model_field.help_text @@ -555,31 +574,10 @@ class ModelSerializer(Serializer): kwargs['empty'] = None return ChoiceField(**kwargs) - # put this below the ChoiceField because min_value isn't a valid initializer - if issubclass(model_field.__class__, models.PositiveIntegerField) or \ - issubclass(model_field.__class__, models.PositiveSmallIntegerField): - kwargs['min_value'] = 0 - if model_field.null and \ issubclass(model_field.__class__, (models.CharField, models.TextField)): kwargs['allow_none'] = True - # attribute_dict = { - # models.CharField: ['max_length'], - # models.CommaSeparatedIntegerField: ['max_length'], - # models.DecimalField: ['max_digits', 'decimal_places'], - # models.EmailField: ['max_length'], - # models.FileField: ['max_length'], - # models.ImageField: ['max_length'], - # models.SlugField: ['max_length'], - # models.URLField: ['max_length'], - # } - - # if model_field.__class__ in attribute_dict: - # attributes = attribute_dict[model_field.__class__] - # for attribute in attributes: - # kwargs.update({attribute: getattr(model_field, attribute)}) - try: return self.field_mapping[model_field.__class__](**kwargs) except KeyError: @@ -594,28 +592,21 @@ class HyperlinkedModelSerializerOptions(ModelSerializerOptions): super(HyperlinkedModelSerializerOptions, self).__init__(meta) self.view_name = getattr(meta, 'view_name', None) self.lookup_field = getattr(meta, 'lookup_field', None) - self.url_field_name = getattr(meta, 'url_field_name', api_settings.URL_FIELD_NAME) class HyperlinkedModelSerializer(ModelSerializer): _options_class = HyperlinkedModelSerializerOptions - _default_view_name = '%(model_name)s-detail' - _hyperlink_field_class = HyperlinkedRelatedField - _hyperlink_identify_field_class = HyperlinkedIdentityField def get_default_fields(self): fields = super(HyperlinkedModelSerializer, self).get_default_fields() if self.opts.view_name is None: - self.opts.view_name = self._get_default_view_name(self.opts.model) + self.opts.view_name = self.get_default_view_name(self.opts.model) - if self.opts.url_field_name not in fields: - url_field = self._hyperlink_identify_field_class( - view_name=self.opts.view_name, - lookup_field=self.opts.lookup_field - ) + url_field_name = api_settings.URL_FIELD_NAME + if url_field_name not in fields: ret = fields.__class__() - ret[self.opts.url_field_name] = url_field + ret[url_field_name] = self.get_url_field() ret.update(fields) fields = ret @@ -625,39 +616,48 @@ class HyperlinkedModelSerializer(ModelSerializer): if self.opts.fields and model_field.name in self.opts.fields: return self.get_field(model_field) - def get_related_field(self, model_field, related_model, to_many): + def get_url_field(self): + kwargs = { + 'view_name': self.get_default_view_name(self.opts.model) + } + if self.opts.lookup_field: + kwargs['lookup_field'] = self.opts.lookup_field + return HyperlinkedIdentityField(**kwargs) + + def get_related_field(self, model_field, related_model, to_many, has_through_model): """ Creates a default instance of a flat relational field. """ - # TODO: filter queryset using: - # .using(db).complex_filter(self.rel.limit_choices_to) - # kwargs = { - # 'queryset': related_model._default_manager, - # 'view_name': self._get_default_view_name(related_model), - # 'many': to_many - # } - kwargs = {} + kwargs = { + 'queryset': related_model._default_manager, + 'view_name': self.get_default_view_name(related_model), + } + + if to_many: + kwargs['many'] = True + + if has_through_model: + kwargs['read_only'] = True + kwargs.pop('queryset', None) if model_field: - kwargs['required'] = not(model_field.null or model_field.blank) + if model_field.null or model_field.blank: + kwargs['required'] = False # if model_field.help_text is not None: # kwargs['help_text'] = model_field.help_text if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name + if not model_field.editable: + kwargs['read_only'] = True + kwargs.pop('queryset', None) - return IntegerField(**kwargs) - # if self.opts.lookup_field: - # kwargs['lookup_field'] = self.opts.lookup_field + return HyperlinkedRelatedField(**kwargs) - # return self._hyperlink_field_class(**kwargs) - - def _get_default_view_name(self, model): + def get_default_view_name(self, model): """ - Return the view name to use if 'view_name' is not specified in 'Meta' + Return the view name to use for related models. """ - model_meta = model._meta - format_kwargs = { - 'app_label': model_meta.app_label, - 'model_name': model_meta.object_name.lower() + return '%(model_name)s-detail' % { + 'app_label': model._meta.app_label, + 'model_name': model._meta.object_name.lower() } - return self._default_view_name % format_kwargs diff --git a/rest_framework/utils/humanize_datetime.py b/rest_framework/utils/humanize_datetime.py new file mode 100644 index 000000000..649f2abc6 --- /dev/null +++ b/rest_framework/utils/humanize_datetime.py @@ -0,0 +1,47 @@ +""" +Helper functions that convert strftime formats into more readable representations. +""" +from rest_framework import ISO_8601 + + +def datetime_formats(formats): + format = ', '.join(formats).replace( + ISO_8601, + 'YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]' + ) + return humanize_strptime(format) + + +def date_formats(formats): + format = ', '.join(formats).replace(ISO_8601, 'YYYY[-MM[-DD]]') + return humanize_strptime(format) + + +def time_formats(formats): + format = ', '.join(formats).replace(ISO_8601, 'hh:mm[:ss[.uuuuuu]]') + return humanize_strptime(format) + + +def humanize_strptime(format_string): + # Note that we're missing some of the locale specific mappings that + # don't really make sense. + mapping = { + "%Y": "YYYY", + "%y": "YY", + "%m": "MM", + "%b": "[Jan-Dec]", + "%B": "[January-December]", + "%d": "DD", + "%H": "hh", + "%I": "hh", # Requires '%p' to differentiate from '%H'. + "%M": "mm", + "%S": "ss", + "%f": "uuuuuu", + "%a": "[Mon-Sun]", + "%A": "[Monday-Sunday]", + "%p": "[AM|PM]", + "%z": "[+HHMM|-HHMM]" + } + for key, val in mapping.items(): + format_string = format_string.replace(key, val) + return format_string diff --git a/rest_framework/utils/modelinfo.py b/rest_framework/utils/modelinfo.py new file mode 100644 index 000000000..c0513886c --- /dev/null +++ b/rest_framework/utils/modelinfo.py @@ -0,0 +1,97 @@ +""" +Helper functions for returning the field information that is associated +with a model class. +""" +from collections import namedtuple, OrderedDict +from django.db import models +from django.utils import six +import inspect + +FieldInfo = namedtuple('FieldResult', ['pk', 'fields', 'forward_relations', 'reverse_relations']) +RelationInfo = namedtuple('RelationInfo', ['field', 'related', 'to_many', 'has_through_model']) + + +def _resolve_model(obj): + """ + Resolve supplied `obj` to a Django model class. + + `obj` must be a Django model class itself, or a string + representation of one. Useful in situtations like GH #1225 where + Django may not have resolved a string-based reference to a model in + another model's foreign key definition. + + String representations should have the format: + 'appname.ModelName' + """ + if isinstance(obj, six.string_types) and len(obj.split('.')) == 2: + app_name, model_name = obj.split('.') + return models.get_model(app_name, model_name) + elif inspect.isclass(obj) and issubclass(obj, models.Model): + return obj + raise ValueError("{0} is not a Django model".format(obj)) + + +def get_field_info(model): + """ + Given a model class, returns a `FieldInfo` instance containing metadata + about the various field types on the model. + """ + opts = model._meta.concrete_model._meta + + # Deal with the primary key. + pk = opts.pk + while pk.rel and pk.rel.parent_link: + # If model is a child via multitable inheritance, use parent's pk. + pk = pk.rel.to._meta.pk + + # Deal with regular fields. + fields = OrderedDict() + for field in [field for field in opts.fields if field.serialize and not field.rel]: + fields[field.name] = field + + # Deal with forward relationships. + forward_relations = OrderedDict() + for field in [field for field in opts.fields if field.serialize and field.rel]: + forward_relations[field.name] = RelationInfo( + field=field, + related=_resolve_model(field.rel.to), + to_many=False, + has_through_model=False + ) + + # Deal with forward many-to-many relationships. + for field in [field for field in opts.many_to_many if field.serialize]: + forward_relations[field.name] = RelationInfo( + field=field, + related=_resolve_model(field.rel.to), + to_many=True, + has_through_model=( + not field.rel.through._meta.auto_created + ) + ) + + # Deal with reverse relationships. + reverse_relations = OrderedDict() + for relation in opts.get_all_related_objects(): + accessor_name = relation.get_accessor_name() + reverse_relations[accessor_name] = RelationInfo( + field=None, + related=relation.model, + to_many=relation.field.rel.multiple, + has_through_model=False + ) + + # Deal with reverse many-to-many relationships. + for relation in opts.get_all_related_many_to_many_objects(): + accessor_name = relation.get_accessor_name() + reverse_relations[accessor_name] = RelationInfo( + field=None, + related=relation.model, + to_many=True, + has_through_model=( + hasattr(relation.field.rel, 'through') and + not relation.field.rel.through._meta.auto_created + ) + ) + + return FieldInfo(pk, fields, forward_relations, reverse_relations) diff --git a/rest_framework/utils/representation.py b/rest_framework/utils/representation.py new file mode 100644 index 000000000..1de21597d --- /dev/null +++ b/rest_framework/utils/representation.py @@ -0,0 +1,72 @@ +""" +Helper functions for creating user-friendly representations +of serializer classes and serializer fields. +""" +import re + + +def smart_repr(value): + value = repr(value) + + # Representations like u'help text' + # should simply be presented as 'help text' + if value.startswith("u'") and value.endswith("'"): + return value[1:] + + # Representations like + # <django.core.validators.RegexValidator object at 0x1047af050> + # Should be presented as + # <django.core.validators.RegexValidator object> + value = re.sub(' at 0x[0-9a-f]{8,10}>', '>', value) + + return value + + +def field_repr(field, force_many=False): + kwargs = field._kwargs + if force_many: + kwargs = kwargs.copy() + kwargs['many'] = True + kwargs.pop('child', None) + + arg_string = ', '.join([smart_repr(val) for val in field._args]) + kwarg_string = ', '.join([ + '%s=%s' % (key, smart_repr(val)) + for key, val in sorted(kwargs.items()) + ]) + if arg_string and kwarg_string: + arg_string += ', ' + + if force_many: + class_name = force_many.__class__.__name__ + else: + class_name = field.__class__.__name__ + + return "%s(%s%s)" % (class_name, arg_string, kwarg_string) + + +def serializer_repr(serializer, indent, force_many=None): + ret = field_repr(serializer, force_many) + ':' + indent_str = ' ' * indent + + if force_many: + fields = force_many.fields + else: + fields = serializer.fields + + for field_name, field in fields.items(): + ret += '\n' + indent_str + field_name + ' = ' + if hasattr(field, 'fields'): + ret += serializer_repr(field, indent + 1) + elif hasattr(field, 'child'): + ret += list_repr(field, indent + 1) + else: + ret += field_repr(field) + return ret + + +def list_repr(serializer, indent): + child = serializer.child + if hasattr(child, 'fields'): + return serializer_repr(serializer, indent, force_many=child) + return field_repr(serializer) diff --git a/tests/test_model_field_mappings.py b/tests/test_model_field_mappings.py new file mode 100644 index 000000000..dc254da45 --- /dev/null +++ b/tests/test_model_field_mappings.py @@ -0,0 +1,160 @@ +""" +The `ModelSerializer` and `HyperlinkedModelSerializer` classes are essentially +shortcuts for automatically creating serializers based on a given model class. + +These tests deal with ensuring that we correctly map the model fields onto +an appropriate set of serializer fields for each case. +""" +from django.db import models +from django.test import TestCase +from rest_framework import serializers + + +# Models for testing regular field mapping + +class RegularFieldsModel(models.Model): + auto_field = models.AutoField(primary_key=True) + big_integer_field = models.BigIntegerField() + boolean_field = models.BooleanField() + char_field = models.CharField(max_length=100) + comma_seperated_integer_field = models.CommaSeparatedIntegerField(max_length=100) + date_field = models.DateField() + datetime_field = models.DateTimeField() + decimal_field = models.DecimalField(max_digits=3, decimal_places=1) + email_field = models.EmailField(max_length=100) + float_field = models.FloatField() + integer_field = models.IntegerField() + null_boolean_field = models.NullBooleanField() + positive_integer_field = models.PositiveIntegerField() + positive_small_integer_field = models.PositiveSmallIntegerField() + slug_field = models.SlugField(max_length=100) + small_integer_field = models.SmallIntegerField() + text_field = models.TextField() + time_field = models.TimeField() + url_field = models.URLField(max_length=100) + + +REGULAR_FIELDS_REPR = """ +TestSerializer(): + auto_field = IntegerField(label='auto field', read_only=True) + big_integer_field = IntegerField(label='big integer field') + boolean_field = BooleanField(default=False, label='boolean field') + char_field = CharField(label='char field', max_length=100) + comma_seperated_integer_field = CharField(label='comma seperated integer field', max_length=100, validators=[<django.core.validators.RegexValidator object>]) + date_field = DateField(label='date field') + datetime_field = DateTimeField(label='datetime field') + decimal_field = DecimalField(decimal_places=1, label='decimal field', max_digits=3) + email_field = EmailField(label='email field', max_length=100) + float_field = FloatField(label='float field') + integer_field = IntegerField(label='integer field') + null_boolean_field = BooleanField(label='null boolean field', required=False) + positive_integer_field = IntegerField(label='positive integer field') + positive_small_integer_field = IntegerField(label='positive small integer field') + slug_field = SlugField(label='slug field', max_length=100) + small_integer_field = IntegerField(label='small integer field') + text_field = CharField(label='text field') + time_field = TimeField(label='time field') + url_field = URLField(label='url field', max_length=100) +""".strip() + + +# Model for testing relational field mapping + +class ForeignKeyTarget(models.Model): + char_field = models.CharField(max_length=100) + + +class ManyToManyTarget(models.Model): + char_field = models.CharField(max_length=100) + + +class OneToOneTarget(models.Model): + char_field = models.CharField(max_length=100) + + +class RelationalModel(models.Model): + foreign_key = models.ForeignKey(ForeignKeyTarget) + many_to_many = models.ManyToManyField(ManyToManyTarget) + one_to_one = models.OneToOneField(OneToOneTarget) + + +RELATIONAL_FLAT_REPR = """ +TestSerializer(): + id = IntegerField(label='ID', read_only=True) + foreign_key = PrimaryKeyRelatedField(label='foreign key', queryset=<django.db.models.manager.Manager object>) + one_to_one = PrimaryKeyRelatedField(label='one to one', queryset=<django.db.models.manager.Manager object>) + many_to_many = PrimaryKeyRelatedField(label='many to many', many=True, queryset=<django.db.models.manager.Manager object>) +""".strip() + + +RELATIONAL_NESTED_REPR = """ +TestSerializer(): + id = IntegerField(label='ID', read_only=True) + foreign_key = NestedModelSerializer(read_only=True): + id = IntegerField(label='ID', read_only=True) + name = CharField(label='name', max_length=100) + one_to_one = NestedModelSerializer(read_only=True): + id = IntegerField(label='ID', read_only=True) + name = CharField(label='name', max_length=100) + many_to_many = NestedModelSerializer(many=True, read_only=True): + id = IntegerField(label='ID', read_only=True) + name = CharField(label='name', max_length=100) +""".strip() + + +HYPERLINKED_FLAT_REPR = """ +TestSerializer(): + url = HyperlinkedIdentityField(view_name='relationalmodel-detail') + foreign_key = HyperlinkedRelatedField(label='foreign key', queryset=<django.db.models.manager.Manager object>, view_name='foreignkeytarget-detail') + one_to_one = HyperlinkedRelatedField(label='one to one', queryset=<django.db.models.manager.Manager object>, view_name='onetoonetarget-detail') + many_to_many = HyperlinkedRelatedField(label='many to many', many=True, queryset=<django.db.models.manager.Manager object>, view_name='manytomanytarget-detail') +""".strip() + + +HYPERLINKED_NESTED_REPR = """ +TestSerializer(): + url = HyperlinkedIdentityField(view_name='relationalmodel-detail') + foreign_key = NestedModelSerializer(read_only=True): + id = IntegerField(label='ID', read_only=True) + name = CharField(label='name', max_length=100) + one_to_one = NestedModelSerializer(read_only=True): + id = IntegerField(label='ID', read_only=True) + name = CharField(label='name', max_length=100) + many_to_many = NestedModelSerializer(many=True, read_only=True): + id = IntegerField(label='ID', read_only=True) + name = CharField(label='name', max_length=100) +""".strip() + + +class TestSerializerMappings(TestCase): + def test_regular_fields(self): + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = RegularFieldsModel + self.assertEqual(repr(TestSerializer()), REGULAR_FIELDS_REPR) + + def test_flat_relational_fields(self): + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = RelationalModel + self.assertEqual(repr(TestSerializer()), RELATIONAL_FLAT_REPR) + + def test_nested_relational_fields(self): + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = RelationalModel + depth = 1 + self.assertEqual(repr(TestSerializer()), RELATIONAL_NESTED_REPR) + + def test_flat_hyperlinked_fields(self): + class TestSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = RelationalModel + self.assertEqual(repr(TestSerializer()), HYPERLINKED_FLAT_REPR) + + def test_nested_hyperlinked_fields(self): + class TestSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = RelationalModel + depth = 1 + self.assertEqual(repr(TestSerializer()), HYPERLINKED_NESTED_REPR) diff --git a/tests/test_serializers.py b/tests/test_modelinfo.py similarity index 94% rename from tests/test_serializers.py rename to tests/test_modelinfo.py index 31c417306..254a33c9c 100644 --- a/tests/test_serializers.py +++ b/tests/test_modelinfo.py @@ -1,6 +1,6 @@ from django.test import TestCase from django.utils import six -from rest_framework.serializers import _resolve_model +from rest_framework.utils.modelinfo import _resolve_model from tests.models import BasicModel diff --git a/tests/test_relations.py b/tests/test_relations.py index a30b12e68..b1bc66b62 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -22,18 +22,18 @@ # https://github.com/tomchristie/django-rest-framework/issues/446 # """ # field = serializers.PrimaryKeyRelatedField(queryset=NullModel.objects.all()) -# self.assertRaises(serializers.ValidationError, field.from_native, '') -# self.assertRaises(serializers.ValidationError, field.from_native, []) +# self.assertRaises(serializers.ValidationError, field.to_primative, '') +# self.assertRaises(serializers.ValidationError, field.to_primative, []) # def test_hyperlinked_related_field_with_empty_string(self): # field = serializers.HyperlinkedRelatedField(queryset=NullModel.objects.all(), view_name='') -# self.assertRaises(serializers.ValidationError, field.from_native, '') -# self.assertRaises(serializers.ValidationError, field.from_native, []) +# self.assertRaises(serializers.ValidationError, field.to_primative, '') +# self.assertRaises(serializers.ValidationError, field.to_primative, []) # def test_slug_related_field_with_empty_string(self): # field = serializers.SlugRelatedField(queryset=NullModel.objects.all(), slug_field='pk') -# self.assertRaises(serializers.ValidationError, field.from_native, '') -# self.assertRaises(serializers.ValidationError, field.from_native, []) +# self.assertRaises(serializers.ValidationError, field.to_primative, '') +# self.assertRaises(serializers.ValidationError, field.to_primative, []) # class TestManyRelatedMixin(TestCase): diff --git a/tests/test_serializer_empty.py b/tests/test_serializer_empty.py index d0006ad38..4e4a7b423 100644 --- a/tests/test_serializer_empty.py +++ b/tests/test_serializer_empty.py @@ -6,7 +6,7 @@ # def test_empty_serializer(self): # class FooBarSerializer(serializers.Serializer): # foo = serializers.IntegerField() -# bar = serializers.SerializerMethodField('get_bar') +# bar = serializers.MethodField() # def get_bar(self, obj): # return 'bar' From 234369aefdf08d7d0161d851866990754c00d31f Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 10 Sep 2014 08:53:33 +0100 Subject: [PATCH 021/249] Tweaks --- rest_framework/fields.py | 6 ++++-- rest_framework/serializers.py | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 043a44edd..e2bd57000 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -190,7 +190,7 @@ class Field(object): raise SkipField() return self.default - def validate(self, data=empty): + def validate_value(self, data=empty): """ Validate a simple representation and return the internal value. @@ -506,6 +506,7 @@ class DateField(Field): default_timezone = timezone.get_default_timezone() value = timezone.make_naive(value, default_timezone) return value.date() + if isinstance(value, datetime.date): return value @@ -560,6 +561,7 @@ class DateTimeField(Field): if isinstance(value, datetime.datetime): return value + if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) if settings.USE_TZ: @@ -675,7 +677,7 @@ class ChoiceField(Field): for item in choices ] if all(pairs): - self.choices = {key: val for key, val in choices} + self.choices = {key: display_value for key, display_value in choices} else: self.choices = {item: item for item in choices} diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 8ca283876..0727b8cdf 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -205,7 +205,7 @@ class Serializer(BaseSerializer): validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: - validated_value = field.validate(primitive_value) + validated_value = field.validate_value(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: @@ -327,6 +327,7 @@ class ModelSerializer(Serializer): models.EmailField: EmailField, models.FileField: FileField, models.FloatField: FloatField, + models.ImageField: ImageField, models.IntegerField: IntegerField, models.NullBooleanField: BooleanField, models.PositiveIntegerField: IntegerField, @@ -336,7 +337,6 @@ class ModelSerializer(Serializer): models.TextField: CharField, models.TimeField: TimeField, models.URLField: URLField, - # models.ImageField: ImageField, } _options_class = ModelSerializerOptions From 01c8c0cad977fc0787dbfc78bd34f4fd37e613f4 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 10 Sep 2014 13:52:16 +0100 Subject: [PATCH 022/249] Added help_text argument to fields --- rest_framework/compat.py | 23 +++++----- rest_framework/fields.py | 5 +- rest_framework/serializers.py | 86 +++++++++++++++++------------------ 3 files changed, 56 insertions(+), 58 deletions(-) diff --git a/rest_framework/compat.py b/rest_framework/compat.py index fa0f0bfb1..70b38df98 100644 --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -39,6 +39,17 @@ except ImportError: django_filters = 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 @@ -99,18 +110,8 @@ def get_concrete_model(model_cls): return model_cls -# View._allowed_methods only present from 1.5 onwards -if django.VERSION >= (1, 5): - from django.views.generic import View -else: - from django.views.generic import View as DjangoView - - class View(DjangoView): - def _allowed_methods(self): - return [m.upper() for m in self.http_method_names if hasattr(self, m)] - - # PATCH method is not implemented by Django +from django.views.generic import View if 'patch' not in View.http_method_names: View.http_method_names = View.http_method_names + ['patch'] diff --git a/rest_framework/fields.py b/rest_framework/fields.py index e2bd57000..e71dce1df 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -101,7 +101,8 @@ class Field(object): def __init__(self, read_only=False, write_only=False, required=None, default=empty, initial=None, source=None, - label=None, style=None, error_messages=None, validators=[]): + label=None, help_text=None, style=None, + error_messages=None, validators=[]): self._creation_counter = Field._creation_counter Field._creation_counter += 1 @@ -122,6 +123,7 @@ class Field(object): self.source = source self.initial = initial self.label = label + self.help_text = help_text self.style = {} if style is None else style self.validators = validators or self.default_validators[:] @@ -372,7 +374,6 @@ class IntegerField(Field): self.validators.append(validators.MaxValueValidator(max_value)) if min_value is not None: self.validators.append(validators.MinValueValidator(min_value)) - print self.__class__.__name__, self.validators def to_native(self, data): try: diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 0727b8cdf..459f8a8ce 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -15,6 +15,7 @@ from django.core.exceptions import ValidationError from django.db import models from django.utils import six from collections import namedtuple, OrderedDict +from rest_framework.compat import clean_manytomany_helptext from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.settings import api_settings from rest_framework.utils import html, modelinfo, representation @@ -117,8 +118,9 @@ class SerializerMetaclass(type): """ This metaclass sets a dictionary named `base_fields` on the class. - Any fields included as attributes on either the class or it's superclasses - will be include in the `base_fields` dictionary. + Any instances of `Field` included as attributes on either the class + or on any of its superclasses will be include in the + `base_fields` dictionary. """ @classmethod @@ -379,6 +381,10 @@ class ModelSerializer(Serializer): info = modelinfo.get_field_info(self.opts.model) ret = OrderedDict() + serializer_url_field = self.get_url_field() + if serializer_url_field: + ret[api_settings.URL_FIELD_NAME] = serializer_url_field + serializer_pk_field = self.get_pk_field(info.pk) if serializer_pk_field: ret[info.pk.name] = serializer_pk_field @@ -404,6 +410,9 @@ class ModelSerializer(Serializer): return ret + def get_url_field(self): + return None + def get_pk_field(self, model_field): """ Returns a default instance of the pk field. @@ -446,13 +455,14 @@ class ModelSerializer(Serializer): if model_field: if model_field.null or model_field.blank: kwargs['required'] = False - # if model_field.help_text is not None: - # kwargs['help_text'] = model_field.help_text - if model_field.verbose_name is not None: + if model_field.verbose_name: kwargs['label'] = model_field.verbose_name if not model_field.editable: kwargs['read_only'] = True kwargs.pop('queryset', None) + help_text = clean_manytomany_helptext(model_field.help_text) + if help_text: + kwargs['help_text'] = help_text return PrimaryKeyRelatedField(**kwargs) @@ -469,6 +479,9 @@ class ModelSerializer(Serializer): if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name + if model_field.help_text: + kwargs['help_text'] = model_field.help_text + if isinstance(model_field, models.AutoField) or not model_field.editable: kwargs['read_only'] = True # Read only implies that the field is not required. @@ -481,6 +494,14 @@ class ModelSerializer(Serializer): # We have a cleaner repr on the instance if we don't set it. kwargs.pop('required', None) + if model_field.flatchoices: + # If this model field contains choices, then use a ChoiceField, + # rather than the standard serializer field for this type. + # Note that we return this prior to setting any validation type + # keyword arguments, as those are not valid initializers. + kwargs['choices'] = model_field.flatchoices + return ChoiceField(**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) @@ -561,23 +582,6 @@ class ModelSerializer(Serializer): if validator_kwarg: kwargs['validators'] = validator_kwarg - # if issubclass(model_field.__class__, models.TextField): - # kwargs['widget'] = widgets.Textarea - - # if model_field.help_text is not None: - # kwargs['help_text'] = model_field.help_text - - # TODO: TypedChoiceField? - if model_field.flatchoices: # This ModelField contains choices - kwargs['choices'] = model_field.flatchoices - if model_field.null: - kwargs['empty'] = None - return ChoiceField(**kwargs) - - if model_field.null and \ - issubclass(model_field.__class__, (models.CharField, models.TextField)): - kwargs['allow_none'] = True - try: return self.field_mapping[model_field.__class__](**kwargs) except KeyError: @@ -597,33 +601,24 @@ class HyperlinkedModelSerializerOptions(ModelSerializerOptions): class HyperlinkedModelSerializer(ModelSerializer): _options_class = HyperlinkedModelSerializerOptions - def get_default_fields(self): - fields = super(HyperlinkedModelSerializer, self).get_default_fields() + def get_url_field(self): + if self.opts.view_name is not None: + view_name = self.opts.view_name + else: + view_name = self.get_default_view_name(self.opts.model) - if self.opts.view_name is None: - self.opts.view_name = self.get_default_view_name(self.opts.model) + kwargs = { + 'view_name': view_name + } + if self.opts.lookup_field: + kwargs['lookup_field'] = self.opts.lookup_field - url_field_name = api_settings.URL_FIELD_NAME - if url_field_name not in fields: - ret = fields.__class__() - ret[url_field_name] = self.get_url_field() - ret.update(fields) - fields = ret - - return fields + return HyperlinkedIdentityField(**kwargs) def get_pk_field(self, model_field): if self.opts.fields and model_field.name in self.opts.fields: return self.get_field(model_field) - def get_url_field(self): - kwargs = { - 'view_name': self.get_default_view_name(self.opts.model) - } - if self.opts.lookup_field: - kwargs['lookup_field'] = self.opts.lookup_field - return HyperlinkedIdentityField(**kwargs) - def get_related_field(self, model_field, related_model, to_many, has_through_model): """ Creates a default instance of a flat relational field. @@ -643,13 +638,14 @@ class HyperlinkedModelSerializer(ModelSerializer): if model_field: if model_field.null or model_field.blank: kwargs['required'] = False - # if model_field.help_text is not None: - # kwargs['help_text'] = model_field.help_text - if model_field.verbose_name is not None: + if model_field.verbose_name: kwargs['label'] = model_field.verbose_name if not model_field.editable: kwargs['read_only'] = True kwargs.pop('queryset', None) + help_text = clean_manytomany_helptext(model_field.help_text) + if help_text: + kwargs['help_text'] = help_text return HyperlinkedRelatedField(**kwargs) From 80ba0473473501968154c5cc5dd5922e53d96a70 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 10 Sep 2014 16:57:22 +0100 Subject: [PATCH 023/249] Compat fixes --- rest_framework/compat.py | 12 +++++++++++- rest_framework/fields.py | 14 +++++++------- rest_framework/serializers.py | 25 +++++++++++++------------ rest_framework/utils/modelinfo.py | 9 +++++---- 4 files changed, 36 insertions(+), 24 deletions(-) diff --git a/rest_framework/compat.py b/rest_framework/compat.py index 70b38df98..7c05bed9c 100644 --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -110,8 +110,18 @@ def get_concrete_model(model_cls): return model_cls +# View._allowed_methods only present from 1.5 onwards +if django.VERSION >= (1, 5): + from django.views.generic import View +else: + from django.views.generic import View as DjangoView + + class View(DjangoView): + def _allowed_methods(self): + return [m.upper() for m in self.http_method_names if hasattr(self, m)] + + # PATCH method is not implemented by Django -from django.views.generic import View if 'patch' not in View.http_method_names: View.http_method_names = View.http_method_names + ['patch'] diff --git a/rest_framework/fields.py b/rest_framework/fields.py index e71dce1df..3ec28908d 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -266,8 +266,8 @@ class BooleanField(Field): default_error_messages = { 'invalid': _('`{input}` is not a valid boolean.') } - TRUE_VALUES = {'t', 'T', 'true', 'True', 'TRUE', '1', 1, True} - FALSE_VALUES = {'f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False} + TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True)) + FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False)) def get_value(self, dictionary): if html.is_html_input(dictionary): @@ -678,16 +678,16 @@ class ChoiceField(Field): for item in choices ] if all(pairs): - self.choices = {key: display_value for key, display_value in choices} + self.choices = dict([(key, display_value) for key, display_value in choices]) else: - self.choices = {item: item for item in choices} + self.choices = dict([(item, item) for item in choices]) # Map the string representation of choices to the underlying value. # Allows us to deal with eg. integer choices while supporting either # integer or string input, but still get the correct datatype out. - self.choice_strings_to_values = { - str(key): key for key in self.choices.keys() - } + self.choice_strings_to_values = dict([ + (str(key), key) for key in self.choices.keys() + ]) super(ChoiceField, self).__init__(**kwargs) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 459f8a8ce..13e579398 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -14,7 +14,8 @@ from django.core import validators from django.core.exceptions import ValidationError from django.db import models from django.utils import six -from collections import namedtuple, OrderedDict +from django.utils.datastructures import SortedDict +from collections import namedtuple from rest_framework.compat import clean_manytomany_helptext from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.settings import api_settings @@ -91,10 +92,10 @@ class BaseSerializer(Field): if self.instance is not None: self._data = self.to_primative(self.instance) elif self._initial_data is not None: - self._data = { - field_name: field.get_value(self._initial_data) + self._data = dict([ + (field_name, field.get_value(self._initial_data)) for field_name, field in self.fields.items() - } + ]) else: self._data = self.get_initial() return self._data @@ -137,7 +138,7 @@ class SerializerMetaclass(type): if hasattr(base, 'base_fields'): fields = list(base.base_fields.items()) + fields - return OrderedDict(fields) + return SortedDict(fields) def __new__(cls, name, bases, attrs): attrs['base_fields'] = cls._get_fields(bases, attrs) @@ -180,10 +181,10 @@ class Serializer(BaseSerializer): field.bind(field_name, self, root) def get_initial(self): - return { - field.field_name: field.get_initial() + return dict([ + (field.field_name, field.get_initial()) for field in self.fields.values() - } + ]) def get_value(self, dictionary): # We override the default field access in order to support @@ -222,14 +223,14 @@ class Serializer(BaseSerializer): try: return self.validate(ret) - except ValidationError, exc: + except ValidationError as exc: raise ValidationError({'non_field_errors': exc.messages}) def to_primative(self, instance): """ Object instance -> Dict of primitive datatypes. """ - ret = OrderedDict() + ret = SortedDict() fields = [field for field in self.fields.values() if not field.write_only] for field in fields: @@ -368,7 +369,7 @@ class ModelSerializer(Serializer): # If `fields` is set on the `Meta` class, # then use only those fields, and in that order. if self.opts.fields: - fields = OrderedDict([ + fields = SortedDict([ (key, fields[key]) for key in self.opts.fields ]) @@ -379,7 +380,7 @@ class ModelSerializer(Serializer): Return all the fields that should be serialized for the model. """ info = modelinfo.get_field_info(self.opts.model) - ret = OrderedDict() + ret = SortedDict() serializer_url_field = self.get_url_field() if serializer_url_field: diff --git a/rest_framework/utils/modelinfo.py b/rest_framework/utils/modelinfo.py index c0513886c..a7a0346c2 100644 --- a/rest_framework/utils/modelinfo.py +++ b/rest_framework/utils/modelinfo.py @@ -2,9 +2,10 @@ Helper functions for returning the field information that is associated with a model class. """ -from collections import namedtuple, OrderedDict +from collections import namedtuple from django.db import models from django.utils import six +from django.utils.datastructures import SortedDict import inspect FieldInfo = namedtuple('FieldResult', ['pk', 'fields', 'forward_relations', 'reverse_relations']) @@ -45,12 +46,12 @@ def get_field_info(model): pk = pk.rel.to._meta.pk # Deal with regular fields. - fields = OrderedDict() + fields = SortedDict() for field in [field for field in opts.fields if field.serialize and not field.rel]: fields[field.name] = field # Deal with forward relationships. - forward_relations = OrderedDict() + forward_relations = SortedDict() for field in [field for field in opts.fields if field.serialize and field.rel]: forward_relations[field.name] = RelationInfo( field=field, @@ -71,7 +72,7 @@ def get_field_info(model): ) # Deal with reverse relationships. - reverse_relations = OrderedDict() + reverse_relations = SortedDict() for relation in opts.get_all_related_objects(): accessor_name = relation.get_accessor_name() reverse_relations[accessor_name] = RelationInfo( From 54ccf7230d0fcdabe8c2457539e314893915a34b Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 11 Sep 2014 13:43:46 +0100 Subject: [PATCH 024/249] Improve memory address removal for serializer representations --- rest_framework/utils/representation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/utils/representation.py b/rest_framework/utils/representation.py index 1de21597d..e2a374979 100644 --- a/rest_framework/utils/representation.py +++ b/rest_framework/utils/representation.py @@ -17,7 +17,7 @@ def smart_repr(value): # <django.core.validators.RegexValidator object at 0x1047af050> # Should be presented as # <django.core.validators.RegexValidator object> - value = re.sub(' at 0x[0-9a-f]{8,10}>', '>', value) + value = re.sub(' at 0x[0-9a-f]{8,32}>', '>', value) return value From 3318f75a7166cbac76a40d0461ca7b3e4640d3a2 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 11 Sep 2014 13:50:53 +0100 Subject: [PATCH 025/249] Improve memory address removal for serializer representations --- rest_framework/utils/representation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/utils/representation.py b/rest_framework/utils/representation.py index e2a374979..1a4d1a62c 100644 --- a/rest_framework/utils/representation.py +++ b/rest_framework/utils/representation.py @@ -17,7 +17,7 @@ def smart_repr(value): # <django.core.validators.RegexValidator object at 0x1047af050> # Should be presented as # <django.core.validators.RegexValidator object> - value = re.sub(' at 0x[0-9a-f]{8,32}>', '>', value) + value = re.sub(' at 0x[0-9a-f]{4,32}>', '>', value) return value From ab40780dc2f341a271c2f489659dcd48eb47c07d Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 11 Sep 2014 20:22:32 +0100 Subject: [PATCH 026/249] Tidy up lookup_class --- rest_framework/serializers.py | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 8fe999aec..4322f2134 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -317,17 +317,17 @@ class ModelSerializerOptions(object): self.depth = getattr(meta, 'depth', 0) -def lookup_class(mapping, obj): +def lookup_class(mapping, instance): """ Takes a dictionary with classes as keys, and an object. Traverses the object's inheritance hierarchy in method resolution order, and returns the first matching value - from the dictionary or None. + from the dictionary or raises a KeyError if nothing matches. """ - return next( - (mapping[cls] for cls in inspect.getmro(obj.__class__) if cls in mapping), - None - ) + for cls in inspect.getmro(instance.__class__): + if cls in mapping: + return mapping[cls] + raise KeyError('Class %s not found in lookup.', cls.__name__) class ModelSerializer(Serializer): @@ -341,6 +341,7 @@ class ModelSerializer(Serializer): models.DateTimeField: DateTimeField, models.DecimalField: DecimalField, models.EmailField: EmailField, + models.Field: ModelField, models.FileField: FileField, models.FloatField: FloatField, models.ImageField: ImageField, @@ -484,6 +485,7 @@ class ModelSerializer(Serializer): """ Creates a default instance of a basic non-relational field. """ + serializer_cls = lookup_class(self.field_mapping, model_field) kwargs = {} validator_kwarg = model_field.validators @@ -602,11 +604,10 @@ class ModelSerializer(Serializer): if validator_kwarg: kwargs['validators'] = validator_kwarg - cls = lookup_class(self.field_mapping, model_field) - if cls is None: - cls = ModelField + if issubclass(serializer_cls, ModelField): kwargs['model_field'] = model_field - return cls(**kwargs) + + return serializer_cls(**kwargs) class HyperlinkedModelSerializerOptions(ModelSerializerOptions): From bf52d04f4c370d6917599d26c84b73124d5ef366 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 11 Sep 2014 20:37:27 +0100 Subject: [PATCH 027/249] Nice manager representations on serializer classes --- rest_framework/utils/representation.py | 13 +++++++++++++ tests/test_model_field_mappings.py | 12 ++++++------ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/rest_framework/utils/representation.py b/rest_framework/utils/representation.py index 1a4d1a62c..71db18863 100644 --- a/rest_framework/utils/representation.py +++ b/rest_framework/utils/representation.py @@ -2,10 +2,23 @@ Helper functions for creating user-friendly representations of serializer classes and serializer fields. """ +from django.db import models import re +def manager_repr(value): + model = value.model + opts = model._meta + for _, name, manager in opts.concrete_managers + opts.abstract_managers: + if manager == value: + return '%s.%s.all()' % (model._meta.object_name, name) + return repr(value) + + def smart_repr(value): + if isinstance(value, models.Manager): + return manager_repr(value) + value = repr(value) # Representations like u'help text' diff --git a/tests/test_model_field_mappings.py b/tests/test_model_field_mappings.py index 57c97cb7d..6e9aaba6c 100644 --- a/tests/test_model_field_mappings.py +++ b/tests/test_model_field_mappings.py @@ -81,9 +81,9 @@ class RelationalModel(models.Model): RELATIONAL_FLAT_REPR = """ TestSerializer(): id = IntegerField(label='ID', read_only=True) - foreign_key = PrimaryKeyRelatedField(label='foreign key', queryset=<django.db.models.manager.Manager object>) - one_to_one = PrimaryKeyRelatedField(label='one to one', queryset=<django.db.models.manager.Manager object>) - many_to_many = PrimaryKeyRelatedField(label='many to many', many=True, queryset=<django.db.models.manager.Manager object>) + foreign_key = PrimaryKeyRelatedField(label='foreign key', queryset=ForeignKeyTargetModel.objects.all()) + one_to_one = PrimaryKeyRelatedField(label='one to one', queryset=OneToOneTargetModel.objects.all()) + many_to_many = PrimaryKeyRelatedField(label='many to many', many=True, queryset=ManyToManyTargetModel.objects.all()) """.strip() @@ -105,9 +105,9 @@ TestSerializer(): HYPERLINKED_FLAT_REPR = """ TestSerializer(): url = HyperlinkedIdentityField(view_name='relationalmodel-detail') - foreign_key = HyperlinkedRelatedField(label='foreign key', queryset=<django.db.models.manager.Manager object>, view_name='foreignkeytargetmodel-detail') - one_to_one = HyperlinkedRelatedField(label='one to one', queryset=<django.db.models.manager.Manager object>, view_name='onetoonetargetmodel-detail') - many_to_many = HyperlinkedRelatedField(label='many to many', many=True, queryset=<django.db.models.manager.Manager object>, view_name='manytomanytargetmodel-detail') + foreign_key = HyperlinkedRelatedField(label='foreign key', queryset=ForeignKeyTargetModel.objects.all(), view_name='foreignkeytargetmodel-detail') + one_to_one = HyperlinkedRelatedField(label='one to one', queryset=OneToOneTargetModel.objects.all(), view_name='onetoonetargetmodel-detail') + many_to_many = HyperlinkedRelatedField(label='many to many', many=True, queryset=ManyToManyTargetModel.objects.all(), view_name='manytomanytargetmodel-detail') """.strip() From 19b8f779de82fa4737b37fb4359145af0b07a56c Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 11 Sep 2014 20:43:44 +0100 Subject: [PATCH 028/249] Throttles now use Retry-After header and no longer support the custom style --- docs/api-guide/throttling.md | 2 ++ rest_framework/views.py | 1 - tests/test_throttling.py | 6 +----- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index 832304f15..16a7457b0 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -178,6 +178,8 @@ To create a custom throttle, override `BaseThrottle` and implement `.allow_reque Optionally you may also override the `.wait()` method. If implemented, `.wait()` should return a recommended number of seconds to wait before attempting the next request, or `None`. The `.wait()` method will only be called if `.allow_request()` has previously returned `False`. +If the `.wait()` method is implemented and the request is throttled, then a `Retry-After` header will be included in the response. + ## Example The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests. diff --git a/rest_framework/views.py b/rest_framework/views.py index 3b7b1c16c..cd394b2d9 100644 --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -62,7 +62,6 @@ def exception_handler(exc): if getattr(exc, 'auth_header', None): headers['WWW-Authenticate'] = exc.auth_header if getattr(exc, 'wait', None): - headers['X-Throttle-Wait-Seconds'] = '%d' % exc.wait headers['Retry-After'] = '%d' % exc.wait return Response({'detail': exc.detail}, diff --git a/tests/test_throttling.py b/tests/test_throttling.py index 7b696f070..cc36a004c 100644 --- a/tests/test_throttling.py +++ b/tests/test_throttling.py @@ -109,7 +109,7 @@ class ThrottlingTests(TestCase): def ensure_response_header_contains_proper_throttle_field(self, view, expected_headers): """ - Ensure the response returns an X-Throttle field with status and next attributes + Ensure the response returns an Retry-After field with status and next attributes set properly. """ request = self.factory.get('/') @@ -117,10 +117,8 @@ class ThrottlingTests(TestCase): self.set_throttle_timer(view, timer) response = view.as_view()(request) if expect is not None: - self.assertEqual(response['X-Throttle-Wait-Seconds'], expect) self.assertEqual(response['Retry-After'], expect) else: - self.assertFalse('X-Throttle-Wait-Seconds' in response) self.assertFalse('Retry-After' in response) def test_seconds_fields(self): @@ -173,13 +171,11 @@ class ThrottlingTests(TestCase): self.assertFalse(hasattr(MockView_NonTimeThrottling.throttle_classes[0], 'called')) response = MockView_NonTimeThrottling.as_view()(request) - self.assertFalse('X-Throttle-Wait-Seconds' in response) self.assertFalse('Retry-After' in response) self.assertTrue(MockView_NonTimeThrottling.throttle_classes[0].called) response = MockView_NonTimeThrottling.as_view()(request) - self.assertFalse('X-Throttle-Wait-Seconds' in response) self.assertFalse('Retry-After' in response) From 55650a743d579e0bc1643c8812428746b0271984 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 11 Sep 2014 20:49:10 +0100 Subject: [PATCH 029/249] no longer tightly coupled to private queryset API --- rest_framework/generics.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/rest_framework/generics.py b/rest_framework/generics.py index c2c59154a..408b12464 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -3,6 +3,7 @@ Generic views that provide commonly needed behaviour. """ from __future__ import unicode_literals +from django.db.models.query import QuerySet from django.core.exceptions import PermissionDenied from django.core.paginator import Paginator, InvalidPage from django.http import Http404 @@ -214,7 +215,9 @@ class GenericAPIView(views.APIView): % self.__class__.__name__ ) - return self.queryset._clone() + if isinstance(self.queryset, QuerySet): + return self.queryset.all() + return self.queryset def get_object(self): """ From a7518719917c7ad8e699119b442cfeb568ba1dde Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 11 Sep 2014 20:50:26 +0100 Subject: [PATCH 030/249] no longer tightly coupled to private queryset API --- rest_framework/generics.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 408b12464..338d56a6a 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -215,9 +215,11 @@ class GenericAPIView(views.APIView): % self.__class__.__name__ ) + queryset = self.queryset if isinstance(self.queryset, QuerySet): - return self.queryset.all() - return self.queryset + # Ensure queryset is re-evaluated on each request. + queryset = queryset.all() + return queryset def get_object(self): """ From 040bfcc09c851bb3dadd60558c78a1f7937e9fbd Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 11 Sep 2014 21:48:54 +0100 Subject: [PATCH 031/249] NotImplemented stubs for Field, and DecimalField improvements --- rest_framework/fields.py | 27 +++++++++++++++++++++------ rest_framework/pagination.py | 4 ++-- rest_framework/utils/encoders.py | 2 +- tests/test_filters.py | 10 +++++----- tests/test_pagination.py | 4 ++-- 5 files changed, 31 insertions(+), 16 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 7496a629e..20b8ffbff 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -229,13 +229,13 @@ class Field(object): """ Transform the *incoming* primative data into a native value. """ - return data + raise NotImplementedError('to_native() must be implemented.') def to_primative(self, value): """ Transform the *outgoing* native value into primative data. """ - return value + raise NotImplementedError('to_primative() must be implemented.') def fail(self, key, **kwargs): """ @@ -429,9 +429,10 @@ class DecimalField(Field): 'max_whole_digits': _('Ensure that there are no more than {max_whole_digits} digits before the decimal point.') } - def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, **kwargs): - self.max_value, self.min_value = max_value, min_value - self.max_digits, self.max_decimal_places = max_digits, decimal_places + def __init__(self, max_digits, decimal_places, coerce_to_string=True, max_value=None, min_value=None, **kwargs): + self.max_digits = max_digits + self.decimal_places = decimal_places + self.coerce_to_string = coerce_to_string super(DecimalField, self).__init__(**kwargs) if max_value is not None: self.validators.append(validators.MaxValueValidator(max_value)) @@ -478,12 +479,26 @@ class DecimalField(Field): if self.max_digits is not None and digits > self.max_digits: self.fail('max_digits', max_digits=self.max_digits) if self.decimal_places is not None and decimals > self.decimal_places: - self.fail('max_decimal_places', max_decimal_places=self.max_decimal_places) + self.fail('max_decimal_places', max_decimal_places=self.decimal_places) if self.max_digits is not None and self.decimal_places is not None and whole_digits > (self.max_digits - self.decimal_places): self.fail('max_whole_digits', max_while_digits=self.max_digits - self.decimal_places) return value + def to_primative(self, value): + if not self.coerce_to_string: + return value + + if isinstance(value, decimal.Decimal): + context = decimal.getcontext().copy() + context.prec = self.max_digits + quantized = value.quantize( + decimal.Decimal('.1') ** self.decimal_places, + context=context + ) + return '{0:f}'.format(quantized) + return '%.*f' % (self.max_decimal_places, value) + # Date & time fields... diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index 9cf31629f..d82d2d3b3 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -37,7 +37,7 @@ class PreviousPageField(serializers.Field): return replace_query_param(url, self.page_field, page) -class DefaultObjectSerializer(serializers.Field): +class DefaultObjectSerializer(serializers.ReadOnlyField): """ If no object serializer is specified, then this serializer will be applied as the default. @@ -79,6 +79,6 @@ class PaginationSerializer(BasePaginationSerializer): """ A default implementation of a pagination serializer. """ - count = serializers.Field(source='paginator.count') + count = serializers.ReadOnlyField(source='paginator.count') next = NextPageField(source='*') previous = PreviousPageField(source='*') diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py index 6a2f61266..7992b6b1c 100644 --- a/rest_framework/utils/encoders.py +++ b/rest_framework/utils/encoders.py @@ -43,7 +43,7 @@ class JSONEncoder(json.JSONEncoder): elif isinstance(o, datetime.timedelta): return str(o.total_seconds()) elif isinstance(o, decimal.Decimal): - return str(o) + return float(o) elif isinstance(o, QuerySet): return list(o) elif hasattr(o, 'tolist'): diff --git a/tests/test_filters.py b/tests/test_filters.py index 300e47e45..01668114b 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -102,7 +102,7 @@ if django_filters: class CommonFilteringTestCase(TestCase): def _serialize_object(self, obj): - return {'id': obj.id, 'text': obj.text, 'decimal': obj.decimal, 'date': obj.date} + return {'id': obj.id, 'text': obj.text, 'decimal': str(obj.decimal), 'date': obj.date} def setUp(self): """ @@ -145,7 +145,7 @@ class IntegrationTestFiltering(CommonFilteringTestCase): request = factory.get('/', {'decimal': '%s' % search_decimal}) response = view(request).render() self.assertEqual(response.status_code, status.HTTP_200_OK) - expected_data = [f for f in self.data if f['decimal'] == search_decimal] + expected_data = [f for f in self.data if Decimal(f['decimal']) == search_decimal] self.assertEqual(response.data, expected_data) # Tests that the date filter works. @@ -168,7 +168,7 @@ class IntegrationTestFiltering(CommonFilteringTestCase): request = factory.get('/', {'decimal': '%s' % search_decimal}) response = view(request).render() self.assertEqual(response.status_code, status.HTTP_200_OK) - expected_data = [f for f in self.data if f['decimal'] == search_decimal] + expected_data = [f for f in self.data if Decimal(f['decimal']) == search_decimal] self.assertEqual(response.data, expected_data) @unittest.skipUnless(django_filters, 'django-filter not installed') @@ -201,7 +201,7 @@ class IntegrationTestFiltering(CommonFilteringTestCase): request = factory.get('/', {'decimal': '%s' % search_decimal}) response = view(request).render() self.assertEqual(response.status_code, status.HTTP_200_OK) - expected_data = [f for f in self.data if f['decimal'] < search_decimal] + expected_data = [f for f in self.data if Decimal(f['decimal']) < search_decimal] self.assertEqual(response.data, expected_data) # Tests that the date filter set with 'gt' in the filter class works. @@ -230,7 +230,7 @@ class IntegrationTestFiltering(CommonFilteringTestCase): response = view(request).render() self.assertEqual(response.status_code, status.HTTP_200_OK) expected_data = [f for f in self.data if f['date'] > search_date and - f['decimal'] < search_decimal] + Decimal(f['decimal']) < search_decimal] self.assertEqual(response.data, expected_data) @unittest.skipUnless(django_filters, 'django-filter not installed') diff --git a/tests/test_pagination.py b/tests/test_pagination.py index 68983ba20..a7f8e691f 100644 --- a/tests/test_pagination.py +++ b/tests/test_pagination.py @@ -135,7 +135,7 @@ class IntegrationTestPaginationAndFiltering(TestCase): self.objects = FilterableItem.objects self.data = [ - {'id': obj.id, 'text': obj.text, 'decimal': obj.decimal, 'date': obj.date} + {'id': obj.id, 'text': obj.text, 'decimal': str(obj.decimal), 'date': obj.date} for obj in self.objects.all() ] @@ -381,7 +381,7 @@ class TestMaxPaginateByParam(TestCase): # Tests for context in pagination serializers -class CustomField(serializers.Field): +class CustomField(serializers.ReadOnlyField): def to_native(self, value): if 'view' not in self.context: raise RuntimeError("context isn't getting passed into custom field") From 1e53eb0aa2998385e26aa0a4d8542013bc7b575b Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 11 Sep 2014 21:57:32 +0100 Subject: [PATCH 032/249] DecimalFields should still be quantized even without coerce_to_string --- rest_framework/fields.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 20b8ffbff..a56ea96b0 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -486,9 +486,6 @@ class DecimalField(Field): return value def to_primative(self, value): - if not self.coerce_to_string: - return value - if isinstance(value, decimal.Decimal): context = decimal.getcontext().copy() context.prec = self.max_digits @@ -496,7 +493,12 @@ class DecimalField(Field): decimal.Decimal('.1') ** self.decimal_places, context=context ) + if not self.coerce_to_string: + return quantized return '{0:f}'.format(quantized) + + if not self.coerce_to_string: + return value return '%.*f' % (self.max_decimal_places, value) From adcb64ab4198f35c61d5be68956d201685ed3538 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 09:12:56 +0100 Subject: [PATCH 033/249] MethodField -> SerializerMethodField --- rest_framework/fields.py | 21 +++++++++------------ rest_framework/serializers.py | 3 ++- rest_framework/utils/modelinfo.py | 3 ++- tests/test_serializer_empty.py | 2 +- 4 files changed, 14 insertions(+), 15 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index a56ea96b0..5f198767c 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -768,16 +768,13 @@ class ReadOnlyField(Field): kwargs['read_only'] = True super(ReadOnlyField, self).__init__(**kwargs) - def to_native(self, data): - raise NotImplemented('.to_native() not supported.') - def to_primative(self, value): if is_simple_callable(value): return value() return value -class MethodField(Field): +class SerializerMethodField(Field): """ A read-only field that get its representation from calling a method on the parent serializer class. The method called will be of the form @@ -787,22 +784,22 @@ class MethodField(Field): For example: class ExampleSerializer(self): - extra_info = MethodField() + extra_info = SerializerMethodField() def get_extra_info(self, obj): return ... # Calculate some data to return. """ - def __init__(self, **kwargs): + def __init__(self, method_attr=None, **kwargs): + self.method_attr = method_attr kwargs['source'] = '*' kwargs['read_only'] = True - super(MethodField, self).__init__(**kwargs) - - def to_native(self, data): - raise NotImplemented('.to_native() not supported.') + super(SerializerMethodField, self).__init__(**kwargs) def to_primative(self, value): - attr = 'get_{field_name}'.format(field_name=self.field_name) - method = getattr(self.parent, attr) + method_attr = self.method_attr + if method_attr is None: + method_attr = 'get_{field_name}'.format(field_name=self.field_name) + method = getattr(self.parent, method_attr) return method(value) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 4322f2134..388fe29f0 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -598,7 +598,8 @@ class ModelSerializer(Serializer): if isinstance(model_field, models.BooleanField): # models.BooleanField has `blank=True`, but *is* actually # required *unless* a default is provided. - # Also note that <1.6 `default=False`, >=1.6 `default=None`. + # Also note that Django<1.6 uses `default=False` for + # models.BooleanField, but Django>=1.6 uses `default=None`. kwargs.pop('required', None) if validator_kwarg: diff --git a/rest_framework/utils/modelinfo.py b/rest_framework/utils/modelinfo.py index a7a0346c2..960fa4d0f 100644 --- a/rest_framework/utils/modelinfo.py +++ b/rest_framework/utils/modelinfo.py @@ -1,6 +1,7 @@ """ Helper functions for returning the field information that is associated -with a model class. +with a model class. This includes returning all the forward and reverse +relationships and their associated metadata. """ from collections import namedtuple from django.db import models diff --git a/tests/test_serializer_empty.py b/tests/test_serializer_empty.py index 4e4a7b423..805ac7d46 100644 --- a/tests/test_serializer_empty.py +++ b/tests/test_serializer_empty.py @@ -6,7 +6,7 @@ # def test_empty_serializer(self): # class FooBarSerializer(serializers.Serializer): # foo = serializers.IntegerField() -# bar = serializers.MethodField() +# bar = serializers.SerializerMethodField() # def get_bar(self, obj): # return 'bar' From 0d354e8f92c7daaf8dac3b80f0fd64f983f21e0b Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 09:49:35 +0100 Subject: [PATCH 034/249] to_internal_value() and to_representation() --- rest_framework/fields.py | 86 ++++++++++++++++++----------------- rest_framework/pagination.py | 4 +- rest_framework/relations.py | 2 +- rest_framework/serializers.py | 28 ++++++------ tests/test_validation.py | 2 +- 5 files changed, 62 insertions(+), 60 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 5f198767c..a96f9ba89 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -195,7 +195,7 @@ class Field(object): raise SkipField() return self.default - def validate_value(self, data=empty): + def run_validation(self, data=empty): """ Validate a simple representation and return the internal value. @@ -208,7 +208,7 @@ class Field(object): self.fail('required') return self.get_default() - value = self.to_native(data) + value = self.to_internal_value(data) self.run_validators(value) return value @@ -225,17 +225,17 @@ class Field(object): if errors: raise ValidationError(errors) - def to_native(self, data): + def to_internal_value(self, data): """ Transform the *incoming* primative data into a native value. """ - raise NotImplementedError('to_native() must be implemented.') + raise NotImplementedError('to_internal_value() must be implemented.') - def to_primative(self, value): + def to_representation(self, value): """ Transform the *outgoing* native value into primative data. """ - raise NotImplementedError('to_primative() must be implemented.') + raise NotImplementedError('to_representation() must be implemented.') def fail(self, key, **kwargs): """ @@ -279,14 +279,14 @@ class BooleanField(Field): return dictionary.get(self.field_name, False) return dictionary.get(self.field_name, empty) - def to_native(self, data): + def to_internal_value(self, data): if data in self.TRUE_VALUES: return True elif data in self.FALSE_VALUES: return False self.fail('invalid', input=data) - def to_primative(self, value): + def to_representation(self, value): if value is None: return None if value in self.TRUE_VALUES: @@ -309,12 +309,14 @@ class CharField(Field): self.min_length = kwargs.pop('min_length', None) super(CharField, self).__init__(**kwargs) - def to_native(self, data): + def to_internal_value(self, data): if data == '' and not self.allow_blank: self.fail('blank') + if data is None: + return None return str(data) - def to_primative(self, value): + def to_representation(self, value): if value is None: return None return str(value) @@ -326,17 +328,17 @@ class EmailField(CharField): } default_validators = [validators.validate_email] - def to_native(self, data): - ret = super(EmailField, self).to_native(data) - if ret is None: + def to_internal_value(self, data): + if data == '' and not self.allow_blank: + self.fail('blank') + if data is None: return None - return ret.strip() + return str(data).strip() - def to_primative(self, value): - ret = super(EmailField, self).to_primative(value) - if ret is None: + def to_representation(self, value): + if value is None: return None - return ret.strip() + return str(value).strip() class RegexField(CharField): @@ -378,14 +380,14 @@ class IntegerField(Field): if min_value is not None: self.validators.append(validators.MinValueValidator(min_value)) - def to_native(self, data): + def to_internal_value(self, data): try: data = int(str(data)) except (ValueError, TypeError): self.fail('invalid') return data - def to_primative(self, value): + def to_representation(self, value): if value is None: return None return int(value) @@ -405,7 +407,12 @@ class FloatField(Field): if min_value is not None: self.validators.append(validators.MinValueValidator(min_value)) - def to_primative(self, value): + def to_internal_value(self, value): + if value is None: + return None + return float(value) + + def to_representation(self, value): if value is None: return None try: @@ -413,11 +420,6 @@ class FloatField(Field): except (TypeError, ValueError): self.fail('invalid', value=value) - def to_native(self, value): - if value is None: - return None - return float(value) - class DecimalField(Field): default_error_messages = { @@ -439,7 +441,7 @@ class DecimalField(Field): if min_value is not None: self.validators.append(validators.MinValueValidator(min_value)) - def from_native(self, value): + def to_internal_value(self, value): """ Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures that there are no more @@ -485,7 +487,7 @@ class DecimalField(Field): return value - def to_primative(self, value): + def to_representation(self, value): if isinstance(value, decimal.Decimal): context = decimal.getcontext().copy() context.prec = self.max_digits @@ -516,7 +518,7 @@ class DateField(Field): self.format = format if format is not None else self.format super(DateField, self).__init__(*args, **kwargs) - def from_native(self, value): + def to_internal_value(self, value): if value in validators.EMPTY_VALUES: return None @@ -552,7 +554,7 @@ class DateField(Field): msg = self.error_messages['invalid'] % humanized_format raise ValidationError(msg) - def to_primative(self, value): + def to_representation(self, value): if value is None or self.format is None: return value @@ -576,7 +578,7 @@ class DateTimeField(Field): self.format = format if format is not None else self.format super(DateTimeField, self).__init__(*args, **kwargs) - def from_native(self, value): + def to_internal_value(self, value): if value in validators.EMPTY_VALUES: return None @@ -618,7 +620,7 @@ class DateTimeField(Field): msg = self.error_messages['invalid'] % humanized_format raise ValidationError(msg) - def to_primative(self, value): + def to_representation(self, value): if value is None or self.format is None: return value @@ -670,7 +672,7 @@ class TimeField(Field): msg = self.error_messages['invalid'] % humanized_format raise ValidationError(msg) - def to_primative(self, value): + def to_representation(self, value): if value is None or self.format is None: return value @@ -711,13 +713,13 @@ class ChoiceField(Field): super(ChoiceField, self).__init__(**kwargs) - def to_native(self, data): + def to_internal_value(self, data): try: return self.choice_strings_to_values[str(data)] except KeyError: self.fail('invalid_choice', input=data) - def to_primative(self, value): + def to_representation(self, value): return value @@ -727,15 +729,15 @@ class MultipleChoiceField(ChoiceField): 'not_a_list': _('Expected a list of items but got type `{input_type}`') } - def to_native(self, data): + def to_internal_value(self, data): if not hasattr(data, '__iter__'): self.fail('not_a_list', input_type=type(data).__name__) return set([ - super(MultipleChoiceField, self).to_native(item) + super(MultipleChoiceField, self).to_internal_value(item) for item in data ]) - def to_primative(self, value): + def to_representation(self, value): return value @@ -768,7 +770,7 @@ class ReadOnlyField(Field): kwargs['read_only'] = True super(ReadOnlyField, self).__init__(**kwargs) - def to_primative(self, value): + def to_representation(self, value): if is_simple_callable(value): return value() return value @@ -795,7 +797,7 @@ class SerializerMethodField(Field): kwargs['read_only'] = True super(SerializerMethodField, self).__init__(**kwargs) - def to_primative(self, value): + def to_representation(self, value): method_attr = self.method_attr if method_attr is None: method_attr = 'get_{field_name}'.format(field_name=self.field_name) @@ -815,13 +817,13 @@ class ModelField(Field): kwargs['source'] = '*' super(ModelField, self).__init__(**kwargs) - def to_native(self, data): + def to_internal_value(self, data): rel = getattr(self.model_field, 'rel', None) if rel is not None: return rel.to._meta.get_field(rel.field_name).to_python(data) return self.model_field.to_python(data) - def to_primative(self, obj): + def to_representation(self, obj): value = self.model_field._get_val_from_obj(obj) if is_protected_type(value): return value diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index d82d2d3b3..c5a9270a4 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -13,7 +13,7 @@ class NextPageField(serializers.Field): """ page_field = 'page' - def to_primative(self, value): + def to_representation(self, value): if not value.has_next(): return None page = value.next_page_number() @@ -28,7 +28,7 @@ class PreviousPageField(serializers.Field): """ page_field = 'page' - def to_primative(self, value): + def to_representation(self, value): if not value.has_previous(): return None page = value.previous_page_number() diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 661a1249a..30a252db9 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -110,7 +110,7 @@ class HyperlinkedIdentityField(RelatedField): def get_attribute(self, instance): return instance - def to_primative(self, value): + def to_representation(self, value): request = self.context.get('request', None) format = self.context.get('format', None) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 388fe29f0..502b1e190 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -47,11 +47,11 @@ class BaseSerializer(Field): self.instance = instance self._initial_data = data - def to_native(self, data): - raise NotImplementedError('`to_native()` must be implemented.') + def to_internal_value(self, data): + raise NotImplementedError('`to_internal_value()` must be implemented.') - def to_primative(self, instance): - raise NotImplementedError('`to_primative()` must be implemented.') + def to_representation(self, instance): + raise NotImplementedError('`to_representation()` must be implemented.') def update(self, instance, attrs): raise NotImplementedError('`update()` must be implemented.') @@ -74,7 +74,7 @@ class BaseSerializer(Field): def is_valid(self, raise_exception=False): if not hasattr(self, '_validated_data'): try: - self._validated_data = self.to_native(self._initial_data) + self._validated_data = self.to_internal_value(self._initial_data) except ValidationError as exc: self._validated_data = {} self._errors = exc.message_dict @@ -90,7 +90,7 @@ class BaseSerializer(Field): def data(self): if not hasattr(self, '_data'): if self.instance is not None: - self._data = self.to_primative(self.instance) + self._data = self.to_representation(self.instance) elif self._initial_data is not None: self._data = dict([ (field_name, field.get_value(self._initial_data)) @@ -193,7 +193,7 @@ class Serializer(BaseSerializer): return html.parse_html_dict(dictionary, prefix=self.field_name) return dictionary.get(self.field_name, empty) - def to_native(self, data): + def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ @@ -208,7 +208,7 @@ class Serializer(BaseSerializer): validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: - validated_value = field.validate_value(primitive_value) + validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: @@ -226,7 +226,7 @@ class Serializer(BaseSerializer): except ValidationError as exc: raise ValidationError({'non_field_errors': exc.messages}) - def to_primative(self, instance): + def to_representation(self, instance): """ Object instance -> Dict of primitive datatypes. """ @@ -235,7 +235,7 @@ class Serializer(BaseSerializer): for field in fields: native_value = field.get_attribute(instance) - ret[field.field_name] = field.to_primative(native_value) + ret[field.field_name] = field.to_representation(native_value) return ret @@ -279,20 +279,20 @@ class ListSerializer(BaseSerializer): return html.parse_html_list(dictionary, prefix=self.field_name) return dictionary.get(self.field_name, empty) - def to_native(self, data): + def to_internal_value(self, data): """ List of dicts of native values <- List of dicts of primitive datatypes. """ if html.is_html_input(data): data = html.parse_html_list(data) - return [self.child.validate(item) for item in data] + return [self.child.run_validation(item) for item in data] - def to_primative(self, data): + def to_representation(self, data): """ List of object instances -> List of dicts of primitive datatypes. """ - return [self.child.to_primative(item) for item in data] + return [self.child.to_representation(item) for item in data] def create(self, attrs_list): return [self.child.create(attrs) for attrs in attrs_list] diff --git a/tests/test_validation.py b/tests/test_validation.py index c4506e7e9..7543d849b 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -158,7 +158,7 @@ class TestChoiceFieldChoicesValidate(TestCase): f = serializers.ChoiceField(choices=self.CHOICES) value = self.CHOICES[0][0] try: - f.to_native(value) + f.to_internal_value(value) except ValidationError: self.fail("Value %s does not validate" % str(value)) From 6db3356c4d1aa4f9a042b0ec67d47238abc16dd7 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 10:21:35 +0100 Subject: [PATCH 035/249] NON_FIELD_ERRORS_KEY setting --- rest_framework/serializers.py | 8 ++++++-- rest_framework/settings.py | 1 + rest_framework/views.py | 8 +++++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 502b1e190..0c2aedfa0 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -198,7 +198,9 @@ class Serializer(BaseSerializer): Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, dict): - raise ValidationError({'non_field_errors': ['Invalid data']}) + raise ValidationError({ + api_settings.NON_FIELD_ERRORS_KEY: ['Invalid data'] + }) ret = {} errors = {} @@ -224,7 +226,9 @@ class Serializer(BaseSerializer): try: return self.validate(ret) except ValidationError as exc: - raise ValidationError({'non_field_errors': exc.messages}) + raise ValidationError({ + api_settings.NON_FIELD_ERRORS_KEY: exc.messages + }) def to_representation(self, instance): """ diff --git a/rest_framework/settings.py b/rest_framework/settings.py index bbe7a56ad..f48643b5d 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -77,6 +77,7 @@ DEFAULTS = { # Exception handling 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler', + 'NON_FIELD_ERRORS_KEY': 'non_field_errors', # Testing 'TEST_REQUEST_RENDERER_CLASSES': ( diff --git a/rest_framework/views.py b/rest_framework/views.py index cd394b2d9..9f08a4ad5 100644 --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -3,7 +3,7 @@ Provides an APIView class that is the base of all views in REST framework. """ from __future__ import unicode_literals -from django.core.exceptions import PermissionDenied, ValidationError +from django.core.exceptions import PermissionDenied, ValidationError, NON_FIELD_ERRORS from django.http import Http404 from django.utils.datastructures import SortedDict from django.views.decorators.csrf import csrf_exempt @@ -69,6 +69,12 @@ def exception_handler(exc): headers=headers) elif isinstance(exc, ValidationError): + # ValidationErrors may include the non-field key named '__all__'. + # When returning a response we map this to a key name that can be + # modified in settings. + if NON_FIELD_ERRORS in exc.message_dict: + errors = exc.message_dict.pop(NON_FIELD_ERRORS) + exc.message_dict[api_settings.NON_FIELD_ERRORS_KEY] = errors return Response(exc.message_dict, status=status.HTTP_400_BAD_REQUEST) From 250755def707e1397876614fa0c08130d9fcc449 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 10:59:51 +0100 Subject: [PATCH 036/249] Clean up relational fields queryset usage --- rest_framework/fields.py | 15 +++----- rest_framework/generics.py | 2 +- rest_framework/relations.py | 73 ++++++++++++++++++++----------------- tests/test_generics.py | 4 +- 4 files changed, 49 insertions(+), 45 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index a96f9ba89..4f06d1868 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -508,7 +508,7 @@ class DecimalField(Field): class DateField(Field): default_error_messages = { - 'invalid': _("Date has wrong format. Use one of these formats instead: %s"), + 'invalid': _('Date has wrong format. Use one of these formats instead: {format}'), } input_formats = api_settings.DATE_INPUT_FORMATS format = api_settings.DATE_FORMAT @@ -551,8 +551,7 @@ class DateField(Field): return parsed.date() humanized_format = humanize_datetime.date_formats(self.input_formats) - msg = self.error_messages['invalid'] % humanized_format - raise ValidationError(msg) + self.fail('invalid', format=humanized_format) def to_representation(self, value): if value is None or self.format is None: @@ -568,7 +567,7 @@ class DateField(Field): class DateTimeField(Field): default_error_messages = { - 'invalid': _("Datetime has wrong format. Use one of these formats instead: %s"), + 'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}'), } input_formats = api_settings.DATETIME_INPUT_FORMATS format = api_settings.DATETIME_FORMAT @@ -617,8 +616,7 @@ class DateTimeField(Field): return parsed humanized_format = humanize_datetime.datetime_formats(self.input_formats) - msg = self.error_messages['invalid'] % humanized_format - raise ValidationError(msg) + self.fail('invalid', format=humanized_format) def to_representation(self, value): if value is None or self.format is None: @@ -634,7 +632,7 @@ class DateTimeField(Field): class TimeField(Field): default_error_messages = { - 'invalid': _("Time has wrong format. Use one of these formats instead: %s"), + 'invalid': _('Time has wrong format. Use one of these formats instead: {format}'), } input_formats = api_settings.TIME_INPUT_FORMATS format = api_settings.TIME_FORMAT @@ -669,8 +667,7 @@ class TimeField(Field): return parsed.time() humanized_format = humanize_datetime.time_formats(self.input_formats) - msg = self.error_messages['invalid'] % humanized_format - raise ValidationError(msg) + self.fail('invalid', format=humanized_format) def to_representation(self, value): if value is None or self.format is None: diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 338d56a6a..eb6b64efa 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -216,7 +216,7 @@ class GenericAPIView(views.APIView): ) queryset = self.queryset - if isinstance(self.queryset, QuerySet): + if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 30a252db9..e23a41526 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -2,28 +2,35 @@ from rest_framework.fields import Field from rest_framework.reverse import reverse from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch +from django.db.models.query import QuerySet from rest_framework.compat import urlparse -def get_default_queryset(serializer_class, field_name): - manager = getattr(serializer_class.opts.model, field_name) - if hasattr(manager, 'related'): - # Forward relationships - return manager.related.model._default_manager.all() - # Reverse relationships - return manager.field.rel.to._default_manager.all() - - class RelatedField(Field): def __init__(self, **kwargs): self.queryset = kwargs.pop('queryset', None) self.many = kwargs.pop('many', False) + assert self.queryset is not None or kwargs.get('read_only', False), ( + 'Relational field must provide a `queryset` argument, ' + 'or set read_only=`True`.' + ) super(RelatedField, self).__init__(**kwargs) - def bind(self, field_name, parent, root): - super(RelatedField, self).bind(field_name, parent, root) - if self.queryset is None and not self.read_only: - self.queryset = get_default_queryset(parent, self.source) + def get_queryset(self): + queryset = self.queryset + if isinstance(queryset, QuerySet): + # Ensure queryset is re-evaluated whenever used. + queryset = queryset.all() + return queryset + + +class StringRelatedField(Field): + def __init__(self, **kwargs): + kwargs['read_only'] = True + super(StringRelatedField, self).__init__(**kwargs) + + def to_representation(self, value): + return str(value) class PrimaryKeyRelatedField(RelatedField): @@ -33,9 +40,9 @@ class PrimaryKeyRelatedField(RelatedField): 'incorrect_type': 'Incorrect type. Expected pk value, received {data_type}.', } - def from_native(self, data): + def to_internal_value(self, data): try: - return self.queryset.get(pk=data) + return self.get_queryset().get(pk=data) except ObjectDoesNotExist: self.fail('does_not_exist', pk_value=data) except (TypeError, ValueError): @@ -68,9 +75,9 @@ class HyperlinkedRelatedField(RelatedField): """ lookup_value = view_kwargs[self.lookup_url_kwarg] lookup_kwargs = {self.lookup_field: lookup_value} - return self.queryset.get(**lookup_kwargs) + return self.get_queryset().get(**lookup_kwargs) - def from_native(self, value): + def to_internal_value(self, value): try: http_prefix = value.startswith(('http:', 'https:')) except AttributeError: @@ -102,13 +109,26 @@ class HyperlinkedIdentityField(RelatedField): def __init__(self, **kwargs): kwargs['read_only'] = True + kwargs['source'] = '*' self.view_name = kwargs.pop('view_name') self.lookup_field = kwargs.pop('lookup_field', self.lookup_field) self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field) super(HyperlinkedIdentityField, self).__init__(**kwargs) - def get_attribute(self, instance): - return instance + def get_url(self, obj, view_name, request, format): + """ + Given an object, return the URL that hyperlinks to the object. + + May raise a `NoReverseMatch` if the `view_name` and `lookup_field` + attributes are not configured to correctly match the URL conf. + """ + # Unsaved objects will not yet have a valid URL. + if obj.pk is None: + return None + + lookup_value = getattr(obj, self.lookup_field) + kwargs = {self.lookup_url_kwarg: lookup_value} + return reverse(view_name, kwargs=kwargs, request=request, format=format) def to_representation(self, value): request = self.context.get('request', None) @@ -144,21 +164,6 @@ class HyperlinkedIdentityField(RelatedField): ) raise Exception(msg % self.view_name) - def get_url(self, obj, view_name, request, format): - """ - Given an object, return the URL that hyperlinks to the object. - - May raise a `NoReverseMatch` if the `view_name` and `lookup_field` - attributes are not configured to correctly match the URL conf. - """ - # Unsaved objects will not yet have a valid URL. - if obj.pk is None: - return None - - lookup_value = getattr(obj, self.lookup_field) - kwargs = {self.lookup_url_kwarg: lookup_value} - return reverse(view_name, kwargs=kwargs, request=request, format=format) - class SlugRelatedField(RelatedField): def __init__(self, **kwargs): diff --git a/tests/test_generics.py b/tests/test_generics.py index 17bfca2ff..51004edfe 100644 --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -547,7 +547,9 @@ class ClassA(models.Model): class ClassASerializer(serializers.ModelSerializer): - childs = serializers.PrimaryKeyRelatedField(many=True, source='childs') + childs = serializers.PrimaryKeyRelatedField( + many=True, queryset=ClassB.objects.all() + ) class Meta: model = ClassA From 5e39e159ee6aee90755709cfecec7d22c7ea3049 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 11:38:22 +0100 Subject: [PATCH 037/249] UNICODE_JSON and COMPACT_JSON settings --- rest_framework/fields.py | 20 ++++++++++---------- rest_framework/parsers.py | 2 +- rest_framework/renderers.py | 33 ++++++++++++--------------------- rest_framework/settings.py | 3 +++ tests/test_renderers.py | 35 +++++++++++++++++++---------------- tests/test_validation.py | 2 +- 6 files changed, 46 insertions(+), 49 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 4f06d1868..9d96cf5cc 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -137,6 +137,16 @@ class Field(object): messages.update(error_messages or {}) self.error_messages = messages + def __new__(cls, *args, **kwargs): + """ + When a field is instantiated, we store the arguments that were used, + so that we can present a helpful representation of the object. + """ + instance = super(Field, cls).__new__(cls) + instance._args = args + instance._kwargs = kwargs + return instance + def bind(self, field_name, parent, root): """ Setup the context for the field instance. @@ -249,16 +259,6 @@ class Field(object): raise AssertionError(msg) raise ValidationError(msg.format(**kwargs)) - def __new__(cls, *args, **kwargs): - """ - When a field is instantiated, we store the arguments that were used, - so that we can present a helpful representation of the object. - """ - instance = super(Field, cls).__new__(cls) - instance._args = args - instance._kwargs = kwargs - return instance - def __repr__(self): return representation.field_repr(self) diff --git a/rest_framework/parsers.py b/rest_framework/parsers.py index c287908dc..fa02ecf1e 100644 --- a/rest_framework/parsers.py +++ b/rest_framework/parsers.py @@ -48,7 +48,7 @@ class JSONParser(BaseParser): """ media_type = 'application/json' - renderer_class = renderers.UnicodeJSONRenderer + renderer_class = renderers.JSONRenderer def parse(self, stream, media_type=None, parser_context=None): """ diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index dfc5a39f6..3bf03e62c 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -26,6 +26,10 @@ from rest_framework.utils.breadcrumbs import get_breadcrumbs from rest_framework import exceptions, status, VERSION +def zero_as_none(value): + return None if value == 0 else value + + class BaseRenderer(object): """ All renderers should extend this class, setting the `media_type` @@ -44,13 +48,13 @@ class BaseRenderer(object): class JSONRenderer(BaseRenderer): """ Renderer which serializes to JSON. - Applies JSON's backslash-u character escaping for non-ascii characters. """ media_type = 'application/json' format = 'json' encoder_class = encoders.JSONEncoder - ensure_ascii = True + ensure_ascii = not api_settings.UNICODE_JSON + compact = api_settings.COMPACT_JSON # We don't set a charset because JSON is a binary encoding, # that can be encoded as utf-8, utf-16 or utf-32. @@ -62,9 +66,10 @@ class JSONRenderer(BaseRenderer): if accepted_media_type: # If the media type looks like 'application/json; indent=4', # then pretty print the result. + # Note that we coerce `indent=0` into `indent=None`. base_media_type, params = parse_header(accepted_media_type.encode('ascii')) try: - return max(min(int(params['indent']), 8), 0) + return zero_as_none(max(min(int(params['indent']), 8), 0)) except (KeyError, ValueError, TypeError): pass @@ -81,10 +86,12 @@ class JSONRenderer(BaseRenderer): renderer_context = renderer_context or {} indent = self.get_indent(accepted_media_type, renderer_context) + separators = (',', ':') if (indent is None and self.compact) else (', ', ': ') ret = json.dumps( data, cls=self.encoder_class, - indent=indent, ensure_ascii=self.ensure_ascii + indent=indent, ensure_ascii=self.ensure_ascii, + separators=separators ) # On python 2.x json.dumps() returns bytestrings if ensure_ascii=True, @@ -96,14 +103,6 @@ class JSONRenderer(BaseRenderer): return ret -class UnicodeJSONRenderer(JSONRenderer): - ensure_ascii = False - """ - Renderer which serializes to JSON. - Does *not* apply JSON's character escaping for non-ascii characters. - """ - - class JSONPRenderer(JSONRenderer): """ Renderer which serializes to json, @@ -196,7 +195,7 @@ class YAMLRenderer(BaseRenderer): format = 'yaml' encoder = encoders.SafeDumper charset = 'utf-8' - ensure_ascii = True + ensure_ascii = False def render(self, data, accepted_media_type=None, renderer_context=None): """ @@ -210,14 +209,6 @@ class YAMLRenderer(BaseRenderer): return yaml.dump(data, stream=None, encoding=self.charset, Dumper=self.encoder, allow_unicode=not self.ensure_ascii) -class UnicodeYAMLRenderer(YAMLRenderer): - """ - Renderer which serializes to YAML. - Does *not* apply character escaping for non-ascii characters. - """ - ensure_ascii = False - - class TemplateHTMLRenderer(BaseRenderer): """ An HTML renderer for use with templates. diff --git a/rest_framework/settings.py b/rest_framework/settings.py index f48643b5d..e55610bbc 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -112,6 +112,9 @@ DEFAULTS = { ), 'TIME_FORMAT': None, + # Encoding + 'UNICODE_JSON': True, + 'COMPACT_JSON': True } diff --git a/tests/test_renderers.py b/tests/test_renderers.py index 91244e261..a8fd5f460 100644 --- a/tests/test_renderers.py +++ b/tests/test_renderers.py @@ -13,7 +13,7 @@ from rest_framework.compat import yaml, etree, StringIO from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.renderers import BaseRenderer, JSONRenderer, YAMLRenderer, \ - XMLRenderer, JSONPRenderer, BrowsableAPIRenderer, UnicodeJSONRenderer, UnicodeYAMLRenderer + XMLRenderer, JSONPRenderer, BrowsableAPIRenderer from rest_framework.parsers import YAMLParser, XMLParser from rest_framework.settings import api_settings from rest_framework.test import APIRequestFactory @@ -32,7 +32,7 @@ RENDERER_B_SERIALIZER = lambda x: ('Renderer B: %s' % x).encode('ascii') expected_results = [ - ((elem for elem in [1, 2, 3]), JSONRenderer, b'[1, 2, 3]') # Generator + ((elem for elem in [1, 2, 3]), JSONRenderer, b'[1,2,3]') # Generator ] @@ -270,7 +270,7 @@ class RendererEndToEndTests(TestCase): self.assertNotContains(resp, '>text/html; charset=utf-8<') -_flat_repr = '{"foo": ["bar", "baz"]}' +_flat_repr = '{"foo":["bar","baz"]}' _indented_repr = '{\n "foo": [\n "bar",\n "baz"\n ]\n}' @@ -373,12 +373,6 @@ class JSONRendererTests(TestCase): content = renderer.render(obj, 'application/json; indent=2') self.assertEqual(strip_trailing_whitespace(content.decode('utf-8')), _indented_repr) - def test_check_ascii(self): - obj = {'countries': ['United Kingdom', 'France', 'España']} - renderer = JSONRenderer() - content = renderer.render(obj, 'application/json') - self.assertEqual(content, '{"countries": ["United Kingdom", "France", "Espa\\u00f1a"]}'.encode('utf-8')) - class UnicodeJSONRendererTests(TestCase): """ @@ -386,9 +380,22 @@ class UnicodeJSONRendererTests(TestCase): """ def test_proper_encoding(self): obj = {'countries': ['United Kingdom', 'France', 'España']} - renderer = UnicodeJSONRenderer() + renderer = JSONRenderer() content = renderer.render(obj, 'application/json') - self.assertEqual(content, '{"countries": ["United Kingdom", "France", "España"]}'.encode('utf-8')) + self.assertEqual(content, '{"countries":["United Kingdom","France","España"]}'.encode('utf-8')) + + +class AsciiJSONRendererTests(TestCase): + """ + Tests specific for the Unicode JSON Renderer + """ + def test_proper_encoding(self): + class AsciiJSONRenderer(JSONRenderer): + ensure_ascii = True + obj = {'countries': ['United Kingdom', 'France', 'España']} + renderer = AsciiJSONRenderer() + content = renderer.render(obj, 'application/json') + self.assertEqual(content, '{"countries":["United Kingdom","France","Espa\\u00f1a"]}'.encode('utf-8')) class JSONPRendererTests(TestCase): @@ -487,13 +494,9 @@ if yaml: def assertYAMLContains(self, content, string): self.assertTrue(string in content, '%r not in %r' % (string, content)) - class UnicodeYAMLRendererTests(TestCase): - """ - Tests specific for the Unicode YAML Renderer - """ def test_proper_encoding(self): obj = {'countries': ['United Kingdom', 'France', 'España']} - renderer = UnicodeYAMLRenderer() + renderer = YAMLRenderer() content = renderer.render(obj, 'application/yaml') self.assertEqual(content.strip(), 'countries: [United Kingdom, France, España]'.encode('utf-8')) diff --git a/tests/test_validation.py b/tests/test_validation.py index 7543d849b..ce39714d1 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -131,7 +131,7 @@ class TestMaxValueValidatorValidation(TestCase): request = factory.patch('/{0}'.format(obj.pk), {'number_value': 101}, format='json') view = UpdateMaxValueValidationModel().as_view() response = view(request, pk=obj.pk).render() - self.assertEqual(response.content, b'{"number_value": ["Ensure this value is less than or equal to 100."]}') + self.assertEqual(response.content, b'{"number_value":["Ensure this value is less than or equal to 100."]}') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) From 22af49bf8ffc73afc9b638f1b9cd2e909c6c89a8 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 11:50:20 +0100 Subject: [PATCH 038/249] Tidy up JSONEncoder --- rest_framework/utils/encoders.py | 67 ++++++++++++++++---------------- 1 file changed, 34 insertions(+), 33 deletions(-) diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py index 7992b6b1c..174b08b8b 100644 --- a/rest_framework/utils/encoders.py +++ b/rest_framework/utils/encoders.py @@ -7,7 +7,6 @@ from django.db.models.query import QuerySet from django.utils.datastructures import SortedDict from django.utils.functional import Promise from rest_framework.compat import force_text -# from rest_framework.serializers import DictWithMetadata, SortedDictWithMetadata import datetime import decimal import types @@ -17,45 +16,47 @@ import json class JSONEncoder(json.JSONEncoder): """ JSONEncoder subclass that knows how to encode date/time/timedelta, - decimal types, and generators. + decimal types, generators and other basic python objects. """ - def default(self, o): + def default(self, obj): # For Date Time string spec, see ECMA 262 # http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 - if isinstance(o, Promise): - return force_text(o) - elif isinstance(o, datetime.datetime): - r = o.isoformat() - if o.microsecond: - r = r[:23] + r[26:] - if r.endswith('+00:00'): - r = r[:-6] + 'Z' - return r - elif isinstance(o, datetime.date): - return o.isoformat() - elif isinstance(o, datetime.time): - if timezone and timezone.is_aware(o): + if isinstance(obj, Promise): + 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 + elif isinstance(obj, datetime.date): + return obj.isoformat() + elif isinstance(obj, datetime.time): + if timezone and timezone.is_aware(obj): raise ValueError("JSON can't represent timezone-aware times.") - r = o.isoformat() - if o.microsecond: - r = r[:12] - return r - elif isinstance(o, datetime.timedelta): - return str(o.total_seconds()) - elif isinstance(o, decimal.Decimal): - return float(o) - elif isinstance(o, QuerySet): - return list(o) - elif hasattr(o, 'tolist'): - return o.tolist() - elif hasattr(o, '__getitem__'): + representation = obj.isoformat() + if obj.microsecond: + representation = representation[:12] + return representation + elif isinstance(obj, datetime.timedelta): + return str(obj.total_seconds()) + elif isinstance(obj, decimal.Decimal): + # Serializers will coerce decimals to strings by default. + return float(obj) + elif isinstance(obj, QuerySet): + return list(obj) + elif hasattr(obj, 'tolist'): + # Numpy arrays and array scalars. + return obj.tolist() + elif hasattr(obj, '__getitem__'): try: - return dict(o) + return dict(obj) except: pass - elif hasattr(o, '__iter__'): - return [i for i in o] - return super(JSONEncoder, self).default(o) + elif hasattr(obj, '__iter__'): + return [item for item in obj] + return super(JSONEncoder, self).default(obj) try: From 79715f01f8c34fdd55c2291b6b21d09fa3a8153e Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 12:10:22 +0100 Subject: [PATCH 039/249] Coerce dates etc to ISO_8601 in seralizer, by default. --- rest_framework/fields.py | 24 +++++++++++++----------- rest_framework/settings.py | 21 ++++++++------------- tests/test_filters.py | 17 +++++++++-------- tests/test_pagination.py | 2 +- 4 files changed, 31 insertions(+), 33 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 9d96cf5cc..e1855ff74 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -431,10 +431,12 @@ class DecimalField(Field): 'max_whole_digits': _('Ensure that there are no more than {max_whole_digits} digits before the decimal point.') } - def __init__(self, max_digits, decimal_places, coerce_to_string=True, max_value=None, min_value=None, **kwargs): + coerce_to_string = api_settings.COERCE_DECIMAL_TO_STRING + + def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None, **kwargs): self.max_digits = max_digits self.decimal_places = decimal_places - self.coerce_to_string = coerce_to_string + self.coerce_to_string = coerce_to_string if (coerce_to_string is not None) else self.coerce_to_string super(DecimalField, self).__init__(**kwargs) if max_value is not None: self.validators.append(validators.MaxValueValidator(max_value)) @@ -510,12 +512,12 @@ class DateField(Field): default_error_messages = { 'invalid': _('Date has wrong format. Use one of these formats instead: {format}'), } - input_formats = api_settings.DATE_INPUT_FORMATS format = api_settings.DATE_FORMAT + input_formats = api_settings.DATE_INPUT_FORMATS - def __init__(self, input_formats=None, format=None, *args, **kwargs): - self.input_formats = input_formats if input_formats is not None else self.input_formats + def __init__(self, format=None, input_formats=None, *args, **kwargs): self.format = format if format is not None else self.format + self.input_formats = input_formats if input_formats is not None else self.input_formats super(DateField, self).__init__(*args, **kwargs) def to_internal_value(self, value): @@ -569,12 +571,12 @@ class DateTimeField(Field): default_error_messages = { 'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}'), } - input_formats = api_settings.DATETIME_INPUT_FORMATS format = api_settings.DATETIME_FORMAT + input_formats = api_settings.DATETIME_INPUT_FORMATS - def __init__(self, input_formats=None, format=None, *args, **kwargs): - self.input_formats = input_formats if input_formats is not None else self.input_formats + def __init__(self, format=None, input_formats=None, *args, **kwargs): self.format = format if format is not None else self.format + self.input_formats = input_formats if input_formats is not None else self.input_formats super(DateTimeField, self).__init__(*args, **kwargs) def to_internal_value(self, value): @@ -634,12 +636,12 @@ class TimeField(Field): default_error_messages = { 'invalid': _('Time has wrong format. Use one of these formats instead: {format}'), } - input_formats = api_settings.TIME_INPUT_FORMATS format = api_settings.TIME_FORMAT + input_formats = api_settings.TIME_INPUT_FORMATS - def __init__(self, input_formats=None, format=None, *args, **kwargs): - self.input_formats = input_formats if input_formats is not None else self.input_formats + def __init__(self, format=None, input_formats=None, *args, **kwargs): self.format = format if format is not None else self.format + self.input_formats = input_formats if input_formats is not None else self.input_formats super(TimeField, self).__init__(*args, **kwargs) def from_native(self, value): diff --git a/rest_framework/settings.py b/rest_framework/settings.py index e55610bbc..421e146c8 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -97,24 +97,19 @@ DEFAULTS = { 'URL_FIELD_NAME': 'url', # Input and output formats - 'DATE_INPUT_FORMATS': ( - ISO_8601, - ), - 'DATE_FORMAT': None, + 'DATE_FORMAT': ISO_8601, + 'DATE_INPUT_FORMATS': (ISO_8601,), - 'DATETIME_INPUT_FORMATS': ( - ISO_8601, - ), - 'DATETIME_FORMAT': None, + 'DATETIME_FORMAT': ISO_8601, + 'DATETIME_INPUT_FORMATS': (ISO_8601,), - 'TIME_INPUT_FORMATS': ( - ISO_8601, - ), - 'TIME_FORMAT': None, + 'TIME_FORMAT': ISO_8601, + 'TIME_INPUT_FORMATS': (ISO_8601,), # Encoding 'UNICODE_JSON': True, - 'COMPACT_JSON': True + 'COMPACT_JSON': True, + 'COERCE_DECIMAL_TO_STRING': True } diff --git a/tests/test_filters.py b/tests/test_filters.py index 01668114b..dc84dcbd0 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -2,10 +2,11 @@ from __future__ import unicode_literals import datetime from decimal import Decimal from django.db import models +from django.conf.urls import patterns, url from django.core.urlresolvers import reverse from django.test import TestCase from django.utils import unittest -from django.conf.urls import patterns, url +from django.utils.dateparse import parse_date from rest_framework import generics, serializers, status, filters from rest_framework.compat import django_filters from rest_framework.test import APIRequestFactory @@ -102,7 +103,7 @@ if django_filters: class CommonFilteringTestCase(TestCase): def _serialize_object(self, obj): - return {'id': obj.id, 'text': obj.text, 'decimal': str(obj.decimal), 'date': obj.date} + return {'id': obj.id, 'text': obj.text, 'decimal': str(obj.decimal), 'date': obj.date.isoformat()} def setUp(self): """ @@ -153,7 +154,7 @@ class IntegrationTestFiltering(CommonFilteringTestCase): request = factory.get('/', {'date': '%s' % search_date}) # search_date str: '2012-09-22' response = view(request).render() self.assertEqual(response.status_code, status.HTTP_200_OK) - expected_data = [f for f in self.data if f['date'] == search_date] + expected_data = [f for f in self.data if parse_date(f['date']) == search_date] self.assertEqual(response.data, expected_data) @unittest.skipUnless(django_filters, 'django-filter not installed') @@ -209,7 +210,7 @@ class IntegrationTestFiltering(CommonFilteringTestCase): request = factory.get('/', {'date': '%s' % search_date}) # search_date str: '2012-10-02' response = view(request).render() self.assertEqual(response.status_code, status.HTTP_200_OK) - expected_data = [f for f in self.data if f['date'] > search_date] + expected_data = [f for f in self.data if parse_date(f['date']) > search_date] self.assertEqual(response.data, expected_data) # Tests that the text filter set with 'icontains' in the filter class works. @@ -229,7 +230,7 @@ class IntegrationTestFiltering(CommonFilteringTestCase): }) response = view(request).render() self.assertEqual(response.status_code, status.HTTP_200_OK) - expected_data = [f for f in self.data if f['date'] > search_date and + expected_data = [f for f in self.data if parse_date(f['date']) > search_date and Decimal(f['decimal']) < search_decimal] self.assertEqual(response.data, expected_data) @@ -481,9 +482,9 @@ class DjangoFilterOrderingTests(TestCase): self.assertEqual( response.data, [ - {'id': 3, 'date': datetime.date(2014, 10, 8), 'text': 'cde'}, - {'id': 2, 'date': datetime.date(2013, 10, 8), 'text': 'bcd'}, - {'id': 1, 'date': datetime.date(2012, 10, 8), 'text': 'abc'} + {'id': 3, 'date': '2014-10-08', 'text': 'cde'}, + {'id': 2, 'date': '2013-10-08', 'text': 'bcd'}, + {'id': 1, 'date': '2012-10-08', 'text': 'abc'} ] ) diff --git a/tests/test_pagination.py b/tests/test_pagination.py index a7f8e691f..1fd9cf9c4 100644 --- a/tests/test_pagination.py +++ b/tests/test_pagination.py @@ -135,7 +135,7 @@ class IntegrationTestPaginationAndFiltering(TestCase): self.objects = FilterableItem.objects self.data = [ - {'id': obj.id, 'text': obj.text, 'decimal': str(obj.decimal), 'date': obj.date} + {'id': obj.id, 'text': obj.text, 'decimal': str(obj.decimal), 'date': obj.date.isoformat()} for obj in self.objects.all() ] From f95e7fae38968f58e742b93842bda9110a61b9f7 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 12:40:53 +0100 Subject: [PATCH 040/249] Updating docs --- docs/api-guide/renderers.md | 29 ++++------------------ docs/api-guide/settings.md | 48 ++++++++++++++++++++++++++++++++++--- 2 files changed, 50 insertions(+), 27 deletions(-) diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 7a3429bfd..b1adf31f8 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -74,37 +74,18 @@ If your API includes views that can serve both regular webpages and API response Renders the request data into `JSON`, using utf-8 encoding. -Note that non-ascii characters will be rendered using JSON's `\uXXXX` character escape. For example: +Note that the default style is to include unicode characters, and render the response using a compact style with no uneccessary whitespace: - {"unicode black star": "\u2605"} + {"unicode black star":"★","value":999} The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`. { - "unicode black star": "\u2605" + "unicode black star": "★", + "value": 999 } -**.media_type**: `application/json` - -**.format**: `'.json'` - -**.charset**: `None` - -## UnicodeJSONRenderer - -Renders the request data into `JSON`, using utf-8 encoding. - -Note that non-ascii characters will not be character escaped. For example: - - {"unicode black star": "★"} - -The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`. - - { - "unicode black star": "★" - } - -Both the `JSONRenderer` and `UnicodeJSONRenderer` styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. +The default JSON encoding style can be altered using the `UNICODE_JSON` and `COMPACT_JSON` settings keys. **.media_type**: `application/json` diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 27a091633..6a855c929 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -265,7 +265,7 @@ A format string that should be used by default for rendering the output of `Date May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string. -Default: `None` +Default: `'iso-8601'` #### DATETIME_INPUT_FORMATS @@ -281,7 +281,7 @@ A format string that should be used by default for rendering the output of `Date May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string. -Default: `None` +Default: `'iso-8601'` #### DATE_INPUT_FORMATS @@ -297,7 +297,7 @@ A format string that should be used by default for rendering the output of `Time May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string. -Default: `None` +Default: `'iso-8601'` #### TIME_INPUT_FORMATS @@ -309,6 +309,46 @@ Default: `['iso-8601']` --- +## Encodings + +#### UNICODE_JSON + +When set to `True`, JSON responses will allow unicode characters in responses. For example: + + {"unicode black star":"★"} + +When set to `False`, JSON responses will escape non-ascii characters, like so: + + {"unicode black star":"\u2605"} + +Both styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. The unicode style is prefered as being more user-friendly when inspecting API responses. + +Default: `True` + +#### COMPACT_JSON + +When set to `True`, JSON responses will return compact representations, with no spacing after `':'` and `','` characters. For example: + + {"is_admin":false,"email":"jane@example"} + +When set to `False`, JSON responses will return slightly more verbose representations, like so: + + {"is_admin": false, "email": "jane@example"} + +The default style is to return minified responses, in line with [Heroku's API design guidelines][heroku-minified-json]. + +Default: `True` + +#### COERCE_DECIMAL_TO_STRING + +When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations. + +When set to `True`, the serializer `DecimalField` class will return strings instead of `Decimal` objects. When set to `False`, serializers will return `Decimal` objects, which the default JSON encoder will return as floats. + +Default: `True` + +--- + ## View names and descriptions **The following settings are used to generate the view names and descriptions, as used in responses to `OPTIONS` requests, and as used in the browsable API.** @@ -378,4 +418,6 @@ An integer of 0 or more, that may be used to specify the number of application p Default: `None` [cite]: http://www.python.org/dev/peps/pep-0020/ +[rfc4627]: http://www.ietf.org/rfc/rfc4627.txt +[heroku-minified-json]: https://github.com/interagent/http-api-design#keep-json-minified-in-all-responses [strftime]: http://docs.python.org/2/library/time.html#time.strftime From b73a205cc021983d9a508b447f30e144a1ce4129 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 17:03:42 +0100 Subject: [PATCH 041/249] Tests for relational fields (not including many=True) --- rest_framework/relations.py | 153 +++++++++++++++++++++++------------- tests/test_relations.py | 139 ++++++++++++++++++++++++++++++++ tests/utils.py | 53 +++++++++++++ 3 files changed, 291 insertions(+), 54 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index e23a41526..75ec89a86 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -1,19 +1,24 @@ +from rest_framework.compat import smart_text, urlparse from rest_framework.fields import Field from rest_framework.reverse import reverse -from django.core.exceptions import ObjectDoesNotExist +from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch from django.db.models.query import QuerySet -from rest_framework.compat import urlparse +from django.utils.translation import ugettext_lazy as _ class RelatedField(Field): def __init__(self, **kwargs): self.queryset = kwargs.pop('queryset', None) self.many = kwargs.pop('many', False) - assert self.queryset is not None or kwargs.get('read_only', False), ( + assert self.queryset is not None or kwargs.get('read_only', None), ( 'Relational field must provide a `queryset` argument, ' 'or set read_only=`True`.' ) + assert not (self.queryset is not None and kwargs.get('read_only', None)), ( + 'Relational fields should not provide a `queryset` argument, ' + 'when setting read_only=`True`.' + ) super(RelatedField, self).__init__(**kwargs) def get_queryset(self): @@ -25,6 +30,11 @@ class RelatedField(Field): class StringRelatedField(Field): + """ + A read only field that represents its targets using their + plain string representation. + """ + def __init__(self, **kwargs): kwargs['read_only'] = True super(StringRelatedField, self).__init__(**kwargs) @@ -34,10 +44,10 @@ class StringRelatedField(Field): class PrimaryKeyRelatedField(RelatedField): - MESSAGES = { + default_error_messages = { 'required': 'This field is required.', 'does_not_exist': "Invalid pk '{pk_value}' - object does not exist.", - 'incorrect_type': 'Incorrect type. Expected pk value, received {data_type}.', + 'incorrect_type': 'Incorrect type. Expected pk value, received {data_type}.', } def to_internal_value(self, data): @@ -48,22 +58,33 @@ class PrimaryKeyRelatedField(RelatedField): except (TypeError, ValueError): self.fail('incorrect_type', data_type=type(data).__name__) + def to_representation(self, value): + return value.pk + class HyperlinkedRelatedField(RelatedField): lookup_field = 'pk' - MESSAGES = { + default_error_messages = { 'required': 'This field is required.', 'no_match': 'Invalid hyperlink - No URL match', 'incorrect_match': 'Invalid hyperlink - Incorrect URL match.', - 'does_not_exist': "Invalid hyperlink - Object does not exist.", - 'incorrect_type': 'Incorrect type. Expected URL string, received {data_type}.', + 'does_not_exist': 'Invalid hyperlink - Object does not exist.', + 'incorrect_type': 'Incorrect type. Expected URL string, received {data_type}.', } - def __init__(self, **kwargs): - self.view_name = kwargs.pop('view_name') + def __init__(self, view_name, **kwargs): + self.view_name = view_name self.lookup_field = kwargs.pop('lookup_field', self.lookup_field) self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field) + self.format = kwargs.pop('format', None) + + # We include these simply for dependancy injection in tests. + # We can't add them as class attributes or they would expect an + # implict `self` argument to be passed. + self.reverse = reverse + self.resolve = resolve + super(HyperlinkedRelatedField, self).__init__(**kwargs) def get_object(self, view_name, view_args, view_kwargs): @@ -77,44 +98,6 @@ class HyperlinkedRelatedField(RelatedField): lookup_kwargs = {self.lookup_field: lookup_value} return self.get_queryset().get(**lookup_kwargs) - def to_internal_value(self, value): - try: - http_prefix = value.startswith(('http:', 'https:')) - except AttributeError: - self.fail('incorrect_type', data_type=type(value).__name__) - - if http_prefix: - # If needed convert absolute URLs to relative path - value = urlparse.urlparse(value).path - prefix = get_script_prefix() - if value.startswith(prefix): - value = '/' + value[len(prefix):] - - try: - match = resolve(value) - except Exception: - self.fail('no_match') - - if match.view_name != self.view_name: - self.fail('incorrect_match') - - try: - return self.get_object(match.view_name, match.args, match.kwargs) - except (ObjectDoesNotExist, TypeError, ValueError): - self.fail('does_not_exist') - - -class HyperlinkedIdentityField(RelatedField): - lookup_field = 'pk' - - def __init__(self, **kwargs): - kwargs['read_only'] = True - kwargs['source'] = '*' - self.view_name = kwargs.pop('view_name') - self.lookup_field = kwargs.pop('lookup_field', self.lookup_field) - self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field) - super(HyperlinkedIdentityField, self).__init__(**kwargs) - def get_url(self, obj, view_name, request, format): """ Given an object, return the URL that hyperlinks to the object. @@ -128,16 +111,42 @@ class HyperlinkedIdentityField(RelatedField): lookup_value = getattr(obj, self.lookup_field) kwargs = {self.lookup_url_kwarg: lookup_value} - return reverse(view_name, kwargs=kwargs, request=request, format=format) + return self.reverse(view_name, kwargs=kwargs, request=request, format=format) + + def to_internal_value(self, data): + try: + http_prefix = data.startswith(('http:', 'https:')) + except AttributeError: + self.fail('incorrect_type', data_type=type(data).__name__) + + if http_prefix: + # If needed convert absolute URLs to relative path + data = urlparse.urlparse(data).path + prefix = get_script_prefix() + if data.startswith(prefix): + data = '/' + data[len(prefix):] + + try: + match = self.resolve(data) + except Exception: + self.fail('no_match') + + if match.view_name != self.view_name: + self.fail('incorrect_match') + + try: + return self.get_object(match.view_name, match.args, match.kwargs) + except (ObjectDoesNotExist, TypeError, ValueError): + self.fail('does_not_exist') def to_representation(self, value): request = self.context.get('request', None) format = self.context.get('format', None) assert request is not None, ( - "`HyperlinkedIdentityField` requires the request in the serializer" + "`%s` requires the request in the serializer" " context. Add `context={'request': request}` when instantiating " - "the serializer." + "the serializer." % self.__class__.__name__ ) # By default use whatever format is given for the current context @@ -162,9 +171,45 @@ class HyperlinkedIdentityField(RelatedField): 'model in your API, or incorrectly configured the ' '`lookup_field` attribute on this field.' ) - raise Exception(msg % self.view_name) + raise ImproperlyConfigured(msg % self.view_name) + + +class HyperlinkedIdentityField(HyperlinkedRelatedField): + """ + A read-only field that represents the identity URL for an object, itself. + + This is in contrast to `HyperlinkedRelatedField` which represents the + URL of relationships to other objects. + """ + + def __init__(self, view_name, **kwargs): + kwargs['read_only'] = True + kwargs['source'] = '*' + super(HyperlinkedIdentityField, self).__init__(view_name, **kwargs) class SlugRelatedField(RelatedField): - def __init__(self, **kwargs): - self.slug_field = kwargs.pop('slug_field', None) + """ + A read-write field the represents the target of the relationship + by a unique 'slug' attribute. + """ + + default_error_messages = { + 'does_not_exist': _("Object with {slug_name}={value} does not exist."), + 'invalid': _('Invalid value.'), + } + + def __init__(self, slug_field, **kwargs): + self.slug_field = slug_field + super(SlugRelatedField, self).__init__(**kwargs) + + def to_internal_value(self, data): + try: + return self.get_queryset().get(**{self.slug_field: data}) + except ObjectDoesNotExist: + self.fail('does_not_exist', slug_name=self.slug_field, value=smart_text(data)) + except (TypeError, ValueError): + self.fail('invalid') + + def to_representation(self, obj): + return getattr(obj, self.slug_field) diff --git a/tests/test_relations.py b/tests/test_relations.py index b1bc66b62..a36721175 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -1,3 +1,142 @@ +from .utils import mock_reverse, fail_reverse, BadType, MockObject, MockQueryset +from django.core.exceptions import ImproperlyConfigured, ValidationError +from rest_framework import serializers +from rest_framework.test import APISimpleTestCase +import pytest + + +class TestStringRelatedField(APISimpleTestCase): + def setUp(self): + self.instance = MockObject(pk=1, name='foo') + self.field = serializers.StringRelatedField() + + def test_string_related_representation(self): + representation = self.field.to_representation(self.instance) + assert representation == '<MockObject name=foo, pk=1>' + + +class TestPrimaryKeyRelatedField(APISimpleTestCase): + def setUp(self): + self.queryset = MockQueryset([ + MockObject(pk=1, name='foo'), + MockObject(pk=2, name='bar'), + MockObject(pk=3, name='baz') + ]) + self.instance = self.queryset.items[2] + self.field = serializers.PrimaryKeyRelatedField(queryset=self.queryset) + + def test_pk_related_lookup_exists(self): + instance = self.field.to_internal_value(self.instance.pk) + assert instance is self.instance + + def test_pk_related_lookup_does_not_exist(self): + with pytest.raises(ValidationError) as excinfo: + self.field.to_internal_value(4) + msg = excinfo.value.message + assert msg == "Invalid pk '4' - object does not exist." + + def test_pk_related_lookup_invalid_type(self): + with pytest.raises(ValidationError) as excinfo: + self.field.to_internal_value(BadType()) + msg = excinfo.value.message + assert msg == 'Incorrect type. Expected pk value, received BadType.' + + def test_pk_representation(self): + representation = self.field.to_representation(self.instance) + assert representation == self.instance.pk + + +class TestHyperlinkedIdentityField(APISimpleTestCase): + def setUp(self): + self.instance = MockObject(pk=1, name='foo') + self.field = serializers.HyperlinkedIdentityField(view_name='example') + self.field.reverse = mock_reverse + self.field.context = {'request': True} + + def test_representation(self): + representation = self.field.to_representation(self.instance) + assert representation == 'http://example.org/example/1/' + + def test_representation_unsaved_object(self): + representation = self.field.to_representation(MockObject(pk=None)) + assert representation is None + + def test_representation_with_format(self): + self.field.context['format'] = 'xml' + representation = self.field.to_representation(self.instance) + assert representation == 'http://example.org/example/1.xml/' + + def test_improperly_configured(self): + """ + If a matching view cannot be reversed with the given instance, + the the user has misconfigured something, as the URL conf and the + hyperlinked field do not match. + """ + self.field.reverse = fail_reverse + with pytest.raises(ImproperlyConfigured): + self.field.to_representation(self.instance) + + +class TestHyperlinkedIdentityFieldWithFormat(APISimpleTestCase): + """ + Tests for a hyperlinked identity field that has a `format` set, + which enforces that alternate formats are never linked too. + + Eg. If your API includes some endpoints that accept both `.xml` and `.json`, + but other endpoints that only accept `.json`, we allow for hyperlinked + relationships that enforce only a single suffix type. + """ + + def setUp(self): + self.instance = MockObject(pk=1, name='foo') + self.field = serializers.HyperlinkedIdentityField(view_name='example', format='json') + self.field.reverse = mock_reverse + self.field.context = {'request': True} + + def test_representation(self): + representation = self.field.to_representation(self.instance) + assert representation == 'http://example.org/example/1/' + + def test_representation_with_format(self): + self.field.context['format'] = 'xml' + representation = self.field.to_representation(self.instance) + assert representation == 'http://example.org/example/1.json/' + + +class TestSlugRelatedField(APISimpleTestCase): + def setUp(self): + self.queryset = MockQueryset([ + MockObject(pk=1, name='foo'), + MockObject(pk=2, name='bar'), + MockObject(pk=3, name='baz') + ]) + self.instance = self.queryset.items[2] + self.field = serializers.SlugRelatedField( + slug_field='name', queryset=self.queryset + ) + + def test_slug_related_lookup_exists(self): + instance = self.field.to_internal_value(self.instance.name) + assert instance is self.instance + + def test_slug_related_lookup_does_not_exist(self): + with pytest.raises(ValidationError) as excinfo: + self.field.to_internal_value('doesnotexist') + msg = excinfo.value.message + assert msg == 'Object with name=doesnotexist does not exist.' + + def test_slug_related_lookup_invalid_type(self): + with pytest.raises(ValidationError) as excinfo: + self.field.to_internal_value(BadType()) + msg = excinfo.value.message + assert msg == 'Invalid value.' + + def test_representation(self): + representation = self.field.to_representation(self.instance) + assert representation == self.instance.name + +# Older tests, for review... + # """ # General tests for relational fields. # """ diff --git a/tests/utils.py b/tests/utils.py index 28be81bd1..5e902ba94 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -1,4 +1,6 @@ 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 @@ -23,3 +25,54 @@ def temporary_setting(setting, value, module=None): if module is not None: six.moves.reload_module(module) + + +class MockObject(object): + def __init__(self, **kwargs): + self._kwargs = kwargs + for key, val in kwargs.items(): + setattr(self, key, val) + + def __str__(self): + kwargs_str = ', '.join([ + '%s=%s' % (key, value) + for key, value in sorted(self._kwargs.items()) + ]) + return '<MockObject %s>' % kwargs_str + + +class MockQueryset(object): + def __init__(self, iterable): + self.items = iterable + + def get(self, **lookup): + for item in self.items: + if all([ + getattr(item, key, None) == value + for key, value in lookup.items() + ]): + return item + raise ObjectDoesNotExist() + + +class BadType(object): + """ + When used as a lookup with a `MockQueryset`, these objects + will raise a `TypeError`, as occurs in Django when making + queryset lookups with an incorrect type for the lookup value. + """ + def __eq__(self): + raise TypeError() + + +def mock_reverse(view_name, args=None, kwargs=None, request=None, format=None): + args = args or [] + kwargs = kwargs or {} + value = (args + list(kwargs.values()) + ['-'])[0] + prefix = 'http://example.org' if request else '' + suffix = ('.' + format) if (format is not None) else '' + return '%s/%s/%s%s/' % (prefix, view_name, value, suffix) + + +def fail_reverse(view_name, args=None, kwargs=None, request=None, format=None): + raise NoReverseMatch() From 0ac52e0808288892717c017e57c57aa8ad81e6d3 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 17:06:37 +0100 Subject: [PATCH 042/249] Use Resolver404 instead of base Exception --- rest_framework/relations.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 75ec89a86..46fe55ef9 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -2,7 +2,7 @@ from rest_framework.compat import smart_text, urlparse from rest_framework.fields import Field from rest_framework.reverse import reverse from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured -from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch +from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch, Resolver404 from django.db.models.query import QuerySet from django.utils.translation import ugettext_lazy as _ @@ -128,7 +128,7 @@ class HyperlinkedRelatedField(RelatedField): try: match = self.resolve(data) - except Exception: + except Resolver404: self.fail('no_match') if match.view_name != self.view_name: From 1f75ffc7912725e771a67bf3e6c3c6362dc3199a Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 19:50:30 +0100 Subject: [PATCH 043/249] Access validation messages in a way thats compatible with 1.4, 1.5 --- tests/test_relations.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/test_relations.py b/tests/test_relations.py index a36721175..c29618ce2 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -32,13 +32,13 @@ class TestPrimaryKeyRelatedField(APISimpleTestCase): def test_pk_related_lookup_does_not_exist(self): with pytest.raises(ValidationError) as excinfo: self.field.to_internal_value(4) - msg = excinfo.value.message + msg = excinfo.value.messages[0] assert msg == "Invalid pk '4' - object does not exist." def test_pk_related_lookup_invalid_type(self): with pytest.raises(ValidationError) as excinfo: self.field.to_internal_value(BadType()) - msg = excinfo.value.message + msg = excinfo.value.messages[0] assert msg == 'Incorrect type. Expected pk value, received BadType.' def test_pk_representation(self): @@ -122,13 +122,13 @@ class TestSlugRelatedField(APISimpleTestCase): def test_slug_related_lookup_does_not_exist(self): with pytest.raises(ValidationError) as excinfo: self.field.to_internal_value('doesnotexist') - msg = excinfo.value.message + msg = excinfo.value.messages[0] assert msg == 'Object with name=doesnotexist does not exist.' def test_slug_related_lookup_invalid_type(self): with pytest.raises(ValidationError) as excinfo: self.field.to_internal_value(BadType()) - msg = excinfo.value.message + msg = excinfo.value.messages[0] assert msg == 'Invalid value.' def test_representation(self): From e6c88a423361b084ba171af7a74a183bd557e73e Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 19:54:27 +0100 Subject: [PATCH 044/249] Drop usage of validatiors.EMPTY_VALUES --- rest_framework/fields.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index e1855ff74..33ab0682c 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -223,7 +223,7 @@ class Field(object): return value def run_validators(self, value): - if value in validators.EMPTY_VALUES: + if value in (None, '', [], (), {}): return errors = [] @@ -450,7 +450,7 @@ class DecimalField(Field): than max_digits in the number, and no more than decimal_places digits after the decimal point. """ - if value in validators.EMPTY_VALUES: + if value in (None, ''): return None value = smart_text(value).strip() @@ -521,7 +521,7 @@ class DateField(Field): super(DateField, self).__init__(*args, **kwargs) def to_internal_value(self, value): - if value in validators.EMPTY_VALUES: + if value in (None, ''): return None if isinstance(value, datetime.datetime): @@ -580,7 +580,7 @@ class DateTimeField(Field): super(DateTimeField, self).__init__(*args, **kwargs) def to_internal_value(self, value): - if value in validators.EMPTY_VALUES: + if value in (None, ''): return None if isinstance(value, datetime.datetime): @@ -645,7 +645,7 @@ class TimeField(Field): super(TimeField, self).__init__(*args, **kwargs) def from_native(self, value): - if value in validators.EMPTY_VALUES: + if value in (None, ''): return None if isinstance(value, datetime.time): From 4fceceae7d1abf4d841677daee2636273ff09de8 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 20:09:08 +0100 Subject: [PATCH 045/249] DecimalField documentation --- docs/api-guide/fields.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index bfbff2adb..f07783186 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -274,7 +274,27 @@ Corresponds to `django.db.models.fields.FloatField`. ## DecimalField -A decimal representation. +A decimal representation, represented in Python by a Decimal instance. + +Has two required arguments: + +- `max_digits` The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places. + +- `decimal_places` The number of decimal places to store with the number. + +For example, to validate numbers up to 999 with a resolution of 2 decimal places, you would use: + + serializers.DecimalField(max_digits=5, decimal_places=2) + +And to validate numbers up to anything lesss than one billion with a resolution of 10 decimal places: + + serializers.DecimalField(max_digits=19, decimal_places=10) + +This field also takes an optional argument, `coerce_to_string`. If set to `True` the representation will be output as a string. If set to `False` the representation will be left as a `Decimal` instance and the final representation will be determined by the renderer. + +If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise. + +**Signature:** `DecimalField(max_digits, decimal_places, coerce_to_string=None)` Corresponds to `django.db.models.fields.DecimalField`. From afb28a44ad1737cd6fcd6da50ba9552f38293368 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 12 Sep 2014 21:32:20 +0100 Subject: [PATCH 046/249] Dealing with reverse relationships --- rest_framework/serializers.py | 8 ++++---- tests/test_model_field_mappings.py | 27 ++++++++++++++++++++++++--- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 0c2aedfa0..ecb2829b6 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -157,7 +157,7 @@ class Serializer(BaseSerializer): def __init__(self, *args, **kwargs): self.context = kwargs.pop('context', {}) kwargs.pop('partial', None) - kwargs.pop('many', False) + kwargs.pop('many', None) super(Serializer, self).__init__(*args, **kwargs) @@ -423,9 +423,9 @@ class ModelSerializer(Serializer): for accessor_name, relation_info in info.reverse_relations.items(): if accessor_name in self.opts.fields: if self.opts.depth: - ret[field_name] = self.get_nested_field(*relation_info) + ret[accessor_name] = self.get_nested_field(*relation_info) else: - ret[field_name] = self.get_related_field(*relation_info) + ret[accessor_name] = self.get_related_field(*relation_info) return ret @@ -444,7 +444,7 @@ class ModelSerializer(Serializer): Note that model_field will be `None` for reverse relationships. """ - class NestedModelSerializer(ModelSerializer): + class NestedModelSerializer(ModelSerializer): # Not right! class Meta: model = related_model depth = self.opts.depth - 1 diff --git a/tests/test_model_field_mappings.py b/tests/test_model_field_mappings.py index 6e9aaba6c..d5750f9e3 100644 --- a/tests/test_model_field_mappings.py +++ b/tests/test_model_field_mappings.py @@ -73,9 +73,9 @@ class OneToOneTargetModel(models.Model): class RelationalModel(models.Model): - foreign_key = models.ForeignKey(ForeignKeyTargetModel) - many_to_many = models.ManyToManyField(ManyToManyTargetModel) - one_to_one = models.OneToOneField(OneToOneTargetModel) + foreign_key = models.ForeignKey(ForeignKeyTargetModel, related_name='reverse_foreign_key') + many_to_many = models.ManyToManyField(ManyToManyTargetModel, related_name='reverse_many_to_many') + one_to_one = models.OneToOneField(OneToOneTargetModel, related_name='reverse_one_to_one') RELATIONAL_FLAT_REPR = """ @@ -160,3 +160,24 @@ class TestSerializerMappings(TestCase): model = RelationalModel depth = 1 self.assertEqual(repr(TestSerializer()), HYPERLINKED_NESTED_REPR) + + # def test_flat_reverse_foreign_key(self): + # class TestSerializer(serializers.ModelSerializer): + # class Meta: + # model = ForeignKeyTargetModel + # fields = ('id', 'name', 'reverse_foreign_key') + # print repr(TestSerializer()) + + # def test_flat_reverse_one_to_one(self): + # class TestSerializer(serializers.ModelSerializer): + # class Meta: + # model = OneToOneTargetModel + # fields = ('id', 'name', 'reverse_one_to_one') + # print repr(TestSerializer()) + + # def test_flat_reverse_many_to_many(self): + # class TestSerializer(serializers.ModelSerializer): + # class Meta: + # model = ManyToManyTargetModel + # fields = ('id', 'name', 'reverse_many_to_many') + # print repr(TestSerializer()) \ No newline at end of file From 40dc588a372375608701f7e521dea6d860a49eb2 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 15 Sep 2014 09:50:51 +0100 Subject: [PATCH 047/249] Drop label from serializer fields when not needed --- rest_framework/fields.py | 6 +- rest_framework/serializers.py | 56 +++++++++------- .../utils/{modelinfo.py => model_meta.py} | 0 tests/test_model_field_mappings.py | 64 +++++++++---------- 4 files changed, 70 insertions(+), 56 deletions(-) rename rest_framework/utils/{modelinfo.py => model_meta.py} (100%) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 33ab0682c..1818e705e 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -80,6 +80,10 @@ def set_value(dictionary, keys, value): dictionary[keys[-1]] = value +def field_name_to_label(field_name): + return field_name.replace('_', ' ').capitalize() + + class SkipField(Exception): pass @@ -158,7 +162,7 @@ class Field(object): # `self.label` should deafult to being based on the field name. if self.label is None: - self.label = self.field_name.replace('_', ' ').capitalize() + self.label = field_name_to_label(self.field_name) # self.source should default to being the same as the field name. if self.source is None: diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index ecb2829b6..ba8d475f8 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -15,11 +15,12 @@ from django.core.exceptions import ValidationError from django.db import models from django.utils import six from django.utils.datastructures import SortedDict +from django.utils.text import capfirst from collections import namedtuple from rest_framework.compat import clean_manytomany_helptext from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.settings import api_settings -from rest_framework.utils import html, modelinfo, representation +from rest_framework.utils import html, model_meta, representation import copy # Note: We do the following so that users of the framework can use this style: @@ -334,6 +335,14 @@ def lookup_class(mapping, instance): raise KeyError('Class %s not found in lookup.', cls.__name__) +def needs_label(model_field, field_name): + """ + Returns `True` if the label based on the model's verbose name + is not equal to the default label it would have based on it's field name. + """ + return capfirst(model_field.verbose_name) != field_name_to_label(field_name) + + class ModelSerializer(Serializer): field_mapping = { models.AutoField: IntegerField, @@ -397,54 +406,55 @@ class ModelSerializer(Serializer): """ Return all the fields that should be serialized for the model. """ - info = modelinfo.get_field_info(self.opts.model) + info = model_meta.get_field_info(self.opts.model) ret = SortedDict() serializer_url_field = self.get_url_field() if serializer_url_field: ret[api_settings.URL_FIELD_NAME] = serializer_url_field - serializer_pk_field = self.get_pk_field(info.pk) + field_name = info.pk.name + serializer_pk_field = self.get_pk_field(field_name, info.pk) if serializer_pk_field: - ret[info.pk.name] = serializer_pk_field + ret[field_name] = serializer_pk_field # Regular fields for field_name, field in info.fields.items(): - ret[field_name] = self.get_field(field) + ret[field_name] = self.get_field(field_name, field) # Forward relations for field_name, relation_info in info.forward_relations.items(): if self.opts.depth: - ret[field_name] = self.get_nested_field(*relation_info) + ret[field_name] = self.get_nested_field(field_name, *relation_info) else: - ret[field_name] = self.get_related_field(*relation_info) + ret[field_name] = self.get_related_field(field_name, *relation_info) # Reverse relations for accessor_name, relation_info in info.reverse_relations.items(): if accessor_name in self.opts.fields: if self.opts.depth: - ret[accessor_name] = self.get_nested_field(*relation_info) + ret[accessor_name] = self.get_nested_field(accessor_name, *relation_info) else: - ret[accessor_name] = self.get_related_field(*relation_info) + ret[accessor_name] = self.get_related_field(accessor_name, *relation_info) return ret def get_url_field(self): return None - def get_pk_field(self, model_field): + def get_pk_field(self, field_name, model_field): """ Returns a default instance of the pk field. """ - return self.get_field(model_field) + return self.get_field(field_name, model_field) - def get_nested_field(self, model_field, related_model, to_many, has_through_model): + def get_nested_field(self, field_name, model_field, related_model, to_many, has_through_model): """ Creates a default instance of a nested relational field. Note that model_field will be `None` for reverse relationships. """ - class NestedModelSerializer(ModelSerializer): # Not right! + class NestedModelSerializer(ModelSerializer): class Meta: model = related_model depth = self.opts.depth - 1 @@ -454,7 +464,7 @@ class ModelSerializer(Serializer): kwargs['many'] = True return NestedModelSerializer(**kwargs) - def get_related_field(self, model_field, related_model, to_many, has_through_model): + def get_related_field(self, field_name, model_field, related_model, to_many, has_through_model): """ Creates a default instance of a flat relational field. @@ -474,8 +484,8 @@ class ModelSerializer(Serializer): if model_field: if model_field.null or model_field.blank: kwargs['required'] = False - if model_field.verbose_name: - kwargs['label'] = model_field.verbose_name + if model_field.verbose_name and needs_label(model_field, field_name): + kwargs['label'] = capfirst(model_field.verbose_name) if not model_field.editable: kwargs['read_only'] = True kwargs.pop('queryset', None) @@ -485,7 +495,7 @@ class ModelSerializer(Serializer): return PrimaryKeyRelatedField(**kwargs) - def get_field(self, model_field): + def get_field(self, field_name, model_field): """ Creates a default instance of a basic non-relational field. """ @@ -496,8 +506,8 @@ class ModelSerializer(Serializer): if model_field.null or model_field.blank: kwargs['required'] = False - if model_field.verbose_name is not None: - kwargs['label'] = model_field.verbose_name + if model_field.verbose_name and needs_label(model_field, field_name): + kwargs['label'] = capfirst(model_field.verbose_name) if model_field.help_text: kwargs['help_text'] = model_field.help_text @@ -642,11 +652,11 @@ class HyperlinkedModelSerializer(ModelSerializer): return HyperlinkedIdentityField(**kwargs) - def get_pk_field(self, model_field): + def get_pk_field(self, field_name, model_field): if self.opts.fields and model_field.name in self.opts.fields: return self.get_field(model_field) - def get_related_field(self, model_field, related_model, to_many, has_through_model): + def get_related_field(self, field_name, model_field, related_model, to_many, has_through_model): """ Creates a default instance of a flat relational field. """ @@ -665,8 +675,8 @@ class HyperlinkedModelSerializer(ModelSerializer): if model_field: if model_field.null or model_field.blank: kwargs['required'] = False - if model_field.verbose_name: - kwargs['label'] = model_field.verbose_name + if model_field.verbose_name and needs_label(model_field, field_name): + kwargs['label'] = capfirst(model_field.verbose_name) if not model_field.editable: kwargs['read_only'] = True kwargs.pop('queryset', None) diff --git a/rest_framework/utils/modelinfo.py b/rest_framework/utils/model_meta.py similarity index 100% rename from rest_framework/utils/modelinfo.py rename to rest_framework/utils/model_meta.py diff --git a/tests/test_model_field_mappings.py b/tests/test_model_field_mappings.py index d5750f9e3..b04ad5f2f 100644 --- a/tests/test_model_field_mappings.py +++ b/tests/test_model_field_mappings.py @@ -36,25 +36,25 @@ class RegularFieldsModel(models.Model): REGULAR_FIELDS_REPR = """ TestSerializer(): - auto_field = IntegerField(label='auto field', read_only=True) - big_integer_field = IntegerField(label='big integer field') - boolean_field = BooleanField(default=False, label='boolean field') - char_field = CharField(label='char field', max_length=100) - comma_seperated_integer_field = CharField(label='comma seperated integer field', max_length=100, validators=[<django.core.validators.RegexValidator object>]) - date_field = DateField(label='date field') - datetime_field = DateTimeField(label='datetime field') - decimal_field = DecimalField(decimal_places=1, label='decimal field', max_digits=3) - email_field = EmailField(label='email field', max_length=100) - float_field = FloatField(label='float field') - integer_field = IntegerField(label='integer field') - null_boolean_field = BooleanField(label='null boolean field', required=False) - positive_integer_field = IntegerField(label='positive integer field') - positive_small_integer_field = IntegerField(label='positive small integer field') - slug_field = SlugField(label='slug field', max_length=100) - small_integer_field = IntegerField(label='small integer field') - text_field = CharField(label='text field') - time_field = TimeField(label='time field') - url_field = URLField(label='url field', max_length=100) + auto_field = IntegerField(read_only=True) + big_integer_field = IntegerField() + boolean_field = BooleanField(default=False) + char_field = CharField(max_length=100) + comma_seperated_integer_field = CharField(max_length=100, validators=[<django.core.validators.RegexValidator object>]) + date_field = DateField() + datetime_field = DateTimeField() + decimal_field = DecimalField(decimal_places=1, max_digits=3) + email_field = EmailField(max_length=100) + float_field = FloatField() + integer_field = IntegerField() + null_boolean_field = BooleanField(required=False) + positive_integer_field = IntegerField() + positive_small_integer_field = IntegerField() + slug_field = SlugField(max_length=100) + small_integer_field = IntegerField() + text_field = CharField() + time_field = TimeField() + url_field = URLField(max_length=100) """.strip() @@ -81,9 +81,9 @@ class RelationalModel(models.Model): RELATIONAL_FLAT_REPR = """ TestSerializer(): id = IntegerField(label='ID', read_only=True) - foreign_key = PrimaryKeyRelatedField(label='foreign key', queryset=ForeignKeyTargetModel.objects.all()) - one_to_one = PrimaryKeyRelatedField(label='one to one', queryset=OneToOneTargetModel.objects.all()) - many_to_many = PrimaryKeyRelatedField(label='many to many', many=True, queryset=ManyToManyTargetModel.objects.all()) + foreign_key = PrimaryKeyRelatedField(queryset=ForeignKeyTargetModel.objects.all()) + one_to_one = PrimaryKeyRelatedField(queryset=OneToOneTargetModel.objects.all()) + many_to_many = PrimaryKeyRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all()) """.strip() @@ -92,22 +92,22 @@ TestSerializer(): id = IntegerField(label='ID', read_only=True) foreign_key = NestedModelSerializer(read_only=True): id = IntegerField(label='ID', read_only=True) - name = CharField(label='name', max_length=100) + name = CharField(max_length=100) one_to_one = NestedModelSerializer(read_only=True): id = IntegerField(label='ID', read_only=True) - name = CharField(label='name', max_length=100) + name = CharField(max_length=100) many_to_many = NestedModelSerializer(many=True, read_only=True): id = IntegerField(label='ID', read_only=True) - name = CharField(label='name', max_length=100) + name = CharField(max_length=100) """.strip() HYPERLINKED_FLAT_REPR = """ TestSerializer(): url = HyperlinkedIdentityField(view_name='relationalmodel-detail') - foreign_key = HyperlinkedRelatedField(label='foreign key', queryset=ForeignKeyTargetModel.objects.all(), view_name='foreignkeytargetmodel-detail') - one_to_one = HyperlinkedRelatedField(label='one to one', queryset=OneToOneTargetModel.objects.all(), view_name='onetoonetargetmodel-detail') - many_to_many = HyperlinkedRelatedField(label='many to many', many=True, queryset=ManyToManyTargetModel.objects.all(), view_name='manytomanytargetmodel-detail') + foreign_key = HyperlinkedRelatedField(queryset=ForeignKeyTargetModel.objects.all(), view_name='foreignkeytargetmodel-detail') + one_to_one = HyperlinkedRelatedField(queryset=OneToOneTargetModel.objects.all(), view_name='onetoonetargetmodel-detail') + many_to_many = HyperlinkedRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all(), view_name='manytomanytargetmodel-detail') """.strip() @@ -116,13 +116,13 @@ TestSerializer(): url = HyperlinkedIdentityField(view_name='relationalmodel-detail') foreign_key = NestedModelSerializer(read_only=True): id = IntegerField(label='ID', read_only=True) - name = CharField(label='name', max_length=100) + name = CharField(max_length=100) one_to_one = NestedModelSerializer(read_only=True): id = IntegerField(label='ID', read_only=True) - name = CharField(label='name', max_length=100) + name = CharField(max_length=100) many_to_many = NestedModelSerializer(many=True, read_only=True): id = IntegerField(label='ID', read_only=True) - name = CharField(label='name', max_length=100) + name = CharField(max_length=100) """.strip() @@ -180,4 +180,4 @@ class TestSerializerMappings(TestCase): # class Meta: # model = ManyToManyTargetModel # fields = ('id', 'name', 'reverse_many_to_many') - # print repr(TestSerializer()) \ No newline at end of file + # print repr(TestSerializer()) From 3cf7ed10d23300104a4613bd6cf3333fd05556ab Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 15 Sep 2014 13:10:58 +0100 Subject: [PATCH 048/249] Fix erronous import --- tests/test_modelinfo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_modelinfo.py b/tests/test_modelinfo.py index 254a33c9c..04b67f041 100644 --- a/tests/test_modelinfo.py +++ b/tests/test_modelinfo.py @@ -1,6 +1,6 @@ from django.test import TestCase from django.utils import six -from rest_framework.utils.modelinfo import _resolve_model +from rest_framework.utils.model_meta import _resolve_model from tests.models import BasicModel From c1e2a9cba6b4b69281ad47b64132bf5ac5691875 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 15 Sep 2014 13:38:28 +0100 Subject: [PATCH 049/249] Clean up field mapping tests --- tests/test_model_field_mappings.py | 166 ++++++++++++++--------------- 1 file changed, 83 insertions(+), 83 deletions(-) diff --git a/tests/test_model_field_mappings.py b/tests/test_model_field_mappings.py index b04ad5f2f..8d59e9853 100644 --- a/tests/test_model_field_mappings.py +++ b/tests/test_model_field_mappings.py @@ -10,6 +10,10 @@ from django.test import TestCase from rest_framework import serializers +def dedent(blocktext): + return '\n'.join([line[12:] for line in blocktext.splitlines()[1:-1]]) + + # Models for testing regular field mapping class RegularFieldsModel(models.Model): @@ -34,28 +38,36 @@ class RegularFieldsModel(models.Model): url_field = models.URLField(max_length=100) -REGULAR_FIELDS_REPR = """ -TestSerializer(): - auto_field = IntegerField(read_only=True) - big_integer_field = IntegerField() - boolean_field = BooleanField(default=False) - char_field = CharField(max_length=100) - comma_seperated_integer_field = CharField(max_length=100, validators=[<django.core.validators.RegexValidator object>]) - date_field = DateField() - datetime_field = DateTimeField() - decimal_field = DecimalField(decimal_places=1, max_digits=3) - email_field = EmailField(max_length=100) - float_field = FloatField() - integer_field = IntegerField() - null_boolean_field = BooleanField(required=False) - positive_integer_field = IntegerField() - positive_small_integer_field = IntegerField() - slug_field = SlugField(max_length=100) - small_integer_field = IntegerField() - text_field = CharField() - time_field = TimeField() - url_field = URLField(max_length=100) -""".strip() +class TestRegularFieldMappings(TestCase): + def test_regular_fields(self): + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = RegularFieldsModel + + expected = dedent(""" + TestSerializer(): + auto_field = IntegerField(read_only=True) + big_integer_field = IntegerField() + boolean_field = BooleanField(default=False) + char_field = CharField(max_length=100) + comma_seperated_integer_field = CharField(max_length=100, validators=[<django.core.validators.RegexValidator object>]) + date_field = DateField() + datetime_field = DateTimeField() + decimal_field = DecimalField(decimal_places=1, max_digits=3) + email_field = EmailField(max_length=100) + float_field = FloatField() + integer_field = IntegerField() + null_boolean_field = BooleanField(required=False) + positive_integer_field = IntegerField() + positive_small_integer_field = IntegerField() + slug_field = SlugField(max_length=100) + small_integer_field = IntegerField() + text_field = CharField() + time_field = TimeField() + url_field = URLField(max_length=100) + """) + + self.assertEqual(repr(TestSerializer()), expected) # Model for testing relational field mapping @@ -78,88 +90,76 @@ class RelationalModel(models.Model): one_to_one = models.OneToOneField(OneToOneTargetModel, related_name='reverse_one_to_one') -RELATIONAL_FLAT_REPR = """ -TestSerializer(): - id = IntegerField(label='ID', read_only=True) - foreign_key = PrimaryKeyRelatedField(queryset=ForeignKeyTargetModel.objects.all()) - one_to_one = PrimaryKeyRelatedField(queryset=OneToOneTargetModel.objects.all()) - many_to_many = PrimaryKeyRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all()) -""".strip() - - -RELATIONAL_NESTED_REPR = """ -TestSerializer(): - id = IntegerField(label='ID', read_only=True) - foreign_key = NestedModelSerializer(read_only=True): - id = IntegerField(label='ID', read_only=True) - name = CharField(max_length=100) - one_to_one = NestedModelSerializer(read_only=True): - id = IntegerField(label='ID', read_only=True) - name = CharField(max_length=100) - many_to_many = NestedModelSerializer(many=True, read_only=True): - id = IntegerField(label='ID', read_only=True) - name = CharField(max_length=100) -""".strip() - - -HYPERLINKED_FLAT_REPR = """ -TestSerializer(): - 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(), view_name='onetoonetargetmodel-detail') - many_to_many = HyperlinkedRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all(), view_name='manytomanytargetmodel-detail') -""".strip() - - -HYPERLINKED_NESTED_REPR = """ -TestSerializer(): - url = HyperlinkedIdentityField(view_name='relationalmodel-detail') - foreign_key = NestedModelSerializer(read_only=True): - id = IntegerField(label='ID', read_only=True) - name = CharField(max_length=100) - one_to_one = NestedModelSerializer(read_only=True): - id = IntegerField(label='ID', read_only=True) - name = CharField(max_length=100) - many_to_many = NestedModelSerializer(many=True, read_only=True): - id = IntegerField(label='ID', read_only=True) - name = CharField(max_length=100) -""".strip() - - -class TestSerializerMappings(TestCase): - maxDiff = 10000 - - def test_regular_fields(self): - class TestSerializer(serializers.ModelSerializer): - class Meta: - model = RegularFieldsModel - self.assertEqual(repr(TestSerializer()), REGULAR_FIELDS_REPR) - +class TestRelationalFieldMappings(TestCase): def test_flat_relational_fields(self): class TestSerializer(serializers.ModelSerializer): class Meta: model = RelationalModel - self.assertEqual(repr(TestSerializer()), RELATIONAL_FLAT_REPR) + + expected = dedent(""" + TestSerializer(): + id = IntegerField(label='ID', read_only=True) + foreign_key = PrimaryKeyRelatedField(queryset=ForeignKeyTargetModel.objects.all()) + one_to_one = PrimaryKeyRelatedField(queryset=OneToOneTargetModel.objects.all()) + many_to_many = PrimaryKeyRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all()) + """) + self.assertEqual(repr(TestSerializer()), expected) def test_nested_relational_fields(self): class TestSerializer(serializers.ModelSerializer): class Meta: model = RelationalModel depth = 1 - self.assertEqual(repr(TestSerializer()), RELATIONAL_NESTED_REPR) + + expected = dedent(""" + TestSerializer(): + id = IntegerField(label='ID', read_only=True) + foreign_key = NestedModelSerializer(read_only=True): + id = IntegerField(label='ID', read_only=True) + name = CharField(max_length=100) + one_to_one = NestedModelSerializer(read_only=True): + id = IntegerField(label='ID', read_only=True) + name = CharField(max_length=100) + many_to_many = NestedModelSerializer(many=True, read_only=True): + id = IntegerField(label='ID', read_only=True) + name = CharField(max_length=100) + """) + self.assertEqual(repr(TestSerializer()), expected) def test_flat_hyperlinked_fields(self): class TestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = RelationalModel - self.assertEqual(repr(TestSerializer()), HYPERLINKED_FLAT_REPR) + + expected = dedent(""" + TestSerializer(): + 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(), view_name='onetoonetargetmodel-detail') + many_to_many = HyperlinkedRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all(), view_name='manytomanytargetmodel-detail') + """) + self.assertEqual(repr(TestSerializer()), expected) def test_nested_hyperlinked_fields(self): class TestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = RelationalModel depth = 1 - self.assertEqual(repr(TestSerializer()), HYPERLINKED_NESTED_REPR) + + expected = dedent(""" + TestSerializer(): + url = HyperlinkedIdentityField(view_name='relationalmodel-detail') + foreign_key = NestedModelSerializer(read_only=True): + id = IntegerField(label='ID', read_only=True) + name = CharField(max_length=100) + one_to_one = NestedModelSerializer(read_only=True): + id = IntegerField(label='ID', read_only=True) + name = CharField(max_length=100) + many_to_many = NestedModelSerializer(many=True, read_only=True): + id = IntegerField(label='ID', read_only=True) + name = CharField(max_length=100) + """) + self.assertEqual(repr(TestSerializer()), expected) # def test_flat_reverse_foreign_key(self): # class TestSerializer(serializers.ModelSerializer): From 0c15b97b331f7937cbc5d85f660c07b3c92917a0 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 15 Sep 2014 13:48:03 +0100 Subject: [PATCH 050/249] Tests for reverse relationships --- tests/test_model_field_mappings.py | 59 ++++++++++++++++++++---------- 1 file changed, 40 insertions(+), 19 deletions(-) diff --git a/tests/test_model_field_mappings.py b/tests/test_model_field_mappings.py index 8d59e9853..a32345b31 100644 --- a/tests/test_model_field_mappings.py +++ b/tests/test_model_field_mappings.py @@ -158,26 +158,47 @@ class TestRelationalFieldMappings(TestCase): many_to_many = NestedModelSerializer(many=True, read_only=True): id = IntegerField(label='ID', read_only=True) name = CharField(max_length=100) - """) + """) self.assertEqual(repr(TestSerializer()), expected) - # def test_flat_reverse_foreign_key(self): - # class TestSerializer(serializers.ModelSerializer): - # class Meta: - # model = ForeignKeyTargetModel - # fields = ('id', 'name', 'reverse_foreign_key') - # print repr(TestSerializer()) + def test_flat_reverse_foreign_key(self): + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = ForeignKeyTargetModel + fields = ('id', 'name', 'reverse_foreign_key') - # def test_flat_reverse_one_to_one(self): - # class TestSerializer(serializers.ModelSerializer): - # class Meta: - # model = OneToOneTargetModel - # fields = ('id', 'name', 'reverse_one_to_one') - # print repr(TestSerializer()) + expected = dedent(""" + TestSerializer(): + id = IntegerField(label='ID', read_only=True) + name = CharField(max_length=100) + reverse_foreign_key = PrimaryKeyRelatedField(many=True, queryset=RelationalModel.objects.all()) + """) + self.assertEqual(repr(TestSerializer()), expected) - # def test_flat_reverse_many_to_many(self): - # class TestSerializer(serializers.ModelSerializer): - # class Meta: - # model = ManyToManyTargetModel - # fields = ('id', 'name', 'reverse_many_to_many') - # print repr(TestSerializer()) + def test_flat_reverse_one_to_one(self): + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = OneToOneTargetModel + fields = ('id', 'name', 'reverse_one_to_one') + + expected = dedent(""" + TestSerializer(): + id = IntegerField(label='ID', read_only=True) + name = CharField(max_length=100) + reverse_one_to_one = PrimaryKeyRelatedField(queryset=RelationalModel.objects.all()) + """) + self.assertEqual(repr(TestSerializer()), expected) + + def test_flat_reverse_many_to_many(self): + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = ManyToManyTargetModel + fields = ('id', 'name', 'reverse_many_to_many') + + expected = dedent(""" + TestSerializer(): + id = IntegerField(label='ID', read_only=True) + name = CharField(max_length=100) + reverse_many_to_many = PrimaryKeyRelatedField(many=True, queryset=RelationalModel.objects.all()) + """) + self.assertEqual(repr(TestSerializer()), expected) From d196608d5af912057baba79ab13d05d876368ad2 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 15 Sep 2014 13:55:09 +0100 Subject: [PATCH 051/249] Fix nested model serializer base class --- rest_framework/serializers.py | 7 ++++++- tests/test_model_field_mappings.py | 6 +++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index ba8d475f8..40d768975 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -368,6 +368,7 @@ class ModelSerializer(Serializer): models.TimeField: TimeField, models.URLField: URLField, } + nested_class = None # We fill this in at the end of this module. _options_class = ModelSerializerOptions @@ -454,7 +455,7 @@ class ModelSerializer(Serializer): Note that model_field will be `None` for reverse relationships. """ - class NestedModelSerializer(ModelSerializer): + class NestedModelSerializer(self.nested_class): class Meta: model = related_model depth = self.opts.depth - 1 @@ -694,3 +695,7 @@ class HyperlinkedModelSerializer(ModelSerializer): 'app_label': model._meta.app_label, 'model_name': model._meta.object_name.lower() } + + +ModelSerializer.nested_class = ModelSerializer +HyperlinkedModelSerializer.nested_class = HyperlinkedModelSerializer diff --git a/tests/test_model_field_mappings.py b/tests/test_model_field_mappings.py index a32345b31..d946172e4 100644 --- a/tests/test_model_field_mappings.py +++ b/tests/test_model_field_mappings.py @@ -150,13 +150,13 @@ class TestRelationalFieldMappings(TestCase): TestSerializer(): url = HyperlinkedIdentityField(view_name='relationalmodel-detail') foreign_key = NestedModelSerializer(read_only=True): - id = IntegerField(label='ID', read_only=True) + url = HyperlinkedIdentityField(view_name='foreignkeytargetmodel-detail') name = CharField(max_length=100) one_to_one = NestedModelSerializer(read_only=True): - id = IntegerField(label='ID', read_only=True) + url = HyperlinkedIdentityField(view_name='onetoonetargetmodel-detail') name = CharField(max_length=100) many_to_many = NestedModelSerializer(many=True, read_only=True): - id = IntegerField(label='ID', read_only=True) + url = HyperlinkedIdentityField(view_name='manytomanytargetmodel-detail') name = CharField(max_length=100) """) self.assertEqual(repr(TestSerializer()), expected) From 4ddc661b01410d0073d463ae729f152cabf2ef4d Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 15 Sep 2014 14:05:58 +0100 Subject: [PATCH 052/249] Tests for through relationships --- tests/test_model_field_mappings.py | 33 ++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/test_model_field_mappings.py b/tests/test_model_field_mappings.py index d946172e4..957bf6613 100644 --- a/tests/test_model_field_mappings.py +++ b/tests/test_model_field_mappings.py @@ -84,10 +84,21 @@ class OneToOneTargetModel(models.Model): name = models.CharField(max_length=100) +class ThroughTargetModel(models.Model): + name = models.CharField(max_length=100) + + +class Supplementary(models.Model): + extra = models.IntegerField() + forwards = models.ForeignKey('ThroughTargetModel') + backwards = models.ForeignKey('RelationalModel') + + class RelationalModel(models.Model): foreign_key = models.ForeignKey(ForeignKeyTargetModel, related_name='reverse_foreign_key') many_to_many = models.ManyToManyField(ManyToManyTargetModel, related_name='reverse_many_to_many') one_to_one = models.OneToOneField(OneToOneTargetModel, related_name='reverse_one_to_one') + through = models.ManyToManyField(ThroughTargetModel, through=Supplementary, related_name='reverse_through') class TestRelationalFieldMappings(TestCase): @@ -102,6 +113,7 @@ class TestRelationalFieldMappings(TestCase): foreign_key = PrimaryKeyRelatedField(queryset=ForeignKeyTargetModel.objects.all()) one_to_one = PrimaryKeyRelatedField(queryset=OneToOneTargetModel.objects.all()) many_to_many = PrimaryKeyRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all()) + through = PrimaryKeyRelatedField(many=True, read_only=True) """) self.assertEqual(repr(TestSerializer()), expected) @@ -123,6 +135,9 @@ class TestRelationalFieldMappings(TestCase): many_to_many = NestedModelSerializer(many=True, read_only=True): id = IntegerField(label='ID', read_only=True) name = CharField(max_length=100) + through = NestedModelSerializer(many=True, read_only=True): + id = IntegerField(label='ID', read_only=True) + name = CharField(max_length=100) """) self.assertEqual(repr(TestSerializer()), expected) @@ -137,6 +152,7 @@ class TestRelationalFieldMappings(TestCase): foreign_key = HyperlinkedRelatedField(queryset=ForeignKeyTargetModel.objects.all(), view_name='foreignkeytargetmodel-detail') one_to_one = HyperlinkedRelatedField(queryset=OneToOneTargetModel.objects.all(), view_name='onetoonetargetmodel-detail') many_to_many = HyperlinkedRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all(), view_name='manytomanytargetmodel-detail') + through = HyperlinkedRelatedField(many=True, read_only=True, view_name='throughtargetmodel-detail') """) self.assertEqual(repr(TestSerializer()), expected) @@ -158,6 +174,9 @@ class TestRelationalFieldMappings(TestCase): many_to_many = NestedModelSerializer(many=True, read_only=True): url = HyperlinkedIdentityField(view_name='manytomanytargetmodel-detail') name = CharField(max_length=100) + through = NestedModelSerializer(many=True, read_only=True): + url = HyperlinkedIdentityField(view_name='throughtargetmodel-detail') + name = CharField(max_length=100) """) self.assertEqual(repr(TestSerializer()), expected) @@ -202,3 +221,17 @@ class TestRelationalFieldMappings(TestCase): reverse_many_to_many = PrimaryKeyRelatedField(many=True, queryset=RelationalModel.objects.all()) """) self.assertEqual(repr(TestSerializer()), expected) + + def test_flat_reverse_through(self): + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = ThroughTargetModel + fields = ('id', 'name', 'reverse_through') + + expected = dedent(""" + TestSerializer(): + id = IntegerField(label='ID', read_only=True) + name = CharField(max_length=100) + reverse_through = PrimaryKeyRelatedField(many=True, read_only=True) + """) + self.assertEqual(repr(TestSerializer()), expected) From c0155fd9dc654dc5932effd46a00f66495ce700b Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 17 Sep 2014 14:11:53 +0100 Subject: [PATCH 053/249] Update comments --- rest_framework/serializers.py | 2 ++ tests/test_model_field_mappings.py | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 40d768975..1fea13802 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -410,10 +410,12 @@ class ModelSerializer(Serializer): info = model_meta.get_field_info(self.opts.model) ret = SortedDict() + # URL field serializer_url_field = self.get_url_field() if serializer_url_field: ret[api_settings.URL_FIELD_NAME] = serializer_url_field + # Primary key field field_name = info.pk.name serializer_pk_field = self.get_pk_field(field_name, info.pk) if serializer_pk_field: diff --git a/tests/test_model_field_mappings.py b/tests/test_model_field_mappings.py index 957bf6613..bae63e5a7 100644 --- a/tests/test_model_field_mappings.py +++ b/tests/test_model_field_mappings.py @@ -14,7 +14,7 @@ def dedent(blocktext): return '\n'.join([line[12:] for line in blocktext.splitlines()[1:-1]]) -# Models for testing regular field mapping +# Testing regular field mappings class RegularFieldsModel(models.Model): auto_field = models.AutoField(primary_key=True) @@ -70,7 +70,7 @@ class TestRegularFieldMappings(TestCase): self.assertEqual(repr(TestSerializer()), expected) -# Model for testing relational field mapping +# Testing relational field mappings class ForeignKeyTargetModel(models.Model): name = models.CharField(max_length=100) From 5b7e4af0d657a575cb15eea85a63a7100c636085 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 18 Sep 2014 11:20:56 +0100 Subject: [PATCH 054/249] get_base_field() refactor --- rest_framework/fields.py | 6 +- rest_framework/relations.py | 9 +- rest_framework/serializers.py | 454 ++++++-------------------- rest_framework/utils/field_mapping.py | 215 ++++++++++++ rest_framework/utils/model_meta.py | 46 ++- tests/models.py | 7 - tests/test_model_field_mappings.py | 16 +- tests/test_response.py | 9 +- tests/test_routers.py | 7 +- 9 files changed, 379 insertions(+), 390 deletions(-) create mode 100644 rest_framework/utils/field_mapping.py diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 1818e705e..0c78b3fbb 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -80,10 +80,6 @@ def set_value(dictionary, keys, value): dictionary[keys[-1]] = value -def field_name_to_label(field_name): - return field_name.replace('_', ' ').capitalize() - - class SkipField(Exception): pass @@ -162,7 +158,7 @@ class Field(object): # `self.label` should deafult to being based on the field name. if self.label is None: - self.label = field_name_to_label(self.field_name) + self.label = field_name.replace('_', ' ').capitalize() # self.source should default to being the same as the field name. if self.source is None: diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 46fe55ef9..9f44ab633 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -73,7 +73,8 @@ class HyperlinkedRelatedField(RelatedField): 'incorrect_type': 'Incorrect type. Expected URL string, received {data_type}.', } - def __init__(self, view_name, **kwargs): + def __init__(self, view_name=None, **kwargs): + assert view_name is not None, 'The `view_name` argument is required.' self.view_name = view_name self.lookup_field = kwargs.pop('lookup_field', self.lookup_field) self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field) @@ -182,7 +183,8 @@ class HyperlinkedIdentityField(HyperlinkedRelatedField): URL of relationships to other objects. """ - def __init__(self, view_name, **kwargs): + def __init__(self, view_name=None, **kwargs): + assert view_name is not None, 'The `view_name` argument is required.' kwargs['read_only'] = True kwargs['source'] = '*' super(HyperlinkedIdentityField, self).__init__(view_name, **kwargs) @@ -199,7 +201,8 @@ class SlugRelatedField(RelatedField): 'invalid': _('Invalid value.'), } - def __init__(self, slug_field, **kwargs): + def __init__(self, slug_field=None, **kwargs): + assert slug_field is not None, 'The `slug_field` argument is required.' self.slug_field = slug_field super(SlugRelatedField, self).__init__(**kwargs) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 1fea13802..99dcc349f 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -10,17 +10,19 @@ python primitives. 2. The process of marshalling between python primitives and request and response content is handled by parsers and renderers. """ -from django.core import validators from django.core.exceptions import ValidationError from django.db import models from django.utils import six from django.utils.datastructures import SortedDict -from django.utils.text import capfirst from collections import namedtuple -from rest_framework.compat import clean_manytomany_helptext from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.settings import api_settings from rest_framework.utils import html, model_meta, representation +from rest_framework.utils.field_mapping import ( + get_url_kwargs, get_field_kwargs, + get_relation_kwargs, get_nested_relation_kwargs, + lookup_class +) import copy # Note: We do the following so that users of the framework can use this style: @@ -126,7 +128,7 @@ class SerializerMetaclass(type): """ @classmethod - def _get_fields(cls, bases, attrs): + def _get_declared_fields(cls, bases, attrs): fields = [(field_name, attrs.pop(field_name)) for field_name, obj in list(attrs.items()) if isinstance(obj, Field)] @@ -136,25 +138,18 @@ class SerializerMetaclass(type): # fields. Note that we loop over the bases in *reverse*. This is necessary # in order to maintain the correct order of fields. for base in bases[::-1]: - if hasattr(base, 'base_fields'): - fields = list(base.base_fields.items()) + fields + if hasattr(base, '_declared_fields'): + fields = list(base._declared_fields.items()) + fields return SortedDict(fields) def __new__(cls, name, bases, attrs): - attrs['base_fields'] = cls._get_fields(bases, attrs) + attrs['_declared_fields'] = cls._get_declared_fields(bases, attrs) return super(SerializerMetaclass, cls).__new__(cls, name, bases, attrs) @six.add_metaclass(SerializerMetaclass) class Serializer(BaseSerializer): - - def __new__(cls, *args, **kwargs): - if kwargs.pop('many', False): - kwargs['child'] = cls() - return ListSerializer(*args, **kwargs) - return super(Serializer, cls).__new__(cls, *args, **kwargs) - def __init__(self, *args, **kwargs): self.context = kwargs.pop('context', {}) kwargs.pop('partial', None) @@ -165,14 +160,22 @@ class Serializer(BaseSerializer): # Every new serializer is created with a clone of the field instances. # This allows users to dynamically modify the fields on a serializer # instance without affecting every other serializer class. - self.fields = self.get_fields() + self.fields = self._get_base_fields() # Setup all the child fields, to provide them with the current context. for field_name, field in self.fields.items(): field.bind(field_name, self, self) - def get_fields(self): - return copy.deepcopy(self.base_fields) + def __new__(cls, *args, **kwargs): + # We override this method in order to automagically create + # `ListSerializer` classes instead when `many=True` is set. + if kwargs.pop('many', False): + kwargs['child'] = cls() + return ListSerializer(*args, **kwargs) + return super(Serializer, cls).__new__(cls, *args, **kwargs) + + def _get_base_fields(self): + return copy.deepcopy(self._declared_fields) def bind(self, field_name, parent, root): # If the serializer is used as a field then when it becomes bound @@ -312,39 +315,8 @@ class ListSerializer(BaseSerializer): return representation.list_repr(self, indent=1) -class ModelSerializerOptions(object): - """ - Meta class options for ModelSerializer - """ - def __init__(self, meta): - self.model = getattr(meta, 'model') - self.fields = getattr(meta, 'fields', ()) - self.depth = getattr(meta, 'depth', 0) - - -def lookup_class(mapping, instance): - """ - Takes a dictionary with classes as keys, and an object. - Traverses the object's inheritance hierarchy in method - resolution order, and returns the first matching value - from the dictionary or raises a KeyError if nothing matches. - """ - for cls in inspect.getmro(instance.__class__): - if cls in mapping: - return mapping[cls] - raise KeyError('Class %s not found in lookup.', cls.__name__) - - -def needs_label(model_field, field_name): - """ - Returns `True` if the label based on the model's verbose name - is not equal to the default label it would have based on it's field name. - """ - return capfirst(model_field.verbose_name) != field_name_to_label(field_name) - - class ModelSerializer(Serializer): - field_mapping = { + _field_mapping = { models.AutoField: IntegerField, models.BigIntegerField: IntegerField, models.BooleanField: BooleanField, @@ -368,16 +340,10 @@ class ModelSerializer(Serializer): models.TimeField: TimeField, models.URLField: URLField, } - nested_class = None # We fill this in at the end of this module. - - _options_class = ModelSerializerOptions - - def __init__(self, *args, **kwargs): - self.opts = self._options_class(self.Meta) - super(ModelSerializer, self).__init__(*args, **kwargs) + _related_class = PrimaryKeyRelatedField def create(self, attrs): - ModelClass = self.opts.model + ModelClass = self.Meta.model return ModelClass.objects.create(**attrs) def update(self, obj, attrs): @@ -385,319 +351,97 @@ class ModelSerializer(Serializer): setattr(obj, attr, value) obj.save() - def get_fields(self): - # Get the explicitly declared fields. - fields = copy.deepcopy(self.base_fields) + def _get_base_fields(self): + declared_fields = copy.deepcopy(self._declared_fields) - # Add in the default fields. - for key, val in self.get_default_fields().items(): - if key not in fields: - fields[key] = val - - # If `fields` is set on the `Meta` class, - # then use only those fields, and in that order. - if self.opts.fields: - fields = SortedDict([ - (key, fields[key]) for key in self.opts.fields - ]) - - return fields - - def get_default_fields(self): - """ - Return all the fields that should be serialized for the model. - """ - info = model_meta.get_field_info(self.opts.model) ret = SortedDict() + model = getattr(self.Meta, 'model') + fields = getattr(self.Meta, 'fields', None) + depth = getattr(self.Meta, 'depth', 0) - # URL field - serializer_url_field = self.get_url_field() - if serializer_url_field: - ret[api_settings.URL_FIELD_NAME] = serializer_url_field + # Retrieve metadata about fields & relationships on the model class. + info = model_meta.get_field_info(model) - # Primary key field - field_name = info.pk.name - serializer_pk_field = self.get_pk_field(field_name, info.pk) - if serializer_pk_field: - ret[field_name] = serializer_pk_field + # Use the default set of fields if none is supplied explicitly. + if fields is None: + fields = self._get_default_field_names(declared_fields, info) - # Regular fields - for field_name, field in info.fields.items(): - ret[field_name] = self.get_field(field_name, field) + 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 - # Forward relations - for field_name, relation_info in info.forward_relations.items(): - if self.opts.depth: - ret[field_name] = self.get_nested_field(field_name, *relation_info) - else: - ret[field_name] = self.get_related_field(field_name, *relation_info) + elif field_name == api_settings.URL_FIELD_NAME: + # Create the URL field. + field_cls = HyperlinkedIdentityField + kwargs = get_url_kwargs(model) - # Reverse relations - for accessor_name, relation_info in info.reverse_relations.items(): - if accessor_name in self.opts.fields: - if self.opts.depth: - ret[accessor_name] = self.get_nested_field(accessor_name, *relation_info) + elif field_name in info.fields_and_pk: + # Create regular model fields. + model_field = info.fields_and_pk[field_name] + field_cls = lookup_class(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) + + 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: - ret[accessor_name] = self.get_related_field(accessor_name, *relation_info) + 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) + + else: + assert False, 'Field name `%s` is not valid.' % field_name + + ret[field_name] = field_cls(**kwargs) return ret - def get_url_field(self): - return None + def _get_default_field_names(self, declared_fields, model_info): + return ( + [model_info.pk.name] + + list(declared_fields.keys()) + + list(model_info.fields.keys()) + + list(model_info.forward_relations.keys()) + ) - def get_pk_field(self, field_name, model_field): - """ - Returns a default instance of the pk field. - """ - return self.get_field(field_name, model_field) - - def get_nested_field(self, field_name, model_field, related_model, to_many, has_through_model): - """ - Creates a default instance of a nested relational field. - - Note that model_field will be `None` for reverse relationships. - """ - class NestedModelSerializer(self.nested_class): + def _get_nested_class(self, nested_depth, relation_info): + class NestedSerializer(ModelSerializer): class Meta: - model = related_model - depth = self.opts.depth - 1 - - kwargs = {'read_only': True} - if to_many: - kwargs['many'] = True - return NestedModelSerializer(**kwargs) - - def get_related_field(self, field_name, model_field, related_model, to_many, has_through_model): - """ - Creates a default instance of a flat relational field. - - Note that model_field will be `None` for reverse relationships. - """ - kwargs = { - 'queryset': related_model._default_manager, - } - - if to_many: - kwargs['many'] = True - - if has_through_model: - kwargs['read_only'] = True - kwargs.pop('queryset', None) - - if model_field: - if model_field.null or model_field.blank: - kwargs['required'] = False - if model_field.verbose_name and needs_label(model_field, field_name): - kwargs['label'] = capfirst(model_field.verbose_name) - if not model_field.editable: - kwargs['read_only'] = True - kwargs.pop('queryset', None) - help_text = clean_manytomany_helptext(model_field.help_text) - if help_text: - kwargs['help_text'] = help_text - - return PrimaryKeyRelatedField(**kwargs) - - def get_field(self, field_name, model_field): - """ - Creates a default instance of a basic non-relational field. - """ - serializer_cls = lookup_class(self.field_mapping, model_field) - kwargs = {} - validator_kwarg = model_field.validators - - if model_field.null or model_field.blank: - kwargs['required'] = False - - if model_field.verbose_name and needs_label(model_field, field_name): - kwargs['label'] = capfirst(model_field.verbose_name) - - if model_field.help_text: - kwargs['help_text'] = model_field.help_text - - if isinstance(model_field, models.AutoField) or not model_field.editable: - kwargs['read_only'] = True - # Read only implies that the field is not required. - # We have a cleaner repr on the instance if we don't set it. - kwargs.pop('required', None) - - if model_field.has_default(): - kwargs['default'] = model_field.get_default() - # Having a default implies that the field is not required. - # We have a cleaner repr on the instance if we don't set it. - kwargs.pop('required', None) - - if model_field.flatchoices: - # If this model field contains choices, then use a ChoiceField, - # rather than the standard serializer field for this type. - # Note that we return this prior to setting any validation type - # keyword arguments, as those are not valid initializers. - kwargs['choices'] = model_field.flatchoices - return ChoiceField(**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) - if max_length is not None: - kwargs['max_length'] = max_length - validator_kwarg = [ - validator for validator in validator_kwarg - if not isinstance(validator, validators.MaxLengthValidator) - ] - - # Ensure that min_length is passed explicitly as a keyword arg, - # rather than as a validator. - min_length = getattr(model_field, 'min_length', None) - if min_length is not None: - kwargs['min_length'] = min_length - validator_kwarg = [ - validator for validator in validator_kwarg - if not isinstance(validator, validators.MinLengthValidator) - ] - - # Ensure that max_value is passed explicitly as a keyword arg, - # rather than as a validator. - max_value = next(( - validator.limit_value for validator in validator_kwarg - if isinstance(validator, validators.MaxValueValidator) - ), None) - if max_value is not None: - kwargs['max_value'] = max_value - validator_kwarg = [ - validator for validator in validator_kwarg - if not isinstance(validator, validators.MaxValueValidator) - ] - - # Ensure that max_value is passed explicitly as a keyword arg, - # rather than as a validator. - min_value = next(( - validator.limit_value for validator in validator_kwarg - if isinstance(validator, validators.MinValueValidator) - ), None) - if min_value is not None: - kwargs['min_value'] = min_value - validator_kwarg = [ - validator for validator in validator_kwarg - if not isinstance(validator, validators.MinValueValidator) - ] - - # URLField does not need to include the URLValidator argument, - # as it is explicitly added in. - if isinstance(model_field, models.URLField): - validator_kwarg = [ - validator for validator in validator_kwarg - if not isinstance(validator, validators.URLValidator) - ] - - # EmailField does not need to include the validate_email argument, - # as it is explicitly added in. - if isinstance(model_field, models.EmailField): - validator_kwarg = [ - validator for validator in validator_kwarg - if validator is not validators.validate_email - ] - - # SlugField do not need to include the 'validate_slug' argument, - if isinstance(model_field, models.SlugField): - validator_kwarg = [ - validator for validator in validator_kwarg - if validator is not validators.validate_slug - ] - - max_digits = getattr(model_field, 'max_digits', None) - if max_digits is not None: - kwargs['max_digits'] = max_digits - - decimal_places = getattr(model_field, 'decimal_places', None) - if decimal_places is not None: - kwargs['decimal_places'] = decimal_places - - if isinstance(model_field, models.BooleanField): - # models.BooleanField has `blank=True`, but *is* actually - # required *unless* a default is provided. - # Also note that Django<1.6 uses `default=False` for - # models.BooleanField, but Django>=1.6 uses `default=None`. - kwargs.pop('required', None) - - if validator_kwarg: - kwargs['validators'] = validator_kwarg - - if issubclass(serializer_cls, ModelField): - kwargs['model_field'] = model_field - - return serializer_cls(**kwargs) - - -class HyperlinkedModelSerializerOptions(ModelSerializerOptions): - """ - Options for HyperlinkedModelSerializer - """ - def __init__(self, meta): - super(HyperlinkedModelSerializerOptions, self).__init__(meta) - self.view_name = getattr(meta, 'view_name', None) - self.lookup_field = getattr(meta, 'lookup_field', None) + model = relation_info.related + depth = nested_depth + return NestedSerializer class HyperlinkedModelSerializer(ModelSerializer): - _options_class = HyperlinkedModelSerializerOptions + _related_class = HyperlinkedRelatedField - def get_url_field(self): - if self.opts.view_name is not None: - view_name = self.opts.view_name - else: - view_name = self.get_default_view_name(self.opts.model) + def _get_default_field_names(self, declared_fields, model_info): + return ( + [api_settings.URL_FIELD_NAME] + + list(declared_fields.keys()) + + list(model_info.fields.keys()) + + list(model_info.forward_relations.keys()) + ) - kwargs = { - 'view_name': view_name - } - if self.opts.lookup_field: - kwargs['lookup_field'] = self.opts.lookup_field - - return HyperlinkedIdentityField(**kwargs) - - def get_pk_field(self, field_name, model_field): - if self.opts.fields and model_field.name in self.opts.fields: - return self.get_field(model_field) - - def get_related_field(self, field_name, model_field, related_model, to_many, has_through_model): - """ - Creates a default instance of a flat relational field. - """ - kwargs = { - 'queryset': related_model._default_manager, - 'view_name': self.get_default_view_name(related_model), - } - - if to_many: - kwargs['many'] = True - - if has_through_model: - kwargs['read_only'] = True - kwargs.pop('queryset', None) - - if model_field: - if model_field.null or model_field.blank: - kwargs['required'] = False - if model_field.verbose_name and needs_label(model_field, field_name): - kwargs['label'] = capfirst(model_field.verbose_name) - if not model_field.editable: - kwargs['read_only'] = True - kwargs.pop('queryset', None) - help_text = clean_manytomany_helptext(model_field.help_text) - if help_text: - kwargs['help_text'] = help_text - - return HyperlinkedRelatedField(**kwargs) - - def get_default_view_name(self, model): - """ - Return the view name to use for related models. - """ - return '%(model_name)s-detail' % { - 'app_label': model._meta.app_label, - 'model_name': model._meta.object_name.lower() - } - - -ModelSerializer.nested_class = ModelSerializer -HyperlinkedModelSerializer.nested_class = HyperlinkedModelSerializer + def _get_nested_class(self, nested_depth, relation_info): + class NestedSerializer(HyperlinkedModelSerializer): + class Meta: + model = relation_info.related + depth = nested_depth + return NestedSerializer diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py new file mode 100644 index 000000000..be72e444e --- /dev/null +++ b/rest_framework/utils/field_mapping.py @@ -0,0 +1,215 @@ +""" +Helper functions for mapping model fields to a dictionary of default +keyword arguments that should be used for their equivelent serializer fields. +""" +from django.core import validators +from django.db import models +from django.utils.text import capfirst +from rest_framework.compat import clean_manytomany_helptext +import inspect + + +def lookup_class(mapping, instance): + """ + Takes a dictionary with classes as keys, and an object. + Traverses the object's inheritance hierarchy in method + resolution order, and returns the first matching value + from the dictionary or raises a KeyError if nothing matches. + """ + for cls in inspect.getmro(instance.__class__): + if cls in mapping: + return mapping[cls] + raise KeyError('Class %s not found in lookup.', cls.__name__) + + +def needs_label(model_field, field_name): + """ + Returns `True` if the label based on the model's verbose name + is not equal to the default label it would have based on it's field name. + """ + default_label = field_name.replace('_', ' ').capitalize() + return capfirst(model_field.verbose_name) != default_label + + +def get_detail_view_name(model): + """ + Given a model class, return the view name to use for URL relationships + that refer to instances of the model. + """ + return '%(model_name)s-detail' % { + 'app_label': model._meta.app_label, + 'model_name': model._meta.object_name.lower() + } + + +def get_field_kwargs(field_name, model_field): + """ + Creates a default instance of a basic non-relational field. + """ + kwargs = {} + validator_kwarg = model_field.validators + + if model_field.null or model_field.blank: + kwargs['required'] = False + + if model_field.verbose_name and needs_label(model_field, field_name): + kwargs['label'] = capfirst(model_field.verbose_name) + + if model_field.help_text: + kwargs['help_text'] = model_field.help_text + + if isinstance(model_field, models.AutoField) or not model_field.editable: + kwargs['read_only'] = True + # Read only implies that the field is not required. + # We have a cleaner repr on the instance if we don't set it. + kwargs.pop('required', None) + + if model_field.has_default(): + kwargs['default'] = model_field.get_default() + # Having a default implies that the field is not required. + # We have a cleaner repr on the instance if we don't set it. + kwargs.pop('required', None) + + if model_field.flatchoices: + # If this model field contains choices, then return now, + # any 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) + if max_length is not None: + kwargs['max_length'] = max_length + validator_kwarg = [ + validator for validator in validator_kwarg + if not isinstance(validator, validators.MaxLengthValidator) + ] + + # Ensure that min_length is passed explicitly as a keyword arg, + # rather than as a validator. + min_length = getattr(model_field, 'min_length', None) + if min_length is not None: + kwargs['min_length'] = min_length + validator_kwarg = [ + validator for validator in validator_kwarg + if not isinstance(validator, validators.MinLengthValidator) + ] + + # Ensure that max_value is passed explicitly as a keyword arg, + # rather than as a validator. + max_value = next(( + validator.limit_value for validator in validator_kwarg + if isinstance(validator, validators.MaxValueValidator) + ), None) + if max_value is not None: + kwargs['max_value'] = max_value + validator_kwarg = [ + validator for validator in validator_kwarg + if not isinstance(validator, validators.MaxValueValidator) + ] + + # Ensure that max_value is passed explicitly as a keyword arg, + # rather than as a validator. + min_value = next(( + validator.limit_value for validator in validator_kwarg + if isinstance(validator, validators.MinValueValidator) + ), None) + if min_value is not None: + kwargs['min_value'] = min_value + validator_kwarg = [ + validator for validator in validator_kwarg + if not isinstance(validator, validators.MinValueValidator) + ] + + # URLField does not need to include the URLValidator argument, + # as it is explicitly added in. + if isinstance(model_field, models.URLField): + validator_kwarg = [ + validator for validator in validator_kwarg + if not isinstance(validator, validators.URLValidator) + ] + + # EmailField does not need to include the validate_email argument, + # as it is explicitly added in. + if isinstance(model_field, models.EmailField): + validator_kwarg = [ + validator for validator in validator_kwarg + if validator is not validators.validate_email + ] + + # SlugField do not need to include the 'validate_slug' argument, + if isinstance(model_field, models.SlugField): + validator_kwarg = [ + validator for validator in validator_kwarg + if validator is not validators.validate_slug + ] + + max_digits = getattr(model_field, 'max_digits', None) + if max_digits is not None: + kwargs['max_digits'] = max_digits + + decimal_places = getattr(model_field, 'decimal_places', None) + if decimal_places is not None: + kwargs['decimal_places'] = decimal_places + + if isinstance(model_field, models.BooleanField): + # models.BooleanField has `blank=True`, but *is* actually + # required *unless* a default is provided. + # Also note that Django<1.6 uses `default=False` for + # models.BooleanField, but Django>=1.6 uses `default=None`. + kwargs.pop('required', None) + + if validator_kwarg: + kwargs['validators'] = validator_kwarg + + # The following will only be used by ModelField classes. + # Gets removed for everything else. + kwargs['model_field'] = model_field + + return kwargs + + +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 + kwargs = { + 'queryset': related_model._default_manager, + 'view_name': get_detail_view_name(related_model) + } + + if to_many: + kwargs['many'] = True + + if has_through_model: + kwargs['read_only'] = True + kwargs.pop('queryset', None) + + if model_field: + if model_field.null or model_field.blank: + kwargs['required'] = False + if model_field.verbose_name and needs_label(model_field, field_name): + kwargs['label'] = capfirst(model_field.verbose_name) + if not model_field.editable: + kwargs['read_only'] = True + kwargs.pop('queryset', None) + help_text = clean_manytomany_helptext(model_field.help_text) + if help_text: + kwargs['help_text'] = help_text + + return kwargs + + +def get_nested_relation_kwargs(relation_info): + kwargs = {'read_only': True} + if relation_info.to_many: + kwargs['many'] = True + return kwargs + + +def get_url_kwargs(model_field): + return { + 'view_name': get_detail_view_name(model_field) + } diff --git a/rest_framework/utils/model_meta.py b/rest_framework/utils/model_meta.py index 960fa4d0f..b6c41174e 100644 --- a/rest_framework/utils/model_meta.py +++ b/rest_framework/utils/model_meta.py @@ -1,7 +1,9 @@ """ -Helper functions for returning the field information that is associated +Helper function for returning the field information that is associated with a model class. This includes returning all the forward and reverse relationships and their associated metadata. + +Usage: `get_field_info(model)` returns a `FieldInfo` instance. """ from collections import namedtuple from django.db import models @@ -9,8 +11,22 @@ from django.utils import six from django.utils.datastructures import SortedDict import inspect -FieldInfo = namedtuple('FieldResult', ['pk', 'fields', 'forward_relations', 'reverse_relations']) -RelationInfo = namedtuple('RelationInfo', ['field', 'related', 'to_many', 'has_through_model']) + +FieldInfo = namedtuple('FieldResult', [ + 'pk', # Model field instance + 'fields', # Dict of field name -> model field instance + 'forward_relations', # Dict of field name -> RelationInfo + 'reverse_relations', # Dict of field name -> RelationInfo + 'fields_and_pk', # Shortcut for 'pk' + 'fields' + 'relations' # Shortcut for 'forward_relations' + 'reverse_relations' +]) + +RelationInfo = namedtuple('RelationInfo', [ + 'model_field', + 'related', + 'to_many', + 'has_through_model' +]) def _resolve_model(obj): @@ -55,7 +71,7 @@ def get_field_info(model): forward_relations = SortedDict() for field in [field for field in opts.fields if field.serialize and field.rel]: forward_relations[field.name] = RelationInfo( - field=field, + model_field=field, related=_resolve_model(field.rel.to), to_many=False, has_through_model=False @@ -64,7 +80,7 @@ def get_field_info(model): # Deal with forward many-to-many relationships. for field in [field for field in opts.many_to_many if field.serialize]: forward_relations[field.name] = RelationInfo( - field=field, + model_field=field, related=_resolve_model(field.rel.to), to_many=True, has_through_model=( @@ -77,7 +93,7 @@ def get_field_info(model): for relation in opts.get_all_related_objects(): accessor_name = relation.get_accessor_name() reverse_relations[accessor_name] = RelationInfo( - field=None, + model_field=None, related=relation.model, to_many=relation.field.rel.multiple, has_through_model=False @@ -87,7 +103,7 @@ def get_field_info(model): for relation in opts.get_all_related_many_to_many_objects(): accessor_name = relation.get_accessor_name() reverse_relations[accessor_name] = RelationInfo( - field=None, + model_field=None, related=relation.model, to_many=True, has_through_model=( @@ -96,4 +112,18 @@ def get_field_info(model): ) ) - return FieldInfo(pk, fields, forward_relations, reverse_relations) + # Shortcut that merges both regular fields and the pk, + # for simplifying regular field lookup. + fields_and_pk = SortedDict() + fields_and_pk['pk'] = pk + fields_and_pk[pk.name] = pk + fields_and_pk.update(fields) + + # Shortcut that merges both forward and reverse relationships + + relations = SortedDict( + list(forward_relations.items()) + + list(reverse_relations.items()) + ) + + return FieldInfo(pk, fields, forward_relations, reverse_relations, fields_and_pk, relations) diff --git a/tests/models.py b/tests/models.py index fe064b46a..06ec5a221 100644 --- a/tests/models.py +++ b/tests/models.py @@ -1,7 +1,6 @@ from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ -from rest_framework import serializers def foobar(): @@ -178,9 +177,3 @@ class NullableOneToOneSource(RESTFrameworkModel): name = models.CharField(max_length=100) target = models.OneToOneField(OneToOneTarget, null=True, blank=True, related_name='nullable_source') - - -# Serializer used to test BasicModel -class BasicModelSerializer(serializers.ModelSerializer): - class Meta: - model = BasicModel diff --git a/tests/test_model_field_mappings.py b/tests/test_model_field_mappings.py index bae63e5a7..6daa574e5 100644 --- a/tests/test_model_field_mappings.py +++ b/tests/test_model_field_mappings.py @@ -126,16 +126,16 @@ class TestRelationalFieldMappings(TestCase): expected = dedent(""" TestSerializer(): id = IntegerField(label='ID', read_only=True) - foreign_key = NestedModelSerializer(read_only=True): + foreign_key = NestedSerializer(read_only=True): id = IntegerField(label='ID', read_only=True) name = CharField(max_length=100) - one_to_one = NestedModelSerializer(read_only=True): + one_to_one = NestedSerializer(read_only=True): id = IntegerField(label='ID', read_only=True) name = CharField(max_length=100) - many_to_many = NestedModelSerializer(many=True, read_only=True): + many_to_many = NestedSerializer(many=True, read_only=True): id = IntegerField(label='ID', read_only=True) name = CharField(max_length=100) - through = NestedModelSerializer(many=True, read_only=True): + through = NestedSerializer(many=True, read_only=True): id = IntegerField(label='ID', read_only=True) name = CharField(max_length=100) """) @@ -165,16 +165,16 @@ class TestRelationalFieldMappings(TestCase): expected = dedent(""" TestSerializer(): url = HyperlinkedIdentityField(view_name='relationalmodel-detail') - foreign_key = NestedModelSerializer(read_only=True): + foreign_key = NestedSerializer(read_only=True): url = HyperlinkedIdentityField(view_name='foreignkeytargetmodel-detail') name = CharField(max_length=100) - one_to_one = NestedModelSerializer(read_only=True): + one_to_one = NestedSerializer(read_only=True): url = HyperlinkedIdentityField(view_name='onetoonetargetmodel-detail') name = CharField(max_length=100) - many_to_many = NestedModelSerializer(many=True, read_only=True): + many_to_many = NestedSerializer(many=True, read_only=True): url = HyperlinkedIdentityField(view_name='manytomanytargetmodel-detail') name = CharField(max_length=100) - through = NestedModelSerializer(many=True, read_only=True): + through = NestedSerializer(many=True, read_only=True): url = HyperlinkedIdentityField(view_name='throughtargetmodel-detail') name = CharField(max_length=100) """) diff --git a/tests/test_response.py b/tests/test_response.py index 67419a718..84c39c1a6 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -2,11 +2,12 @@ from __future__ import unicode_literals from django.conf.urls import patterns, url, include from django.test import TestCase from django.utils import six -from tests.models import BasicModel, BasicModelSerializer +from tests.models import BasicModel from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import generics from rest_framework import routers +from rest_framework import serializers from rest_framework import status from rest_framework.renderers import ( BaseRenderer, @@ -17,6 +18,12 @@ from rest_framework import viewsets from rest_framework.settings import api_settings +# Serializer used to test BasicModel +class BasicModelSerializer(serializers.ModelSerializer): + class Meta: + model = BasicModel + + class MockPickleRenderer(BaseRenderer): media_type = 'application/pickle' diff --git a/tests/test_routers.py b/tests/test_routers.py index b076f134e..c2d595f7f 100644 --- a/tests/test_routers.py +++ b/tests/test_routers.py @@ -76,9 +76,10 @@ class TestCustomLookupFields(TestCase): def setUp(self): class NoteSerializer(serializers.HyperlinkedModelSerializer): + url = serializers.HyperlinkedIdentityField(view_name='routertestmodel-detail', lookup_field='uuid') + class Meta: model = RouterTestModel - lookup_field = 'uuid' fields = ('url', 'uuid', 'text') class NoteViewSet(viewsets.ModelViewSet): @@ -86,8 +87,6 @@ class TestCustomLookupFields(TestCase): serializer_class = NoteSerializer lookup_field = 'uuid' - RouterTestModel.objects.create(uuid='123', text='foo bar') - self.router = SimpleRouter() self.router.register(r'notes', NoteViewSet) @@ -98,6 +97,8 @@ class TestCustomLookupFields(TestCase): url(r'^', include(self.router.urls)), ) + RouterTestModel.objects.create(uuid='123', text='foo bar') + def test_custom_lookup_field_route(self): detail_route = self.router.urls[-1] detail_url_pattern = detail_route.regex.pattern From 87734be5f41de921ac32ad1f6664db243aab6d07 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 18 Sep 2014 12:17:21 +0100 Subject: [PATCH 055/249] Configuration correctness tests on ModelSerializer --- rest_framework/serializers.py | 30 ++++++- ...d_mappings.py => test_model_serializer.py} | 85 +++++++++++++++++++ 2 files changed, 112 insertions(+), 3 deletions(-) rename tests/{test_model_field_mappings.py => test_model_serializer.py} (77%) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 99dcc349f..9f3e53fd0 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -10,7 +10,7 @@ python primitives. 2. The process of marshalling between python primitives and request and response content is handled by parsers and renderers. """ -from django.core.exceptions import ValidationError +from django.core.exceptions import ImproperlyConfigured, ValidationError from django.db import models from django.utils import six from django.utils.datastructures import SortedDict @@ -358,6 +358,7 @@ class ModelSerializer(Serializer): model = getattr(self.Meta, 'model') fields = getattr(self.Meta, 'fields', None) depth = getattr(self.Meta, 'depth', 0) + extra_kwargs = getattr(self.Meta, 'extra_kwargs', {}) # Retrieve metadata about fields & relationships on the model class. info = model_meta.get_field_info(model) @@ -405,9 +406,32 @@ class ModelSerializer(Serializer): if not issubclass(field_cls, HyperlinkedRelatedField): kwargs.pop('view_name', None) - else: - assert False, 'Field name `%s` is not valid.' % field_name + elif hasattr(model, field_name): + # Create a read only field for model methods and properties. + field_cls = ReadOnlyField + kwargs = {} + else: + raise ImproperlyConfigured( + 'Field name `%s` is not valid for model `%s`.' % + (field_name, model.__class__.__name__) + ) + + # Check that any fields declared on the class are + # also explicity 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__) + ) + + # Populate any kwargs defined in `Meta.extra_kwargs` + kwargs.update(extra_kwargs.get(field_name, {})) + + # Create the serializer field. ret[field_name] = field_cls(**kwargs) return ret diff --git a/tests/test_model_field_mappings.py b/tests/test_model_serializer.py similarity index 77% rename from tests/test_model_field_mappings.py rename to tests/test_model_serializer.py index 6daa574e5..63e364528 100644 --- a/tests/test_model_field_mappings.py +++ b/tests/test_model_serializer.py @@ -5,6 +5,7 @@ shortcuts for automatically creating serializers based on a given model class. These tests deal with ensuring that we correctly map the model fields onto an appropriate set of serializer fields for each case. """ +from django.core.exceptions import ImproperlyConfigured from django.db import models from django.test import TestCase from rest_framework import serializers @@ -37,6 +38,9 @@ class RegularFieldsModel(models.Model): time_field = models.TimeField() url_field = models.URLField(max_length=100) + def method(self): + return 'method' + class TestRegularFieldMappings(TestCase): def test_regular_fields(self): @@ -69,6 +73,87 @@ class TestRegularFieldMappings(TestCase): self.assertEqual(repr(TestSerializer()), expected) + def test_method_field(self): + """ + Properties and methods on the model should be allowed as `Meta.fields` + values, and should map to `ReadOnlyField`. + """ + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = RegularFieldsModel + fields = ('auto_field', 'method') + + expected = dedent(""" + TestSerializer(): + auto_field = IntegerField(read_only=True) + method = ReadOnlyField() + """) + self.assertEqual(repr(TestSerializer()), expected) + + def test_pk_fields(self): + """ + Both `pk` and the actual primary key name are valid in `Meta.fields`. + """ + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = RegularFieldsModel + fields = ('pk', 'auto_field') + + expected = dedent(""" + TestSerializer(): + pk = IntegerField(label='Auto field', read_only=True) + auto_field = IntegerField(read_only=True) + """) + self.assertEqual(repr(TestSerializer()), expected) + + def test_extra_field_kwargs(self): + """ + Ensure `extra_kwargs` are passed to generated fields. + """ + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = RegularFieldsModel + fields = ('pk', 'char_field') + extra_kwargs = {'char_field': {'default': 'extra'}} + + expected = dedent(""" + TestSerializer(): + pk = IntegerField(label='Auto field', read_only=True) + char_field = CharField(default='extra', 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 + raise a configuration errror. + """ + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = RegularFieldsModel + fields = ('auto_field', 'invalid') + + with self.assertRaises(ImproperlyConfigured) as excinfo: + TestSerializer() + expected = 'Field name `invalid` is not valid for model `ModelBase`.' + assert str(excinfo.exception) == expected + + def test_missing_field(self): + class TestSerializer(serializers.ModelSerializer): + missing = serializers.ReadOnlyField() + + class Meta: + model = RegularFieldsModel + fields = ('auto_field',) + + with self.assertRaises(ImproperlyConfigured) as excinfo: + TestSerializer() + expected = ( + 'Field `missing` has been declared on serializer ' + '`TestSerializer`, but is missing from `Meta.fields`.' + ) + assert str(excinfo.exception) == expected + # Testing relational field mappings From 3bc628edc01a6bd4feeceaefa45168549b79a31a Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 18 Sep 2014 13:07:38 +0100 Subject: [PATCH 056/249] Test for custom fields --- tests/test_model_serializer.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index 63e364528..3ee91126f 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -17,6 +17,10 @@ def dedent(blocktext): # Testing regular field mappings +class CustomField(models.Field): + pass + + class RegularFieldsModel(models.Model): auto_field = models.AutoField(primary_key=True) big_integer_field = models.BigIntegerField() @@ -37,6 +41,7 @@ class RegularFieldsModel(models.Model): text_field = models.TextField() time_field = models.TimeField() url_field = models.URLField(max_length=100) + custom_field = CustomField() def method(self): return 'method' @@ -44,6 +49,9 @@ class RegularFieldsModel(models.Model): class TestRegularFieldMappings(TestCase): def test_regular_fields(self): + """ + Model fields should map to their equivelent serializer fields. + """ class TestSerializer(serializers.ModelSerializer): class Meta: model = RegularFieldsModel @@ -69,8 +77,8 @@ class TestRegularFieldMappings(TestCase): text_field = CharField() time_field = TimeField() url_field = URLField(max_length=100) + custom_field = ModelField(model_field=<tests.test_model_serializer.CustomField: custom_field>) """) - self.assertEqual(repr(TestSerializer()), expected) def test_method_field(self): @@ -139,6 +147,10 @@ class TestRegularFieldMappings(TestCase): assert str(excinfo.exception) == expected def test_missing_field(self): + """ + Fields that have been declared on the serializer class must be included + in the `Meta.fields` if it exists. + """ class TestSerializer(serializers.ModelSerializer): missing = serializers.ReadOnlyField() From 9fdb2280d11db126771686d626aa8a0247b8a46c Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 18 Sep 2014 14:23:00 +0100 Subject: [PATCH 057/249] First pass on ManyRelation --- rest_framework/relations.py | 42 +++++++++++++++++++- rest_framework/utils/representation.py | 2 + tests/test_model_serializer.py | 54 ++++++++++++++++++++++---- 3 files changed, 89 insertions(+), 9 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 9f44ab633..474d3e757 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -10,7 +10,6 @@ from django.utils.translation import ugettext_lazy as _ class RelatedField(Field): def __init__(self, **kwargs): self.queryset = kwargs.pop('queryset', None) - self.many = kwargs.pop('many', False) assert self.queryset is not None or kwargs.get('read_only', None), ( 'Relational field must provide a `queryset` argument, ' 'or set read_only=`True`.' @@ -21,6 +20,13 @@ class RelatedField(Field): ) super(RelatedField, self).__init__(**kwargs) + def __new__(cls, *args, **kwargs): + # We override this method in order to automagically create + # `ManyRelation` classes instead when `many=True` is set. + if kwargs.pop('many', False): + return ManyRelation(child_relation=cls(*args, **kwargs)) + return super(RelatedField, cls).__new__(cls, *args, **kwargs) + def get_queryset(self): queryset = self.queryset if isinstance(queryset, QuerySet): @@ -216,3 +222,37 @@ class SlugRelatedField(RelatedField): def to_representation(self, obj): return getattr(obj, self.slug_field) + + +class ManyRelation(Field): + """ + Relationships with `many=True` transparently get coerced into instead being + a ManyRelation with a child relationship. + + The `ManyRelation` class is responsible for handling iterating through + the values and passing each one to the child relationship. + + You shouldn't need to be using this class directly yourself. + """ + + def __init__(self, child_relation=None, *args, **kwargs): + self.child_relation = child_relation + assert child_relation is not None, '`child_relation` is a required argument.' + super(ManyRelation, self).__init__(*args, **kwargs) + + def bind(self, field_name, parent, root): + # ManyRelation needs to provide the current context to the child relation. + super(ManyRelation, self).bind(field_name, parent, root) + self.child_relation.bind(field_name, parent, root) + + def to_internal_value(self, data): + return [ + self.child_relation.to_internal_value(item) + for item in data + ] + + def to_representation(self, obj): + return [ + self.child_relation.to_representation(value) + for value in obj.all() + ] diff --git a/rest_framework/utils/representation.py b/rest_framework/utils/representation.py index 71db18863..e64fdd223 100644 --- a/rest_framework/utils/representation.py +++ b/rest_framework/utils/representation.py @@ -73,6 +73,8 @@ def serializer_repr(serializer, indent, force_many=None): ret += serializer_repr(field, indent + 1) elif hasattr(field, 'child'): ret += list_repr(field, indent + 1) + elif hasattr(field, 'child_relation'): + ret += field_repr(field.child_relation, force_many=field.child_relation) else: ret += field_repr(field) return ret diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index 3ee91126f..b3dae7134 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -199,7 +199,7 @@ class RelationalModel(models.Model): class TestRelationalFieldMappings(TestCase): - def test_flat_relational_fields(self): + def test_pk_relations(self): class TestSerializer(serializers.ModelSerializer): class Meta: model = RelationalModel @@ -214,7 +214,7 @@ class TestRelationalFieldMappings(TestCase): """) self.assertEqual(repr(TestSerializer()), expected) - def test_nested_relational_fields(self): + def test_nested_relations(self): class TestSerializer(serializers.ModelSerializer): class Meta: model = RelationalModel @@ -238,7 +238,7 @@ class TestRelationalFieldMappings(TestCase): """) self.assertEqual(repr(TestSerializer()), expected) - def test_flat_hyperlinked_fields(self): + def test_hyperlinked_relations(self): class TestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = RelationalModel @@ -253,7 +253,7 @@ class TestRelationalFieldMappings(TestCase): """) self.assertEqual(repr(TestSerializer()), expected) - def test_nested_hyperlinked_fields(self): + def test_nested_hyperlinked_relations(self): class TestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = RelationalModel @@ -277,7 +277,7 @@ class TestRelationalFieldMappings(TestCase): """) self.assertEqual(repr(TestSerializer()), expected) - def test_flat_reverse_foreign_key(self): + def test_pk_reverse_foreign_key(self): class TestSerializer(serializers.ModelSerializer): class Meta: model = ForeignKeyTargetModel @@ -291,7 +291,7 @@ class TestRelationalFieldMappings(TestCase): """) self.assertEqual(repr(TestSerializer()), expected) - def test_flat_reverse_one_to_one(self): + def test_pk_reverse_one_to_one(self): class TestSerializer(serializers.ModelSerializer): class Meta: model = OneToOneTargetModel @@ -305,7 +305,7 @@ class TestRelationalFieldMappings(TestCase): """) self.assertEqual(repr(TestSerializer()), expected) - def test_flat_reverse_many_to_many(self): + def test_pk_reverse_many_to_many(self): class TestSerializer(serializers.ModelSerializer): class Meta: model = ManyToManyTargetModel @@ -319,7 +319,7 @@ class TestRelationalFieldMappings(TestCase): """) self.assertEqual(repr(TestSerializer()), expected) - def test_flat_reverse_through(self): + def test_pk_reverse_through(self): class TestSerializer(serializers.ModelSerializer): class Meta: model = ThroughTargetModel @@ -332,3 +332,41 @@ class TestRelationalFieldMappings(TestCase): reverse_through = PrimaryKeyRelatedField(many=True, read_only=True) """) self.assertEqual(repr(TestSerializer()), expected) + + +class TestIntegration(TestCase): + def setUp(self): + self.foreign_key_target = ForeignKeyTargetModel.objects.create( + name='foreign_key' + ) + self.one_to_one_target = OneToOneTargetModel.objects.create( + name='one_to_one' + ) + self.many_to_many_targets = [ + ManyToManyTargetModel.objects.create( + name='many_to_many (%d)' % idx + ) for idx in range(3) + ] + self.instance = RelationalModel.objects.create( + foreign_key=self.foreign_key_target, + one_to_one=self.one_to_one_target, + ) + self.instance.many_to_many = self.many_to_many_targets + self.instance.save() + + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = RelationalModel + + self.serializer_cls = TestSerializer + + def test_pk_relationship_representations(self): + serializer = self.serializer_cls(self.instance) + expected = { + 'id': self.instance.pk, + 'foreign_key': self.foreign_key_target.pk, + 'one_to_one': self.one_to_one_target.pk, + 'many_to_many': [item.pk for item in self.many_to_many_targets], + 'through': [] + } + self.assertEqual(serializer.data, expected) From 106362b437f45e04faaea759df57a66a8a2d7cfd Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 18 Sep 2014 14:58:08 +0100 Subject: [PATCH 058/249] ModelSerializer.create() to handle many to many by default --- rest_framework/relations.py | 5 +++- rest_framework/serializers.py | 20 ++++++++++++++- tests/test_model_serializer.py | 45 +++++++++++++++++++++++++++++++++- 3 files changed, 67 insertions(+), 3 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 474d3e757..5aa1f8bd8 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -24,7 +24,10 @@ class RelatedField(Field): # We override this method in order to automagically create # `ManyRelation` classes instead when `many=True` is set. if kwargs.pop('many', False): - return ManyRelation(child_relation=cls(*args, **kwargs)) + return ManyRelation( + child_relation=cls(*args, **kwargs), + read_only=kwargs.get('read_only', False) + ) return super(RelatedField, cls).__new__(cls, *args, **kwargs) def get_queryset(self): diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 9f3e53fd0..03e20df8a 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -344,7 +344,25 @@ class ModelSerializer(Serializer): def create(self, attrs): ModelClass = self.Meta.model - return ModelClass.objects.create(**attrs) + + # Remove many-to-many relationships from attrs. + # They are not valid arguments to the default `.create()` method, + # as they require that the instance has already been saved. + info = model_meta.get_field_info(ModelClass) + many_to_many = {} + for key, relation_info in info.relations.items(): + if relation_info.to_many and (key in attrs): + many_to_many[key] = attrs.pop(key) + + instance = ModelClass.objects.create(**attrs) + + # Save many to many relationships after the instance is created. + if many_to_many: + for key, value in many_to_many.items(): + setattr(instance, key, value) + instance.save() + + return instance def update(self, obj, attrs): for attr, value in attrs.items(): diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index b3dae7134..6f207e02c 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -360,7 +360,7 @@ class TestIntegration(TestCase): self.serializer_cls = TestSerializer - def test_pk_relationship_representations(self): + def test_pk_retrival(self): serializer = self.serializer_cls(self.instance) expected = { 'id': self.instance.pk, @@ -370,3 +370,46 @@ class TestIntegration(TestCase): 'through': [] } self.assertEqual(serializer.data, expected) + + def test_pk_create(self): + new_foreign_key = ForeignKeyTargetModel.objects.create( + name='foreign_key' + ) + new_one_to_one = OneToOneTargetModel.objects.create( + name='one_to_one' + ) + new_many_to_many = [ + ManyToManyTargetModel.objects.create( + name='new many_to_many (%d)' % idx + ) for idx in range(3) + ] + data = { + 'foreign_key': new_foreign_key.pk, + 'one_to_one': new_one_to_one.pk, + 'many_to_many': [item.pk for item in new_many_to_many], + } + + # Serializer should validate okay. + serializer = self.serializer_cls(data=data) + assert serializer.is_valid() + + # Creating the instance, relationship attributes should be set. + instance = serializer.save() + assert instance.foreign_key.pk == new_foreign_key.pk + assert instance.one_to_one.pk == new_one_to_one.pk + assert [ + item.pk for item in instance.many_to_many.all() + ] == [ + item.pk for item in new_many_to_many + ] + assert list(instance.through.all()) == [] + + # Representation should be correct. + expected = { + 'id': instance.pk, + 'foreign_key': new_foreign_key.pk, + 'one_to_one': new_one_to_one.pk, + 'many_to_many': [item.pk for item in new_many_to_many], + 'through': [] + } + self.assertEqual(serializer.data, expected) From f90049316a3ecca6c92e10b57bfa5becbceff386 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 18 Sep 2014 15:47:27 +0100 Subject: [PATCH 059/249] Added a model update integration test --- rest_framework/serializers.py | 13 +++++----- tests/test_model_serializer.py | 43 ++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 7 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 03e20df8a..d2740fc2a 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -350,17 +350,16 @@ class ModelSerializer(Serializer): # as they require that the instance has already been saved. info = model_meta.get_field_info(ModelClass) many_to_many = {} - for key, relation_info in info.relations.items(): - if relation_info.to_many and (key in attrs): - many_to_many[key] = attrs.pop(key) + for field_name, relation_info in info.relations.items(): + if relation_info.to_many and (field_name in attrs): + many_to_many[field_name] = attrs.pop(field_name) instance = ModelClass.objects.create(**attrs) - # Save many to many relationships after the instance is created. + # Save many-to-many relationships after the instance is created. if many_to_many: - for key, value in many_to_many.items(): - setattr(instance, key, value) - instance.save() + for field_name, value in many_to_many.items(): + setattr(instance, field_name, value) return instance diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index 6f207e02c..e0120c313 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -413,3 +413,46 @@ class TestIntegration(TestCase): 'through': [] } self.assertEqual(serializer.data, expected) + + def test_pk_update(self): + new_foreign_key = ForeignKeyTargetModel.objects.create( + name='foreign_key' + ) + new_one_to_one = OneToOneTargetModel.objects.create( + name='one_to_one' + ) + new_many_to_many = [ + ManyToManyTargetModel.objects.create( + name='new many_to_many (%d)' % idx + ) for idx in range(3) + ] + data = { + 'foreign_key': new_foreign_key.pk, + 'one_to_one': new_one_to_one.pk, + 'many_to_many': [item.pk for item in new_many_to_many], + } + + # Serializer should validate okay. + serializer = self.serializer_cls(self.instance, data=data) + assert serializer.is_valid() + + # Creating the instance, relationship attributes should be set. + instance = serializer.save() + assert instance.foreign_key.pk == new_foreign_key.pk + assert instance.one_to_one.pk == new_one_to_one.pk + assert [ + item.pk for item in instance.many_to_many.all() + ] == [ + item.pk for item in new_many_to_many + ] + assert list(instance.through.all()) == [] + + # Representation should be correct. + expected = { + 'id': self.instance.pk, + 'foreign_key': new_foreign_key.pk, + 'one_to_one': new_one_to_one.pk, + 'many_to_many': [item.pk for item in new_many_to_many], + 'through': [] + } + self.assertEqual(serializer.data, expected) From 12ccb0fe8a7dfbefa3687d07ff59a456fbda9ee6 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 19 Sep 2014 09:09:26 +0100 Subject: [PATCH 060/249] Test tweaking --- tests/test_model_serializer.py | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index e0120c313..ec922b6d5 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -18,10 +18,16 @@ def dedent(blocktext): # Testing regular field mappings class CustomField(models.Field): + """ + A custom model field simply for testing purposes. + """ pass class RegularFieldsModel(models.Model): + """ + A model class for testing regular flat fields. + """ auto_field = models.AutoField(primary_key=True) big_integer_field = models.BigIntegerField() boolean_field = models.BooleanField(default=False) @@ -121,12 +127,12 @@ class TestRegularFieldMappings(TestCase): class TestSerializer(serializers.ModelSerializer): class Meta: model = RegularFieldsModel - fields = ('pk', 'char_field') + fields = ('auto_field', 'char_field') extra_kwargs = {'char_field': {'default': 'extra'}} expected = dedent(""" TestSerializer(): - pk = IntegerField(label='Auto field', read_only=True) + auto_field = IntegerField(read_only=True) char_field = CharField(default='extra', max_length=100) """) self.assertEqual(repr(TestSerializer()), expected) @@ -354,14 +360,12 @@ class TestIntegration(TestCase): self.instance.many_to_many = self.many_to_many_targets self.instance.save() + def test_pk_retrival(self): class TestSerializer(serializers.ModelSerializer): class Meta: model = RelationalModel - self.serializer_cls = TestSerializer - - def test_pk_retrival(self): - serializer = self.serializer_cls(self.instance) + serializer = TestSerializer(self.instance) expected = { 'id': self.instance.pk, 'foreign_key': self.foreign_key_target.pk, @@ -372,6 +376,10 @@ class TestIntegration(TestCase): self.assertEqual(serializer.data, expected) def test_pk_create(self): + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = RelationalModel + new_foreign_key = ForeignKeyTargetModel.objects.create( name='foreign_key' ) @@ -390,7 +398,7 @@ class TestIntegration(TestCase): } # Serializer should validate okay. - serializer = self.serializer_cls(data=data) + serializer = TestSerializer(data=data) assert serializer.is_valid() # Creating the instance, relationship attributes should be set. @@ -415,6 +423,10 @@ class TestIntegration(TestCase): self.assertEqual(serializer.data, expected) def test_pk_update(self): + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = RelationalModel + new_foreign_key = ForeignKeyTargetModel.objects.create( name='foreign_key' ) @@ -433,7 +445,7 @@ class TestIntegration(TestCase): } # Serializer should validate okay. - serializer = self.serializer_cls(self.instance, data=data) + serializer = TestSerializer(self.instance, data=data) assert serializer.is_valid() # Creating the instance, relationship attributes should be set. From 6d73b5969a9d415a6d43175e77bc10ba76151e97 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 19 Sep 2014 14:02:17 +0100 Subject: [PATCH 061/249] Initial release notes --- docs/topics/3.0-announcement.md | 239 ++++++++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 docs/topics/3.0-announcement.md diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md new file mode 100644 index 000000000..029d98960 --- /dev/null +++ b/docs/topics/3.0-announcement.md @@ -0,0 +1,239 @@ +**THIS DOCUMENT IS CURRENTLY A WORK IN PROGRESS** + +See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-framework/pull/1800) for more details. + +# REST framework 3.0 + +**Note incremental nature, discuss upgrading.** + +## Motivation + +**TODO** + +--- + +## Request objects + +#### The `request.data` property. + +**TODO** + +#### The parser API. + +**TODO** + +## Serializers + +#### Single-step object creation. + +**TODO**: Drop `.restore_object()`, use `.create()` and `.update()` which should save the instance. + +**TODO**: Drop`.object`, use `.validated_data` or get the instance with `.save()`. + +#### Always use `fields`, not `exclude`. + +The `exclude` option is no longer available. You should use the more explicit `fields` option instead. + +#### The `extra_kwargs` option. + +The `read_only_fields` and `write_only_fields` options have been removed and replaced with a more generic `extra_kwargs`. + + class MySerializer(serializer.ModelSerializer): + class Meta: + model = MyModel + fields = ('id', 'email', 'notes', 'is_admin') + extra_kwargs = { + 'is_admin': {'read_only': True} + } + +Alternatively, specify the field explicitly on the serializer class: + + class MySerializer(serializer.ModelSerializer): + is_admin = serializers.BooleanField(read_only=True) + + class Meta: + model = MyModel + fields = ('id', 'email', 'notes', 'is_admin') + +#### Changes to `HyperlinkedModelSerializer`. + +The `view_name` and `lookup_field` options have been removed. They are no longer required, as you can use the `extra_kwargs` argument instead: + + class MySerializer(serializer.HyperlinkedModelSerializer): + class Meta: + model = MyModel + fields = ('url', 'email', 'notes', 'is_admin') + extra_kwargs = { + 'url': {'lookup_field': 'uuid'} + } + +Alternatively, specify the field explicitly on the serializer class: + + class MySerializer(serializer.HyperlinkedModelSerializer): + url = serializers.HyperlinkedIdentityField( + view_name='mymodel-detail', + lookup_field='uuid' + ) + + class Meta: + model = MyModel + fields = ('url', 'email', 'notes', 'is_admin') + +#### Fields for model methods and properties. + +You can now specify field names in the `fields` option that refer to model methods or properties. For example, suppose you have the following model: + + class Invitation(models.Model): + created = models.DateTimeField() + to_email = models.EmailField() + message = models.CharField(max_length=1000) + + def expiry_date(self): + return self.created + datetime.timedelta(days=30) + +You can include `expiry_date` as a field option on a `ModelSerializer` class. + + class InvitationSerializer(serializers.ModelSerializer): + class Meta: + model = Invitation + fields = ('to_email', 'message', 'expiry_date') + +These fields will be mapped to `serializers.ReadOnlyField()` instances. + + >>> serializer = InvitationSerializer() + >>> print repr(serializer) + InvitationSerializer(): + to_email = EmailField(max_length=75) + message = CharField(max_length=1000) + expiry_date = ReadOnlyField() + + +## Serializer fields + +#### The `Field` and `ReadOnly` field classes. + +**TODO** + +#### Coercing output types. + +**TODO** + +#### The `ListSerializer` class. + +**TODO** + +#### The `MultipleChoiceField` class. + +**TODO** + +#### Changes to the custom field API. + +**TODO** `to_representation`, `to_internal_value`. + +#### Explicit `querysets` required on relational fields. + +**TODO** + +#### Optional argument to `SerializerMethodField`. + +**TODO** + +## Generic views + +#### Simplification of view logic. + +**TODO** + +#### Removal of pre/post save hooks. + +The following method hooks no longer exist on the new, simplified, generic views: `pre_save`, `post_save`, `pre_delete`, `post_delete`. + +If you do need custom behavior, you might choose to instead override the `.save()` method on your serializer class. For example: + + def save(self, *args, **kwargs): + instance = super(MySerializer).save(*args, **kwarg) + send_email(instance.to_email, instance.message) + return instance + +Alternatively write your view logic exlpicitly, or tie your pre/post save behavior into the model class or model manager. + +#### Removal of view attributes. + +The `.object` and `.object_list` attributes are no longer set on the view instance. Treating views as mutable object instances that store state during the processing of the view tends to be poor design, and can lead to obscure flow logic. + +I would personally recommend that developers treat view instances as immutable objects in their application code. + +#### PUT as create. + +**TODO** + +## API style + +There are some improvements in the default style we use in our API responses. + +#### Unicode JSON by default. + +Unicode JSON is now the default. The `UnicodeJSONRenderer` class no longer exists, and the `UNICODE_JSON` setting has been added. To revert this behavior use the new setting: + + REST_FRAMEWORK = { + 'UNICODE_JSON': False + } + +#### Compact JSON by default. + +We now output compact JSON in responses by default. For example, we return: + + {"email":"amy@example.com","is_admin":true} + +Instead of the following: + + {"email": "amy@example.com", "is_admin": true} + +The `COMPACT_JSON` setting has been added, and can be used to revert this behavior if needed: + + REST_FRAMEWORK = { + 'COMPACT_JSON': False + } + +#### Throttle headers using `Retry-After`. + +The custom `X-Throttle-Wait-Second` header has now been dropped in favor of the standard `Retry-After` header. You can revert this behavior if needed by writing a custom exception handler for your application. + +#### Date and time objects as ISO-8859-1 strings in serializer data. + +Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as `Date`, `Time` and `DateTime` objects, and later coerced to strings by the renderer. + +You can modify this behavior globally by settings the existing `DATE_FORMAT`, `DATETIME_FORMAT` and `TIME_FORMAT` settings keys. Setting these values to `None` instead of their default value of `'iso-8859-1'` will result in native objects being returned in serializer data. + + REST_FRAMEWORK = { + # Return native `Date` and `Time` objects in `serializer.data` + 'DATETIME_FORMAT': None + 'DATE_FORMAT': None + 'TIME_FORMAT': None + } + +You can also modify serializer fields individually, using the `date_format`, `time_format` and `datetime_format` arguments: + + # Return `DateTime` instances in `serializer.data`, not strings. + created = serializers.DateTimeField(format=None) + +#### Decimals as strings in serializer data. + +Decimals are now coerced to strings by default in the serializer output. Previously they were returned as `Decimal` objects, and later coerced to strings by the renderer. + +You can modify this behavior globally by using the `COERCE_DECIMAL_TO_STRING` settings key. + + REST_FRAMEWORK = { + 'COERCE_DECIMAL_TO_STRING': False + } + +Or modify it on an individual serializer field, using the `corece_to_string` keyword argument. + + # Return `Decimal` instances in `serializer.data`, not strings. + amount = serializers.DecimalField( + max_digits=10, + decimal_places=2, + coerce_to_string=False + ) + +The default JSON renderer will return float objects for uncoerced `Decimal` instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs. From c0150e619ca02a69d87c335a70c47644e9b2e509 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 19 Sep 2014 14:59:59 +0100 Subject: [PATCH 062/249] Add BaseSerializer heading --- docs/topics/3.0-announcement.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 029d98960..cd883cdd8 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -30,6 +30,10 @@ See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-fr **TODO**: Drop`.object`, use `.validated_data` or get the instance with `.save()`. +#### The `BaseSerializer` class. + +**TODO** + #### Always use `fields`, not `exclude`. The `exclude` option is no longer available. You should use the more explicit `fields` option instead. From b361c54c5c198583e5085cf49ef44291ec09d2e8 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 19 Sep 2014 15:46:32 +0100 Subject: [PATCH 063/249] Test rejigging --- tests/test_model_serializer.py | 5 +++ tests/test_modelinfo.py | 31 ---------------- tests/test_templatetags.py | 35 ++++++++++++++++++ tests/test_urlizer.py | 37 ------------------- tests/{test_breadcrumbs.py => test_utils.py} | 38 ++++++++++++++++++-- 5 files changed, 75 insertions(+), 71 deletions(-) delete mode 100644 tests/test_modelinfo.py delete mode 100644 tests/test_urlizer.py rename tests/{test_breadcrumbs.py => test_utils.py} (67%) diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index ec922b6d5..d518dd581 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -24,6 +24,9 @@ class CustomField(models.Field): pass +COLOR_CHOICES = (('red', 'Red'), ('blue', 'Blue'), ('green', 'Green')) + + class RegularFieldsModel(models.Model): """ A model class for testing regular flat fields. @@ -32,6 +35,7 @@ class RegularFieldsModel(models.Model): big_integer_field = models.BigIntegerField() boolean_field = models.BooleanField(default=False) char_field = models.CharField(max_length=100) + choices_field = models.CharField(max_length=100, choices=COLOR_CHOICES) comma_seperated_integer_field = models.CommaSeparatedIntegerField(max_length=100) date_field = models.DateField() datetime_field = models.DateTimeField() @@ -68,6 +72,7 @@ class TestRegularFieldMappings(TestCase): big_integer_field = IntegerField() boolean_field = BooleanField(default=False) char_field = CharField(max_length=100) + choices_field = ChoiceField(choices=[('red', 'Red'), ('blue', 'Blue'), ('green', 'Green')]) comma_seperated_integer_field = CharField(max_length=100, validators=[<django.core.validators.RegexValidator object>]) date_field = DateField() datetime_field = DateTimeField() diff --git a/tests/test_modelinfo.py b/tests/test_modelinfo.py deleted file mode 100644 index 04b67f041..000000000 --- a/tests/test_modelinfo.py +++ /dev/null @@ -1,31 +0,0 @@ -from django.test import TestCase -from django.utils import six -from rest_framework.utils.model_meta import _resolve_model -from tests.models import BasicModel - - -class ResolveModelTests(TestCase): - """ - `_resolve_model` should return a Django model class given the - provided argument is a Django model class itself, or a properly - formatted string representation of one. - """ - def test_resolve_django_model(self): - resolved_model = _resolve_model(BasicModel) - self.assertEqual(resolved_model, BasicModel) - - def test_resolve_string_representation(self): - resolved_model = _resolve_model('tests.BasicModel') - self.assertEqual(resolved_model, BasicModel) - - def test_resolve_unicode_representation(self): - resolved_model = _resolve_model(six.text_type('tests.BasicModel')) - self.assertEqual(resolved_model, BasicModel) - - def test_resolve_non_django_model(self): - with self.assertRaises(ValueError): - _resolve_model(TestCase) - - def test_resolve_improper_string_representation(self): - with self.assertRaises(ValueError): - _resolve_model('BasicModel') diff --git a/tests/test_templatetags.py b/tests/test_templatetags.py index 75ee0eaa8..b04a937e0 100644 --- a/tests/test_templatetags.py +++ b/tests/test_templatetags.py @@ -4,6 +4,7 @@ from django.test import TestCase from rest_framework.test import APIRequestFactory from rest_framework.templatetags.rest_framework import add_query_param, urlize_quoted_links + factory = APIRequestFactory() @@ -49,3 +50,37 @@ class Issue1386Tests(TestCase): # example from issue #1386, this shouldn't raise an exception urlize_quoted_links("asdf:[/p]zxcv.com") + + +class URLizerTests(TestCase): + """ + Test if both JSON and YAML URLs are transformed into links well + """ + def _urlize_dict_check(self, data): + """ + For all items in dict test assert that the value is urlized key + """ + for original, urlized in data.items(): + assert urlize_quoted_links(original, nofollow=False) == urlized + + def test_json_with_url(self): + """ + Test if JSON URLs are transformed into links well + """ + data = {} + data['"url": "http://api/users/1/", '] = \ + '"url": "<a href="http://api/users/1/">http://api/users/1/</a>", ' + data['"foo_set": [\n "http://api/foos/1/"\n], '] = \ + '"foo_set": [\n "<a href="http://api/foos/1/">http://api/foos/1/</a>"\n], ' + self._urlize_dict_check(data) + + def test_yaml_with_url(self): + """ + Test if YAML URLs are transformed into links well + """ + data = {} + data['''{users: 'http://api/users/'}'''] = \ + '''{users: '<a href="http://api/users/">http://api/users/</a>'}''' + data['''foo_set: ['http://api/foos/1/']'''] = \ + '''foo_set: ['<a href="http://api/foos/1/">http://api/foos/1/</a>']''' + self._urlize_dict_check(data) diff --git a/tests/test_urlizer.py b/tests/test_urlizer.py deleted file mode 100644 index a77aa22ab..000000000 --- a/tests/test_urlizer.py +++ /dev/null @@ -1,37 +0,0 @@ -from __future__ import unicode_literals -from django.test import TestCase -from rest_framework.templatetags.rest_framework import urlize_quoted_links - - -class URLizerTests(TestCase): - """ - Test if both JSON and YAML URLs are transformed into links well - """ - def _urlize_dict_check(self, data): - """ - For all items in dict test assert that the value is urlized key - """ - for original, urlized in data.items(): - assert urlize_quoted_links(original, nofollow=False) == urlized - - def test_json_with_url(self): - """ - Test if JSON URLs are transformed into links well - """ - data = {} - data['"url": "http://api/users/1/", '] = \ - '"url": "<a href="http://api/users/1/">http://api/users/1/</a>", ' - data['"foo_set": [\n "http://api/foos/1/"\n], '] = \ - '"foo_set": [\n "<a href="http://api/foos/1/">http://api/foos/1/</a>"\n], ' - self._urlize_dict_check(data) - - def test_yaml_with_url(self): - """ - Test if YAML URLs are transformed into links well - """ - data = {} - data['''{users: 'http://api/users/'}'''] = \ - '''{users: '<a href="http://api/users/">http://api/users/</a>'}''' - data['''foo_set: ['http://api/foos/1/']'''] = \ - '''foo_set: ['<a href="http://api/foos/1/">http://api/foos/1/</a>']''' - self._urlize_dict_check(data) diff --git a/tests/test_breadcrumbs.py b/tests/test_utils.py similarity index 67% rename from tests/test_breadcrumbs.py rename to tests/test_utils.py index 780fd5c4d..96c5f997e 100644 --- a/tests/test_breadcrumbs.py +++ b/tests/test_utils.py @@ -1,8 +1,11 @@ from __future__ import unicode_literals from django.conf.urls import patterns, url from django.test import TestCase +from django.utils import six +from rest_framework.utils.model_meta import _resolve_model from rest_framework.utils.breadcrumbs import get_breadcrumbs from rest_framework.views import APIView +from tests.models import BasicModel class Root(APIView): @@ -24,6 +27,7 @@ class NestedResourceRoot(APIView): class NestedResourceInstance(APIView): pass + urlpatterns = patterns( '', url(r'^$', Root.as_view()), @@ -35,9 +39,10 @@ urlpatterns = patterns( class BreadcrumbTests(TestCase): - """Tests the breadcrumb functionality used by the HTML renderer.""" - - urls = 'tests.test_breadcrumbs' + """ + Tests the breadcrumb functionality used by the HTML renderer. + """ + urls = 'tests.test_utils' def test_root_breadcrumbs(self): url = '/' @@ -98,3 +103,30 @@ class BreadcrumbTests(TestCase): get_breadcrumbs(url), [('Root', '/')] ) + + +class ResolveModelTests(TestCase): + """ + `_resolve_model` should return a Django model class given the + provided argument is a Django model class itself, or a properly + formatted string representation of one. + """ + def test_resolve_django_model(self): + resolved_model = _resolve_model(BasicModel) + self.assertEqual(resolved_model, BasicModel) + + def test_resolve_string_representation(self): + resolved_model = _resolve_model('tests.BasicModel') + self.assertEqual(resolved_model, BasicModel) + + def test_resolve_unicode_representation(self): + resolved_model = _resolve_model(six.text_type('tests.BasicModel')) + self.assertEqual(resolved_model, BasicModel) + + def test_resolve_non_django_model(self): + with self.assertRaises(ValueError): + _resolve_model(TestCase) + + def test_resolve_improper_string_representation(self): + with self.assertRaises(ValueError): + _resolve_model('BasicModel') From cf72b9a8b755652cec4ad19a27488e3a79c2e401 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 19 Sep 2014 16:43:13 +0100 Subject: [PATCH 064/249] Moar tests --- rest_framework/serializers.py | 2 ++ tests/test_model_serializer.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index d2740fc2a..d9f9c8cbc 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -24,6 +24,7 @@ from rest_framework.utils.field_mapping import ( lookup_class ) import copy +import inspect # Note: We do the following so that users of the framework can use this style: # @@ -268,6 +269,7 @@ class ListSerializer(BaseSerializer): 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.' self.context = kwargs.pop('context', {}) kwargs.pop('partial', None) diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index d518dd581..d9f9efbe7 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -473,3 +473,36 @@ class TestIntegration(TestCase): 'through': [] } self.assertEqual(serializer.data, expected) + + +# Tests for bulk create using `ListSerializer`. + +class BulkCreateModel(models.Model): + name = models.CharField(max_length=10) + + +class TestBulkCreate(TestCase): + def test_bulk_create(self): + class BasicModelSerializer(serializers.ModelSerializer): + class Meta: + model = BulkCreateModel + fields = ('name',) + + class BulkCreateSerializer(serializers.ListSerializer): + child = BasicModelSerializer() + + data = [{'name': 'a'}, {'name': 'b'}, {'name': 'c'}] + serializer = BulkCreateSerializer(data=data) + assert serializer.is_valid() + + # Objects are returned by save(). + instances = serializer.save() + assert len(instances) == 3 + assert [item.name for item in instances] == ['a', 'b', 'c'] + + # Objects have been created in the database. + assert BulkCreateModel.objects.count() == 3 + assert list(BulkCreateModel.objects.values_list('name', flat=True)) == ['a', 'b', 'c'] + + # Serializer returns correct data. + assert serializer.data == data From af46fd6b00f1d7f018049c19094af58acb1415fb Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 22 Sep 2014 12:25:57 +0100 Subject: [PATCH 065/249] Field tests and associated cleanup --- rest_framework/fields.py | 64 ++++---- tests/test_fields.py | 334 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 365 insertions(+), 33 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 0c78b3fbb..db75ddf91 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -12,7 +12,6 @@ from rest_framework.utils import html, representation, humanize_datetime import datetime import decimal import inspect -import warnings class empty: @@ -395,7 +394,7 @@ class IntegerField(Field): class FloatField(Field): default_error_messages = { - 'invalid': _("'%s' value must be a float."), + 'invalid': _("A valid number is required."), } def __init__(self, **kwargs): @@ -410,20 +409,20 @@ class FloatField(Field): def to_internal_value(self, value): if value is None: return None - return float(value) + try: + return float(value) + except (TypeError, ValueError): + self.fail('invalid') def to_representation(self, value): if value is None: return None - try: - return float(value) - except (TypeError, ValueError): - self.fail('invalid', value=value) + return float(value) class DecimalField(Field): default_error_messages = { - 'invalid': _('Enter a number.'), + 'invalid': _('A valid number is required.'), 'max_value': _('Ensure this value is less than or equal to {max_value}.'), 'min_value': _('Ensure this value is greater than or equal to {min_value}.'), 'max_digits': _('Ensure that there are no more than {max_digits} digits in total.'), @@ -485,7 +484,7 @@ class DecimalField(Field): if self.decimal_places is not None and decimals > self.decimal_places: self.fail('max_decimal_places', max_decimal_places=self.decimal_places) if self.max_digits is not None and self.decimal_places is not None and whole_digits > (self.max_digits - self.decimal_places): - self.fail('max_whole_digits', max_while_digits=self.max_digits - self.decimal_places) + self.fail('max_whole_digits', max_whole_digits=self.max_digits - self.decimal_places) return value @@ -511,6 +510,7 @@ class DecimalField(Field): class DateField(Field): default_error_messages = { 'invalid': _('Date has wrong format. Use one of these formats instead: {format}'), + 'datetime': _('Expected a date but got a datetime.'), } format = api_settings.DATE_FORMAT input_formats = api_settings.DATE_INPUT_FORMATS @@ -525,12 +525,7 @@ class DateField(Field): return None if isinstance(value, datetime.datetime): - if timezone and settings.USE_TZ and timezone.is_aware(value): - # Convert aware datetimes to the default time zone - # before casting them to dates (#17742). - default_timezone = timezone.get_default_timezone() - value = timezone.make_naive(value, default_timezone) - return value.date() + self.fail('datetime') if isinstance(value, datetime.date): return value @@ -570,35 +565,38 @@ class DateField(Field): class DateTimeField(Field): default_error_messages = { 'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}'), + 'date': _('Expected a datetime but got a date.'), } format = api_settings.DATETIME_FORMAT input_formats = api_settings.DATETIME_INPUT_FORMATS + default_timezone = timezone.get_default_timezone() if settings.USE_TZ else None - def __init__(self, format=None, input_formats=None, *args, **kwargs): + def __init__(self, format=None, input_formats=None, default_timezone=None, *args, **kwargs): self.format = format if format is not None else self.format self.input_formats = input_formats if input_formats is not None else self.input_formats + self.default_timezone = default_timezone if default_timezone is not None else self.default_timezone super(DateTimeField, self).__init__(*args, **kwargs) + def enforce_timezone(self, value): + """ + When `self.default_timezone` is `None`, always return naive datetimes. + When `self.default_timezone` is not `None`, always return aware datetimes. + """ + if (self.default_timezone is not None) and not timezone.is_aware(value): + return timezone.make_aware(value, self.default_timezone) + elif (self.default_timezone is None) and timezone.is_aware(value): + return timezone.make_naive(value, timezone.UTC()) + return value + def to_internal_value(self, value): if value in (None, ''): return None - if isinstance(value, datetime.datetime): - return value + if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime): + self.fail('date') - if isinstance(value, datetime.date): - value = datetime.datetime(value.year, value.month, value.day) - if settings.USE_TZ: - # For backwards compatibility, interpret naive datetimes in - # local time. This won't work during DST change, but we can't - # do much about it, so we let the exceptions percolate up the - # call stack. - warnings.warn("DateTimeField received a naive datetime (%s)" - " while time zone support is active." % value, - RuntimeWarning) - default_timezone = timezone.get_default_timezone() - value = timezone.make_aware(value, default_timezone) - return value + if isinstance(value, datetime.datetime): + return self.enforce_timezone(value) for format in self.input_formats: if format.lower() == ISO_8601: @@ -608,14 +606,14 @@ class DateTimeField(Field): pass else: if parsed is not None: - return parsed + return self.enforce_timezone(parsed) else: try: parsed = datetime.datetime.strptime(value, format) except (ValueError, TypeError): pass else: - return parsed + return self.enforce_timezone(parsed) humanized_format = humanize_datetime.datetime_formats(self.input_formats) self.fail('invalid', format=humanized_format) diff --git a/tests/test_fields.py b/tests/test_fields.py index a92fafbcb..6ec18041c 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1,3 +1,337 @@ +from decimal import Decimal +from django.utils import timezone +from rest_framework import fields +import datetime +import pytest + + +class ValidAndInvalidValues: + """ + Base class for testing valid and invalid field values. + """ + def test_valid_values(self): + """ + Ensure that valid values return the expected validated data. + """ + for input_value, expected_output in self.valid_mappings.items(): + assert self.field.run_validation(input_value) == expected_output + + def test_invalid_values(self): + """ + Ensure that invalid values raise the expected validation error. + """ + for input_value, expected_failure in self.invalid_mappings.items(): + with pytest.raises(fields.ValidationError) as exc_info: + self.field.run_validation(input_value) + assert exc_info.value.messages == expected_failure + + +class TestCharField(ValidAndInvalidValues): + valid_mappings = { + 1: '1', + 'abc': 'abc' + } + invalid_mappings = { + '': ['This field may not be blank.'] + } + field = fields.CharField() + + +class TestBooleanField(ValidAndInvalidValues): + valid_mappings = { + 'true': True, + 'false': False, + '1': True, + '0': False, + 1: True, + 0: False, + True: True, + False: False, + } + invalid_mappings = { + 'foo': ['`foo` is not a valid boolean.'] + } + field = fields.BooleanField() + + +# Number types... + +class TestIntegerField(ValidAndInvalidValues): + """ + Valid and invalid values for `IntegerField`. + """ + valid_mappings = { + '1': 1, + '0': 0, + 1: 1, + 0: 0, + 1.0: 1, + 0.0: 0 + } + invalid_mappings = { + 'abc': ['A valid integer is required.'] + } + field = fields.IntegerField() + + +class TestMinMaxIntegerField(ValidAndInvalidValues): + """ + Valid and invalid values for `IntegerField` with min and max limits. + """ + valid_mappings = { + '1': 1, + '3': 3, + 1: 1, + 3: 3, + } + invalid_mappings = { + 0: ['Ensure this value is greater than or equal to 1.'], + 4: ['Ensure this value is less than or equal to 3.'], + '0': ['Ensure this value is greater than or equal to 1.'], + '4': ['Ensure this value is less than or equal to 3.'], + } + field = fields.IntegerField(min_value=1, max_value=3) + + +class TestFloatField(ValidAndInvalidValues): + """ + Valid and invalid values for `FloatField`. + """ + valid_mappings = { + '1': 1.0, + '0': 0.0, + 1: 1.0, + 0: 0.0, + 1.0: 1.0, + 0.0: 0.0, + } + invalid_mappings = { + 'abc': ["A valid number is required."] + } + field = fields.FloatField() + + +class TestMinMaxFloatField(ValidAndInvalidValues): + """ + Valid and invalid values for `FloatField` with min and max limits. + """ + valid_mappings = { + '1': 1, + '3': 3, + 1: 1, + 3: 3, + 1.0: 1.0, + 3.0: 3.0, + } + invalid_mappings = { + 0.9: ['Ensure this value is greater than or equal to 1.'], + 3.1: ['Ensure this value is less than or equal to 3.'], + '0.0': ['Ensure this value is greater than or equal to 1.'], + '3.1': ['Ensure this value is less than or equal to 3.'], + } + field = fields.FloatField(min_value=1, max_value=3) + + +class TestDecimalField(ValidAndInvalidValues): + """ + Valid and invalid values for `DecimalField`. + """ + valid_mappings = { + '12.3': Decimal('12.3'), + '0.1': Decimal('0.1'), + 10: Decimal('10'), + 0: Decimal('0'), + 12.3: Decimal('12.3'), + 0.1: Decimal('0.1'), + } + invalid_mappings = { + 'abc': ["A valid number is required."], + Decimal('Nan'): ["A valid number is required."], + Decimal('Inf'): ["A valid number is required."], + '12.345': ["Ensure that there are no more than 3 digits in total."], + '0.01': ["Ensure that there are no more than 1 decimal places."], + 123: ["Ensure that there are no more than 2 digits before the decimal point."] + } + field = fields.DecimalField(max_digits=3, decimal_places=1) + + +class TestMinMaxDecimalField(ValidAndInvalidValues): + """ + Valid and invalid values for `DecimalField` with min and max limits. + """ + valid_mappings = { + '10.0': 10.0, + '20.0': 20.0, + } + invalid_mappings = { + '9.9': ['Ensure this value is greater than or equal to 10.'], + '20.1': ['Ensure this value is less than or equal to 20.'], + } + field = fields.DecimalField( + max_digits=3, decimal_places=1, + min_value=10, max_value=20 + ) + + +# Date & time fields... + +class TestDateField(ValidAndInvalidValues): + """ + Valid and invalid values for `DateField`. + """ + valid_mappings = { + '2001-01-01': datetime.date(2001, 1, 1), + datetime.date(2001, 1, 1): datetime.date(2001, 1, 1), + } + invalid_mappings = { + 'abc': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]'], + '2001-99-99': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]'], + datetime.datetime(2001, 1, 1, 12, 00): ['Expected a date but got a datetime.'], + } + field = fields.DateField() + + +class TestCustomInputFormatDateField(ValidAndInvalidValues): + """ + Valid and invalid values for `DateField` with a cutom input format. + """ + valid_mappings = { + '1 Jan 2001': datetime.date(2001, 1, 1), + } + invalid_mappings = { + '2001-01-01': ['Date has wrong format. Use one of these formats instead: DD [Jan-Dec] YYYY'] + } + field = fields.DateField(input_formats=['%d %b %Y']) + + +class TestDateTimeField(ValidAndInvalidValues): + """ + Valid and invalid values for `DateTimeField`. + """ + valid_mappings = { + '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), + '2001-01-01T13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), + '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), + '2001-01-01T14:00+0100': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), + datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), + datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), + } + invalid_mappings = { + 'abc': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'], + '2001-99-99T99:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'], + datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'], + } + field = fields.DateTimeField(default_timezone=timezone.UTC()) + + +class TestCustomInputFormatDateTimeField(ValidAndInvalidValues): + """ + Valid and invalid values for `DateTimeField` with a cutom input format. + """ + valid_mappings = { + '1:35pm, 1 Jan 2001': datetime.datetime(2001, 1, 1, 13, 35, tzinfo=timezone.UTC()), + } + invalid_mappings = { + '2001-01-01T20:50': ['Datetime has wrong format. Use one of these formats instead: hh:mm[AM|PM], DD [Jan-Dec] YYYY'] + } + field = fields.DateTimeField(default_timezone=timezone.UTC(), input_formats=['%I:%M%p, %d %b %Y']) + + +class TestNaiveDateTimeField(ValidAndInvalidValues): + """ + Valid and invalid values for `DateTimeField` with naive datetimes. + """ + valid_mappings = { + datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00), + '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00), + } + invalid_mappings = {} + field = fields.DateTimeField(default_timezone=None) + + +# Choice types... + +class TestChoiceField(ValidAndInvalidValues): + """ + Valid and invalid values for `ChoiceField`. + """ + valid_mappings = { + 'poor': 'poor', + 'medium': 'medium', + 'good': 'good', + } + invalid_mappings = { + 'awful': ['`awful` is not a valid choice.'] + } + field = fields.ChoiceField( + choices=[ + ('poor', 'Poor quality'), + ('medium', 'Medium quality'), + ('good', 'Good quality'), + ] + ) + + +class TestChoiceFieldWithType(ValidAndInvalidValues): + """ + Valid and invalid values for a `Choice` field that uses an integer type, + instead of a char type. + """ + valid_mappings = { + '1': 1, + 3: 3, + } + invalid_mappings = { + 5: ['`5` is not a valid choice.'], + 'abc': ['`abc` is not a valid choice.'] + } + field = fields.ChoiceField( + choices=[ + (1, 'Poor quality'), + (2, 'Medium quality'), + (3, 'Good quality'), + ] + ) + + +class TestChoiceFieldWithListChoices(ValidAndInvalidValues): + """ + Valid and invalid values for a `Choice` field that uses a flat list for the + choices, rather than a list of pairs of (`value`, `description`). + """ + valid_mappings = { + 'poor': 'poor', + 'medium': 'medium', + 'good': 'good', + } + invalid_mappings = { + 'awful': ['`awful` is not a valid choice.'] + } + field = fields.ChoiceField(choices=('poor', 'medium', 'good')) + + +class TestMultipleChoiceField(ValidAndInvalidValues): + """ + Valid and invalid values for `MultipleChoiceField`. + """ + valid_mappings = { + (): set(), + ('aircon',): set(['aircon']), + ('aircon', 'manual'): set(['aircon', 'manual']), + } + invalid_mappings = { + 'abc': ['Expected a list of items but got type `str`'], + ('aircon', 'incorrect'): ['`incorrect` is not a valid choice.'] + } + field = fields.MultipleChoiceField( + choices=[ + ('aircon', 'AirCon'), + ('manual', 'Manual drive'), + ('diesel', 'Diesel'), + ] + ) + + # """ # General serializer field tests. # """ From afb3f8ab0ad6c33b147292e9777ba0ddf3871d14 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 22 Sep 2014 13:26:47 +0100 Subject: [PATCH 066/249] Tests and tweaks for text fields --- rest_framework/fields.py | 32 ++++++++++---- tests/test_fields.py | 93 +++++++++++++++++++++++++++++++++++----- 2 files changed, 107 insertions(+), 18 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index db75ddf91..35bd5c4b4 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -12,6 +12,7 @@ from rest_framework.utils import html, representation, humanize_datetime import datetime import decimal import inspect +import re class empty: @@ -325,7 +326,11 @@ class EmailField(CharField): default_error_messages = { 'invalid': _('Enter a valid email address.') } - default_validators = [validators.validate_email] + + def __init__(self, **kwargs): + super(EmailField, self).__init__(**kwargs) + validator = validators.EmailValidator(message=self.error_messages['invalid']) + self.validators = [validator] + self.validators def to_internal_value(self, data): if data == '' and not self.allow_blank: @@ -341,26 +346,37 @@ class EmailField(CharField): class RegexField(CharField): + default_error_messages = { + 'invalid': _('This value does not match the required pattern.') + } + def __init__(self, regex, **kwargs): - kwargs['validators'] = ( - [validators.RegexValidator(regex)] + - kwargs.get('validators', []) - ) super(RegexField, self).__init__(**kwargs) + validator = validators.RegexValidator(regex, message=self.error_messages['invalid']) + self.validators = [validator] + self.validators class SlugField(CharField): default_error_messages = { 'invalid': _("Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.") } - default_validators = [validators.validate_slug] + + def __init__(self, **kwargs): + super(SlugField, self).__init__(**kwargs) + slug_regex = re.compile(r'^[-a-zA-Z0-9_]+$') + validator = validators.RegexValidator(slug_regex, message=self.error_messages['invalid']) + self.validators = [validator] + self.validators class URLField(CharField): default_error_messages = { 'invalid': _("Enter a valid URL.") } - default_validators = [validators.URLValidator()] + + def __init__(self, **kwargs): + super(URLField, self).__init__(**kwargs) + validator = validators.URLValidator(message=self.error_messages['invalid']) + self.validators = [validator] + self.validators # Number types... @@ -642,7 +658,7 @@ class TimeField(Field): self.input_formats = input_formats if input_formats is not None else self.input_formats super(TimeField, self).__init__(*args, **kwargs) - def from_native(self, value): + def to_internal_value(self, value): if value in (None, ''): return None diff --git a/tests/test_fields.py b/tests/test_fields.py index 6ec18041c..ae7f19193 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -26,16 +26,7 @@ class ValidAndInvalidValues: assert exc_info.value.messages == expected_failure -class TestCharField(ValidAndInvalidValues): - valid_mappings = { - 1: '1', - 'abc': 'abc' - } - invalid_mappings = { - '': ['This field may not be blank.'] - } - field = fields.CharField() - +# Boolean types... class TestBooleanField(ValidAndInvalidValues): valid_mappings = { @@ -54,6 +45,60 @@ class TestBooleanField(ValidAndInvalidValues): field = fields.BooleanField() +# String types... + +class TestCharField(ValidAndInvalidValues): + valid_mappings = { + 1: '1', + 'abc': 'abc' + } + invalid_mappings = { + '': ['This field may not be blank.'] + } + field = fields.CharField() + + +class TestEmailField(ValidAndInvalidValues): + valid_mappings = { + 'example@example.com': 'example@example.com', + ' example@example.com ': 'example@example.com', + } + invalid_mappings = { + 'example.com': ['Enter a valid email address.'] + } + field = fields.EmailField() + + +class TestRegexField(ValidAndInvalidValues): + valid_mappings = { + 'a9': 'a9', + } + invalid_mappings = { + 'A9': ["This value does not match the required pattern."] + } + field = fields.RegexField(regex='[a-z][0-9]') + + +class TestSlugField(ValidAndInvalidValues): + valid_mappings = { + 'slug-99': 'slug-99', + } + invalid_mappings = { + 'slug 99': ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."] + } + field = fields.SlugField() + + +class TestURLField(ValidAndInvalidValues): + valid_mappings = { + 'http://example.com': 'http://example.com', + } + invalid_mappings = { + 'example.com': ['Enter a valid URL.'] + } + field = fields.URLField() + + # Number types... class TestIntegerField(ValidAndInvalidValues): @@ -249,6 +294,34 @@ class TestNaiveDateTimeField(ValidAndInvalidValues): field = fields.DateTimeField(default_timezone=None) +class TestTimeField(ValidAndInvalidValues): + """ + Valid and invalid values for `TimeField`. + """ + valid_mappings = { + '13:00': datetime.time(13, 00), + datetime.time(13, 00): datetime.time(13, 00), + } + invalid_mappings = { + 'abc': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]'], + '99:99': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]'], + } + field = fields.TimeField() + + +class TestCustomInputFormatTimeField(ValidAndInvalidValues): + """ + Valid and invalid values for `TimeField` with a custom input format. + """ + valid_mappings = { + '1:00pm': datetime.time(13, 00), + } + invalid_mappings = { + '13:00': ['Time has wrong format. Use one of these formats instead: hh:mm[AM|PM]'], + } + field = fields.TimeField(input_formats=['%I:%M%p']) + + # Choice types... class TestChoiceField(ValidAndInvalidValues): From c54f394904c3f93211b8aa073de4e9e50110f831 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 22 Sep 2014 13:57:45 +0100 Subject: [PATCH 067/249] Ensure 'messages' in fields are respected in preference to default validator messages --- rest_framework/compat.py | 19 +++++++++++++++++++ rest_framework/fields.py | 34 ++++++++++++++++++++++------------ 2 files changed, 41 insertions(+), 12 deletions(-) diff --git a/rest_framework/compat.py b/rest_framework/compat.py index 7c05bed9c..2b4ddb021 100644 --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -121,6 +121,25 @@ else: return [m.upper() for m in self.http_method_names if hasattr(self, m)] + +# MinValueValidator and MaxValueValidator only accept `message` in 1.8+ +if django.VERSION >= (1, 8): + from django.core.validators import MinValueValidator, MaxValueValidator +else: + from django.core.validators import MinValueValidator as DjangoMinValueValidator + from django.core.validators import MaxValueValidator as DjangoMaxValueValidator + + class MinValueValidator(DjangoMinValueValidator): + def __init__(self, *args, **kwargs): + self.message = kwargs.pop('message', self.message) + super(MinValueValidator, self).__init__(*args, **kwargs) + + class MaxValueValidator(DjangoMaxValueValidator): + def __init__(self, *args, **kwargs): + self.message = kwargs.pop('message', self.message) + super(MaxValueValidator, self).__init__(*args, **kwargs) + + # PATCH method is not implemented by Django if 'patch' not in View.http_method_names: View.http_method_names = View.http_method_names + ['patch'] diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 35bd5c4b4..5105dfcb4 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -6,7 +6,7 @@ from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.encoding import is_protected_type from django.utils.translation import ugettext_lazy as _ from rest_framework import ISO_8601 -from rest_framework.compat import smart_text +from rest_framework.compat import smart_text, MinValueValidator, MaxValueValidator from rest_framework.settings import api_settings from rest_framework.utils import html, representation, humanize_datetime import datetime @@ -330,7 +330,7 @@ class EmailField(CharField): def __init__(self, **kwargs): super(EmailField, self).__init__(**kwargs) validator = validators.EmailValidator(message=self.error_messages['invalid']) - self.validators = [validator] + self.validators + self.validators.append(validator) def to_internal_value(self, data): if data == '' and not self.allow_blank: @@ -353,7 +353,7 @@ class RegexField(CharField): def __init__(self, regex, **kwargs): super(RegexField, self).__init__(**kwargs) validator = validators.RegexValidator(regex, message=self.error_messages['invalid']) - self.validators = [validator] + self.validators + self.validators.append(validator) class SlugField(CharField): @@ -365,7 +365,7 @@ class SlugField(CharField): super(SlugField, self).__init__(**kwargs) slug_regex = re.compile(r'^[-a-zA-Z0-9_]+$') validator = validators.RegexValidator(slug_regex, message=self.error_messages['invalid']) - self.validators = [validator] + self.validators + self.validators.append(validator) class URLField(CharField): @@ -376,14 +376,16 @@ class URLField(CharField): def __init__(self, **kwargs): super(URLField, self).__init__(**kwargs) validator = validators.URLValidator(message=self.error_messages['invalid']) - self.validators = [validator] + self.validators + self.validators.append(validator) # Number types... class IntegerField(Field): default_error_messages = { - 'invalid': _('A valid integer is required.') + 'invalid': _('A valid integer is required.'), + 'max_value': _('Ensure this value is less than or equal to {max_value}.'), + 'min_value': _('Ensure this value is greater than or equal to {min_value}.'), } def __init__(self, **kwargs): @@ -391,9 +393,11 @@ class IntegerField(Field): min_value = kwargs.pop('min_value', None) super(IntegerField, self).__init__(**kwargs) if max_value is not None: - self.validators.append(validators.MaxValueValidator(max_value)) + message = self.error_messages['max_value'].format(max_value=max_value) + self.validators.append(MaxValueValidator(max_value, message=message)) if min_value is not None: - self.validators.append(validators.MinValueValidator(min_value)) + message = self.error_messages['min_value'].format(min_value=min_value) + self.validators.append(MinValueValidator(min_value, message=message)) def to_internal_value(self, data): try: @@ -411,6 +415,8 @@ class IntegerField(Field): class FloatField(Field): default_error_messages = { 'invalid': _("A valid number is required."), + 'max_value': _('Ensure this value is less than or equal to {max_value}.'), + 'min_value': _('Ensure this value is greater than or equal to {min_value}.'), } def __init__(self, **kwargs): @@ -418,9 +424,11 @@ class FloatField(Field): min_value = kwargs.pop('min_value', None) super(FloatField, self).__init__(**kwargs) if max_value is not None: - self.validators.append(validators.MaxValueValidator(max_value)) + message = self.error_messages['max_value'].format(max_value=max_value) + self.validators.append(MaxValueValidator(max_value, message=message)) if min_value is not None: - self.validators.append(validators.MinValueValidator(min_value)) + message = self.error_messages['min_value'].format(min_value=min_value) + self.validators.append(MinValueValidator(min_value, message=message)) def to_internal_value(self, value): if value is None: @@ -454,9 +462,11 @@ class DecimalField(Field): self.coerce_to_string = coerce_to_string if (coerce_to_string is not None) else self.coerce_to_string super(DecimalField, self).__init__(**kwargs) if max_value is not None: - self.validators.append(validators.MaxValueValidator(max_value)) + message = self.error_messages['max_value'].format(max_value=max_value) + self.validators.append(MaxValueValidator(max_value, message=message)) if min_value is not None: - self.validators.append(validators.MinValueValidator(min_value)) + message = self.error_messages['min_value'].format(min_value=min_value) + self.validators.append(MinValueValidator(min_value, message=message)) def to_internal_value(self, value): """ From 249253a144ba4381581809fb3f27959c7bd6e577 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 22 Sep 2014 14:54:33 +0100 Subject: [PATCH 068/249] Fix compat issues --- rest_framework/fields.py | 13 ++++++++++--- tests/test_fields.py | 31 ++++++++++++++++++++----------- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 5105dfcb4..5fb99a42f 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -209,8 +209,10 @@ class Field(object): """ Validate a simple representation and return the internal value. - The provided data may be `empty` if no representation was included. - May return `empty` if the field should not be included in the + 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. """ if data is empty: @@ -223,6 +225,10 @@ class Field(object): return value def run_validators(self, value): + """ + Test the given value against all the validators on the field, + and either raise a `ValidationError` or simply return. + """ if value in (None, '', [], (), {}): return @@ -753,8 +759,9 @@ class MultipleChoiceField(ChoiceField): } def to_internal_value(self, data): - if not hasattr(data, '__iter__'): + if isinstance(data, type('')) or not hasattr(data, '__iter__'): self.fail('not_a_list', input_type=type(data).__name__) + return set([ super(MultipleChoiceField, self).to_internal_value(item) for item in data diff --git a/tests/test_fields.py b/tests/test_fields.py index ae7f19193..e03ece544 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -5,22 +5,31 @@ import datetime import pytest +def get_items(mapping_or_list_of_two_tuples): + # Tests accept either lists of two tuples, or dictionaries. + if isinstance(mapping_or_list_of_two_tuples, dict): + # {value: expected} + return mapping_or_list_of_two_tuples.items() + # [(value, expected), ...] + return mapping_or_list_of_two_tuples + + class ValidAndInvalidValues: """ - Base class for testing valid and invalid field values. + Base class for testing valid and invalid input values. """ def test_valid_values(self): """ Ensure that valid values return the expected validated data. """ - for input_value, expected_output in self.valid_mappings.items(): + for input_value, expected_output in get_items(self.valid_mappings): assert self.field.run_validation(input_value) == expected_output def test_invalid_values(self): """ Ensure that invalid values raise the expected validation error. """ - for input_value, expected_failure in self.invalid_mappings.items(): + for input_value, expected_failure in get_items(self.invalid_mappings): with pytest.raises(fields.ValidationError) as exc_info: self.field.run_validation(input_value) assert exc_info.value.messages == expected_failure @@ -189,14 +198,14 @@ class TestDecimalField(ValidAndInvalidValues): 12.3: Decimal('12.3'), 0.1: Decimal('0.1'), } - invalid_mappings = { - 'abc': ["A valid number is required."], - Decimal('Nan'): ["A valid number is required."], - Decimal('Inf'): ["A valid number is required."], - '12.345': ["Ensure that there are no more than 3 digits in total."], - '0.01': ["Ensure that there are no more than 1 decimal places."], - 123: ["Ensure that there are no more than 2 digits before the decimal point."] - } + invalid_mappings = ( + ('abc', ["A valid number is required."]), + (Decimal('Nan'), ["A valid number is required."]), + (Decimal('Inf'), ["A valid number is required."]), + ('12.345', ["Ensure that there are no more than 3 digits in total."]), + ('0.01', ["Ensure that there are no more than 1 decimal places."]), + (123, ["Ensure that there are no more than 2 digits before the decimal point."]) + ) field = fields.DecimalField(max_digits=3, decimal_places=1) From 4db23cae213decc3e8a8613ad5c76a545f8cfb1a Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 22 Sep 2014 15:34:06 +0100 Subject: [PATCH 069/249] Tweaks to DecimalField --- rest_framework/fields.py | 25 +++-- tests/test_fields.py | 233 ++++++++++++++++++++++++++------------- 2 files changed, 172 insertions(+), 86 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 5fb99a42f..db7ceabb1 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -521,20 +521,21 @@ class DecimalField(Field): return value def to_representation(self, value): - if isinstance(value, decimal.Decimal): - context = decimal.getcontext().copy() - context.prec = self.max_digits - quantized = value.quantize( - decimal.Decimal('.1') ** self.decimal_places, - context=context - ) - if not self.coerce_to_string: - return quantized - return '{0:f}'.format(quantized) + if value in (None, ''): + return None + if not isinstance(value, decimal.Decimal): + value = decimal.Decimal(value) + + context = decimal.getcontext().copy() + context.prec = self.max_digits + quantized = value.quantize( + decimal.Decimal('.1') ** self.decimal_places, + context=context + ) if not self.coerce_to_string: - return value - return '%.*f' % (self.max_decimal_places, value) + return quantized + return '{0:f}'.format(quantized) # Date & time fields... diff --git a/tests/test_fields.py b/tests/test_fields.py index e03ece544..0f445d415 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -14,31 +14,35 @@ def get_items(mapping_or_list_of_two_tuples): return mapping_or_list_of_two_tuples -class ValidAndInvalidValues: +class FieldValues: """ Base class for testing valid and invalid input values. """ - def test_valid_values(self): + def test_valid_inputs(self): """ Ensure that valid values return the expected validated data. """ - for input_value, expected_output in get_items(self.valid_mappings): + for input_value, expected_output in get_items(self.valid_inputs): assert self.field.run_validation(input_value) == expected_output - def test_invalid_values(self): + def test_invalid_inputs(self): """ Ensure that invalid values raise the expected validation error. """ - for input_value, expected_failure in get_items(self.invalid_mappings): + for input_value, expected_failure in get_items(self.invalid_inputs): with pytest.raises(fields.ValidationError) as exc_info: self.field.run_validation(input_value) assert exc_info.value.messages == expected_failure + def test_outputs(self): + for output_value, expected_output in get_items(self.outputs): + assert self.field.to_representation(output_value) == expected_output + # Boolean types... -class TestBooleanField(ValidAndInvalidValues): - valid_mappings = { +class TestBooleanField(FieldValues): + valid_inputs = { 'true': True, 'false': False, '1': True, @@ -48,73 +52,92 @@ class TestBooleanField(ValidAndInvalidValues): True: True, False: False, } - invalid_mappings = { + invalid_inputs = { 'foo': ['`foo` is not a valid boolean.'] } + outputs = { + 'true': True, + 'false': False, + '1': True, + '0': False, + 1: True, + 0: False, + True: True, + False: False, + 'other': True + } field = fields.BooleanField() # String types... -class TestCharField(ValidAndInvalidValues): - valid_mappings = { +class TestCharField(FieldValues): + valid_inputs = { 1: '1', 'abc': 'abc' } - invalid_mappings = { + invalid_inputs = { '': ['This field may not be blank.'] } + outputs = { + 1: '1', + 'abc': 'abc' + } field = fields.CharField() -class TestEmailField(ValidAndInvalidValues): - valid_mappings = { +class TestEmailField(FieldValues): + valid_inputs = { 'example@example.com': 'example@example.com', ' example@example.com ': 'example@example.com', } - invalid_mappings = { + invalid_inputs = { 'example.com': ['Enter a valid email address.'] } + outputs = {} field = fields.EmailField() -class TestRegexField(ValidAndInvalidValues): - valid_mappings = { +class TestRegexField(FieldValues): + valid_inputs = { 'a9': 'a9', } - invalid_mappings = { + invalid_inputs = { 'A9': ["This value does not match the required pattern."] } + outputs = {} field = fields.RegexField(regex='[a-z][0-9]') -class TestSlugField(ValidAndInvalidValues): - valid_mappings = { +class TestSlugField(FieldValues): + valid_inputs = { 'slug-99': 'slug-99', } - invalid_mappings = { + invalid_inputs = { 'slug 99': ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."] } + outputs = {} field = fields.SlugField() -class TestURLField(ValidAndInvalidValues): - valid_mappings = { +class TestURLField(FieldValues): + valid_inputs = { 'http://example.com': 'http://example.com', } - invalid_mappings = { + invalid_inputs = { 'example.com': ['Enter a valid URL.'] } + outputs = {} field = fields.URLField() # Number types... -class TestIntegerField(ValidAndInvalidValues): +class TestIntegerField(FieldValues): """ Valid and invalid values for `IntegerField`. """ - valid_mappings = { + valid_inputs = { '1': 1, '0': 0, 1: 1, @@ -122,36 +145,45 @@ class TestIntegerField(ValidAndInvalidValues): 1.0: 1, 0.0: 0 } - invalid_mappings = { + invalid_inputs = { 'abc': ['A valid integer is required.'] } + outputs = { + '1': 1, + '0': 0, + 1: 1, + 0: 0, + 1.0: 1, + 0.0: 0 + } field = fields.IntegerField() -class TestMinMaxIntegerField(ValidAndInvalidValues): +class TestMinMaxIntegerField(FieldValues): """ Valid and invalid values for `IntegerField` with min and max limits. """ - valid_mappings = { + valid_inputs = { '1': 1, '3': 3, 1: 1, 3: 3, } - invalid_mappings = { + invalid_inputs = { 0: ['Ensure this value is greater than or equal to 1.'], 4: ['Ensure this value is less than or equal to 3.'], '0': ['Ensure this value is greater than or equal to 1.'], '4': ['Ensure this value is less than or equal to 3.'], } + outputs = {} field = fields.IntegerField(min_value=1, max_value=3) -class TestFloatField(ValidAndInvalidValues): +class TestFloatField(FieldValues): """ Valid and invalid values for `FloatField`. """ - valid_mappings = { + valid_inputs = { '1': 1.0, '0': 0.0, 1: 1.0, @@ -159,17 +191,25 @@ class TestFloatField(ValidAndInvalidValues): 1.0: 1.0, 0.0: 0.0, } - invalid_mappings = { + invalid_inputs = { 'abc': ["A valid number is required."] } + outputs = { + '1': 1.0, + '0': 0.0, + 1: 1.0, + 0: 0.0, + 1.0: 1.0, + 0.0: 0.0, + } field = fields.FloatField() -class TestMinMaxFloatField(ValidAndInvalidValues): +class TestMinMaxFloatField(FieldValues): """ Valid and invalid values for `FloatField` with min and max limits. """ - valid_mappings = { + valid_inputs = { '1': 1, '3': 3, 1: 1, @@ -177,20 +217,21 @@ class TestMinMaxFloatField(ValidAndInvalidValues): 1.0: 1.0, 3.0: 3.0, } - invalid_mappings = { + invalid_inputs = { 0.9: ['Ensure this value is greater than or equal to 1.'], 3.1: ['Ensure this value is less than or equal to 3.'], '0.0': ['Ensure this value is greater than or equal to 1.'], '3.1': ['Ensure this value is less than or equal to 3.'], } + outputs = {} field = fields.FloatField(min_value=1, max_value=3) -class TestDecimalField(ValidAndInvalidValues): +class TestDecimalField(FieldValues): """ Valid and invalid values for `DecimalField`. """ - valid_mappings = { + valid_inputs = { '12.3': Decimal('12.3'), '0.1': Decimal('0.1'), 10: Decimal('10'), @@ -198,7 +239,7 @@ class TestDecimalField(ValidAndInvalidValues): 12.3: Decimal('12.3'), 0.1: Decimal('0.1'), } - invalid_mappings = ( + invalid_inputs = ( ('abc', ["A valid number is required."]), (Decimal('Nan'), ["A valid number is required."]), (Decimal('Inf'), ["A valid number is required."]), @@ -206,63 +247,98 @@ class TestDecimalField(ValidAndInvalidValues): ('0.01', ["Ensure that there are no more than 1 decimal places."]), (123, ["Ensure that there are no more than 2 digits before the decimal point."]) ) + outputs = { + '1': '1.0', + '0': '0.0', + '1.09': '1.1', + '0.04': '0.0', + 1: '1.0', + 0: '0.0', + Decimal('1.0'): '1.0', + Decimal('0.0'): '0.0', + Decimal('1.09'): '1.1', + Decimal('0.04'): '0.0', + } field = fields.DecimalField(max_digits=3, decimal_places=1) -class TestMinMaxDecimalField(ValidAndInvalidValues): +class TestMinMaxDecimalField(FieldValues): """ Valid and invalid values for `DecimalField` with min and max limits. """ - valid_mappings = { + valid_inputs = { '10.0': 10.0, '20.0': 20.0, } - invalid_mappings = { + invalid_inputs = { '9.9': ['Ensure this value is greater than or equal to 10.'], '20.1': ['Ensure this value is less than or equal to 20.'], } + outputs = {} field = fields.DecimalField( max_digits=3, decimal_places=1, min_value=10, max_value=20 ) +class TestNoStringCoercionDecimalField(FieldValues): + """ + Output values for `DecimalField` with `coerce_to_string=False`. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + 1.09: Decimal('1.1'), + 0.04: Decimal('0.0'), + '1.09': Decimal('1.1'), + '0.04': Decimal('0.0'), + Decimal('1.09'): Decimal('1.1'), + Decimal('0.04'): Decimal('0.0'), + } + field = fields.DecimalField( + max_digits=3, decimal_places=1, + coerce_to_string=False + ) + + # Date & time fields... -class TestDateField(ValidAndInvalidValues): +class TestDateField(FieldValues): """ Valid and invalid values for `DateField`. """ - valid_mappings = { + valid_inputs = { '2001-01-01': datetime.date(2001, 1, 1), datetime.date(2001, 1, 1): datetime.date(2001, 1, 1), } - invalid_mappings = { + invalid_inputs = { 'abc': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]'], '2001-99-99': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]'], datetime.datetime(2001, 1, 1, 12, 00): ['Expected a date but got a datetime.'], } + outputs = {} field = fields.DateField() -class TestCustomInputFormatDateField(ValidAndInvalidValues): +class TestCustomInputFormatDateField(FieldValues): """ Valid and invalid values for `DateField` with a cutom input format. """ - valid_mappings = { + valid_inputs = { '1 Jan 2001': datetime.date(2001, 1, 1), } - invalid_mappings = { + invalid_inputs = { '2001-01-01': ['Date has wrong format. Use one of these formats instead: DD [Jan-Dec] YYYY'] } + outputs = {} field = fields.DateField(input_formats=['%d %b %Y']) -class TestDateTimeField(ValidAndInvalidValues): +class TestDateTimeField(FieldValues): """ Valid and invalid values for `DateTimeField`. """ - valid_mappings = { + valid_inputs = { '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), '2001-01-01T13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), @@ -270,81 +346,87 @@ class TestDateTimeField(ValidAndInvalidValues): datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), } - invalid_mappings = { + invalid_inputs = { 'abc': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'], '2001-99-99T99:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'], datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'], } + outputs = {} field = fields.DateTimeField(default_timezone=timezone.UTC()) -class TestCustomInputFormatDateTimeField(ValidAndInvalidValues): +class TestCustomInputFormatDateTimeField(FieldValues): """ Valid and invalid values for `DateTimeField` with a cutom input format. """ - valid_mappings = { + valid_inputs = { '1:35pm, 1 Jan 2001': datetime.datetime(2001, 1, 1, 13, 35, tzinfo=timezone.UTC()), } - invalid_mappings = { + invalid_inputs = { '2001-01-01T20:50': ['Datetime has wrong format. Use one of these formats instead: hh:mm[AM|PM], DD [Jan-Dec] YYYY'] } + outputs = {} field = fields.DateTimeField(default_timezone=timezone.UTC(), input_formats=['%I:%M%p, %d %b %Y']) -class TestNaiveDateTimeField(ValidAndInvalidValues): +class TestNaiveDateTimeField(FieldValues): """ Valid and invalid values for `DateTimeField` with naive datetimes. """ - valid_mappings = { + valid_inputs = { datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00), '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00), } - invalid_mappings = {} + invalid_inputs = {} + outputs = {} field = fields.DateTimeField(default_timezone=None) -class TestTimeField(ValidAndInvalidValues): +class TestTimeField(FieldValues): """ Valid and invalid values for `TimeField`. """ - valid_mappings = { + valid_inputs = { '13:00': datetime.time(13, 00), datetime.time(13, 00): datetime.time(13, 00), } - invalid_mappings = { + invalid_inputs = { 'abc': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]'], '99:99': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]'], } + outputs = {} field = fields.TimeField() -class TestCustomInputFormatTimeField(ValidAndInvalidValues): +class TestCustomInputFormatTimeField(FieldValues): """ Valid and invalid values for `TimeField` with a custom input format. """ - valid_mappings = { + valid_inputs = { '1:00pm': datetime.time(13, 00), } - invalid_mappings = { + invalid_inputs = { '13:00': ['Time has wrong format. Use one of these formats instead: hh:mm[AM|PM]'], } + outputs = {} field = fields.TimeField(input_formats=['%I:%M%p']) # Choice types... -class TestChoiceField(ValidAndInvalidValues): +class TestChoiceField(FieldValues): """ Valid and invalid values for `ChoiceField`. """ - valid_mappings = { + valid_inputs = { 'poor': 'poor', 'medium': 'medium', 'good': 'good', } - invalid_mappings = { + invalid_inputs = { 'awful': ['`awful` is not a valid choice.'] } + outputs = {} field = fields.ChoiceField( choices=[ ('poor', 'Poor quality'), @@ -354,19 +436,20 @@ class TestChoiceField(ValidAndInvalidValues): ) -class TestChoiceFieldWithType(ValidAndInvalidValues): +class TestChoiceFieldWithType(FieldValues): """ Valid and invalid values for a `Choice` field that uses an integer type, instead of a char type. """ - valid_mappings = { + valid_inputs = { '1': 1, 3: 3, } - invalid_mappings = { + invalid_inputs = { 5: ['`5` is not a valid choice.'], 'abc': ['`abc` is not a valid choice.'] } + outputs = {} field = fields.ChoiceField( choices=[ (1, 'Poor quality'), @@ -376,35 +459,37 @@ class TestChoiceFieldWithType(ValidAndInvalidValues): ) -class TestChoiceFieldWithListChoices(ValidAndInvalidValues): +class TestChoiceFieldWithListChoices(FieldValues): """ Valid and invalid values for a `Choice` field that uses a flat list for the choices, rather than a list of pairs of (`value`, `description`). """ - valid_mappings = { + valid_inputs = { 'poor': 'poor', 'medium': 'medium', 'good': 'good', } - invalid_mappings = { + invalid_inputs = { 'awful': ['`awful` is not a valid choice.'] } + outputs = {} field = fields.ChoiceField(choices=('poor', 'medium', 'good')) -class TestMultipleChoiceField(ValidAndInvalidValues): +class TestMultipleChoiceField(FieldValues): """ Valid and invalid values for `MultipleChoiceField`. """ - valid_mappings = { + valid_inputs = { (): set(), ('aircon',): set(['aircon']), ('aircon', 'manual'): set(['aircon', 'manual']), } - invalid_mappings = { + invalid_inputs = { 'abc': ['Expected a list of items but got type `str`'], ('aircon', 'incorrect'): ['`incorrect` is not a valid choice.'] } + outputs = {} field = fields.MultipleChoiceField( choices=[ ('aircon', 'AirCon'), From 5586b6581d9d8db05276c08f2c6deffec04ade4f Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 22 Sep 2014 16:02:59 +0100 Subject: [PATCH 070/249] Support format=None for date/time fields --- rest_framework/fields.py | 12 +++--- tests/test_fields.py | 85 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 88 insertions(+), 9 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index db7ceabb1..cbd3334a3 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -548,8 +548,8 @@ class DateField(Field): format = api_settings.DATE_FORMAT input_formats = api_settings.DATE_INPUT_FORMATS - def __init__(self, format=None, input_formats=None, *args, **kwargs): - self.format = format if format is not None else self.format + def __init__(self, format=empty, input_formats=None, *args, **kwargs): + self.format = format if format is not empty else self.format self.input_formats = input_formats if input_formats is not None else self.input_formats super(DateField, self).__init__(*args, **kwargs) @@ -604,8 +604,8 @@ class DateTimeField(Field): input_formats = api_settings.DATETIME_INPUT_FORMATS default_timezone = timezone.get_default_timezone() if settings.USE_TZ else None - def __init__(self, format=None, input_formats=None, default_timezone=None, *args, **kwargs): - self.format = format if format is not None else self.format + def __init__(self, format=empty, input_formats=None, default_timezone=None, *args, **kwargs): + self.format = format if format is not empty else self.format self.input_formats = input_formats if input_formats is not None else self.input_formats self.default_timezone = default_timezone if default_timezone is not None else self.default_timezone super(DateTimeField, self).__init__(*args, **kwargs) @@ -670,8 +670,8 @@ class TimeField(Field): format = api_settings.TIME_FORMAT input_formats = api_settings.TIME_INPUT_FORMATS - def __init__(self, format=None, input_formats=None, *args, **kwargs): - self.format = format if format is not None else self.format + def __init__(self, format=empty, input_formats=None, *args, **kwargs): + self.format = format if format is not empty else self.format self.input_formats = input_formats if input_formats is not None else self.input_formats super(TimeField, self).__init__(*args, **kwargs) diff --git a/tests/test_fields.py b/tests/test_fields.py index 0f445d415..b221089ce 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -316,7 +316,9 @@ class TestDateField(FieldValues): '2001-99-99': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]'], datetime.datetime(2001, 1, 1, 12, 00): ['Expected a date but got a datetime.'], } - outputs = {} + outputs = { + datetime.date(2001, 1, 1): '2001-01-01', + } field = fields.DateField() @@ -334,6 +336,30 @@ class TestCustomInputFormatDateField(FieldValues): field = fields.DateField(input_formats=['%d %b %Y']) +class TestCustomOutputFormatDateField(FieldValues): + """ + Values for `DateField` with a custom output format. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + datetime.date(2001, 1, 1): '01 Jan 2001' + } + field = fields.DateField(format='%d %b %Y') + + +class TestNoOutputFormatDateField(FieldValues): + """ + Values for `DateField` with no output format. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + datetime.date(2001, 1, 1): datetime.date(2001, 1, 1) + } + field = fields.DateField(format=None) + + class TestDateTimeField(FieldValues): """ Valid and invalid values for `DateTimeField`. @@ -351,7 +377,10 @@ class TestDateTimeField(FieldValues): '2001-99-99T99:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'], datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'], } - outputs = {} + 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', + } field = fields.DateTimeField(default_timezone=timezone.UTC()) @@ -369,6 +398,30 @@ class TestCustomInputFormatDateTimeField(FieldValues): field = fields.DateTimeField(default_timezone=timezone.UTC(), input_formats=['%I:%M%p, %d %b %Y']) +class TestCustomOutputFormatDateTimeField(FieldValues): + """ + Values for `DateTimeField` with a custom output format. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + datetime.datetime(2001, 1, 1, 13, 00): '01:00PM, 01 Jan 2001', + } + field = fields.DateTimeField(format='%I:%M%p, %d %b %Y') + + +class TestNoOutputFormatDateTimeField(FieldValues): + """ + Values for `DateTimeField` with no output format. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00), + } + field = fields.DateTimeField(format=None) + + class TestNaiveDateTimeField(FieldValues): """ Valid and invalid values for `DateTimeField` with naive datetimes. @@ -394,7 +447,9 @@ class TestTimeField(FieldValues): 'abc': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]'], '99:99': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]'], } - outputs = {} + outputs = { + datetime.time(13, 00): '13:00:00' + } field = fields.TimeField() @@ -412,6 +467,30 @@ class TestCustomInputFormatTimeField(FieldValues): field = fields.TimeField(input_formats=['%I:%M%p']) +class TestCustomOutputFormatTimeField(FieldValues): + """ + Values for `TimeField` with a custom output format. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + datetime.time(13, 00): '01:00PM' + } + field = fields.TimeField(format='%I:%M%p') + + +class TestNoOutputFormatTimeField(FieldValues): + """ + Values for `TimeField` with a no output format. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + datetime.time(13, 00): datetime.time(13, 00) + } + field = fields.TimeField(format=None) + + # Choice types... class TestChoiceField(FieldValues): From e5f0a97595ff9280c7876fc917f6feb27b5ea95d Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 22 Sep 2014 16:45:06 +0100 Subject: [PATCH 071/249] More compat fixes --- rest_framework/compat.py | 23 +++++++++++++++++++++++ rest_framework/fields.py | 8 ++++---- tests/test_fields.py | 10 ++++++---- 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/rest_framework/compat.py b/rest_framework/compat.py index 2b4ddb021..7303c32a6 100644 --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -139,6 +139,29 @@ else: self.message = kwargs.pop('message', self.message) super(MaxValueValidator, self).__init__(*args, **kwargs) +# URLValidator only accept `message` in 1.6+ +if django.VERSION >= (1, 6): + from django.core.validators import URLValidator +else: + from django.core.validators import URLValidator as DjangoURLValidator + + class URLValidator(DjangoURLValidator): + def __init__(self, *args, **kwargs): + self.message = kwargs.pop('message', self.message) + super(URLValidator, self).__init__(*args, **kwargs) + + +# EmailValidator requires explicit regex prior to 1.6+ +if django.VERSION >= (1, 6): + from django.core.validators import EmailValidator +else: + from django.core.validators import EmailValidator as DjangoEmailValidator + from django.core.validators import email_re + + class EmailValidator(DjangoEmailValidator): + def __init__(self, *args, **kwargs): + super(EmailValidator, self).__init__(email_re, *args, **kwargs) + # PATCH method is not implemented by Django if 'patch' not in View.http_method_names: diff --git a/rest_framework/fields.py b/rest_framework/fields.py index cbd3334a3..12975ae49 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -6,7 +6,7 @@ from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.encoding import is_protected_type from django.utils.translation import ugettext_lazy as _ from rest_framework import ISO_8601 -from rest_framework.compat import smart_text, MinValueValidator, MaxValueValidator +from rest_framework.compat import smart_text, EmailValidator, MinValueValidator, MaxValueValidator, URLValidator from rest_framework.settings import api_settings from rest_framework.utils import html, representation, humanize_datetime import datetime @@ -335,7 +335,7 @@ class EmailField(CharField): def __init__(self, **kwargs): super(EmailField, self).__init__(**kwargs) - validator = validators.EmailValidator(message=self.error_messages['invalid']) + validator = EmailValidator(message=self.error_messages['invalid']) self.validators.append(validator) def to_internal_value(self, data): @@ -381,7 +381,7 @@ class URLField(CharField): def __init__(self, **kwargs): super(URLField, self).__init__(**kwargs) - validator = validators.URLValidator(message=self.error_messages['invalid']) + validator = URLValidator(message=self.error_messages['invalid']) self.validators.append(validator) @@ -525,7 +525,7 @@ class DecimalField(Field): return None if not isinstance(value, decimal.Decimal): - value = decimal.Decimal(value) + value = decimal.Decimal(str(value).strip()) context = decimal.getcontext().copy() context.prec = self.max_digits diff --git a/tests/test_fields.py b/tests/test_fields.py index b221089ce..8c50aaba6 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -2,6 +2,7 @@ from decimal import Decimal from django.utils import timezone from rest_framework import fields import datetime +import django import pytest @@ -92,7 +93,7 @@ class TestEmailField(FieldValues): ' example@example.com ': 'example@example.com', } invalid_inputs = { - 'example.com': ['Enter a valid email address.'] + 'examplecom': ['Enter a valid email address.'] } outputs = {} field = fields.EmailField() @@ -267,8 +268,8 @@ class TestMinMaxDecimalField(FieldValues): Valid and invalid values for `DecimalField` with min and max limits. """ valid_inputs = { - '10.0': 10.0, - '20.0': 20.0, + '10.0': Decimal('10.0'), + '20.0': Decimal('20.0'), } invalid_inputs = { '9.9': ['Ensure this value is greater than or equal to 10.'], @@ -368,9 +369,10 @@ class TestDateTimeField(FieldValues): '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), '2001-01-01T13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), - '2001-01-01T14:00+0100': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), + # Note that 1.4 does not support timezone string parsing. + '2001-01-01T14:00+01:00' if (django.VERSION > (1, 4)) else '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()) } invalid_inputs = { 'abc': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'], From b5454dd02290130a7fb0a0e375f3efecc58edc6d Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 22 Sep 2014 16:50:04 +0100 Subject: [PATCH 072/249] Tests and tweaks for choice fields --- rest_framework/fields.py | 4 ++-- tests/test_fields.py | 15 +++++++++++---- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 12975ae49..500018f3d 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -750,7 +750,7 @@ class ChoiceField(Field): self.fail('invalid_choice', input=data) def to_representation(self, value): - return value + return self.choice_strings_to_values[str(value)] class MultipleChoiceField(ChoiceField): @@ -769,7 +769,7 @@ class MultipleChoiceField(ChoiceField): ]) def to_representation(self, value): - return value + return [self.choice_strings_to_values[str(item)] for item in value] # File types... diff --git a/tests/test_fields.py b/tests/test_fields.py index 8c50aaba6..3343123f4 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -505,9 +505,11 @@ class TestChoiceField(FieldValues): 'good': 'good', } invalid_inputs = { - 'awful': ['`awful` is not a valid choice.'] + 'amazing': ['`amazing` is not a valid choice.'] + } + outputs = { + 'good': 'good' } - outputs = {} field = fields.ChoiceField( choices=[ ('poor', 'Poor quality'), @@ -530,7 +532,10 @@ class TestChoiceFieldWithType(FieldValues): 5: ['`5` is not a valid choice.'], 'abc': ['`abc` is not a valid choice.'] } - outputs = {} + outputs = { + '1': 1, + 1: 1 + } field = fields.ChoiceField( choices=[ (1, 'Poor quality'), @@ -553,7 +558,9 @@ class TestChoiceFieldWithListChoices(FieldValues): invalid_inputs = { 'awful': ['`awful` is not a valid choice.'] } - outputs = {} + outputs = { + 'good': 'good' + } field = fields.ChoiceField(choices=('poor', 'medium', 'good')) From 5a95baf2a2258fb5297062ac18582129c05fb320 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 22 Sep 2014 16:52:57 +0100 Subject: [PATCH 073/249] Tests & tweaks for ChoiceField --- rest_framework/fields.py | 4 +++- tests/test_fields.py | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 500018f3d..80eadf1e8 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -769,7 +769,9 @@ class MultipleChoiceField(ChoiceField): ]) def to_representation(self, value): - return [self.choice_strings_to_values[str(item)] for item in value] + return set([ + self.choice_strings_to_values[str(item)] for item in value + ]) # File types... diff --git a/tests/test_fields.py b/tests/test_fields.py index 3343123f4..3cfc1b88f 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -577,7 +577,9 @@ class TestMultipleChoiceField(FieldValues): 'abc': ['Expected a list of items but got type `str`'], ('aircon', 'incorrect'): ['`incorrect` is not a valid choice.'] } - outputs = {} + outputs = [ + (['aircon', 'manual'], set(['aircon', 'manual'])) + ] field = fields.MultipleChoiceField( choices=[ ('aircon', 'AirCon'), From 5d80f7f932bfcc0630ac0fdbf07072a53197b98f Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 22 Sep 2014 17:46:02 +0100 Subject: [PATCH 074/249] allow_blank, allow_null --- rest_framework/fields.py | 40 +- tests/test_field_options.py | 55 ++ tests/test_field_values.py | 607 +++++++++++++ tests/test_fields.py | 1633 ----------------------------------- 4 files changed, 678 insertions(+), 1657 deletions(-) create mode 100644 tests/test_field_options.py create mode 100644 tests/test_field_values.py delete mode 100644 tests/test_fields.py diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 80eadf1e8..48a3e1ab9 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -98,14 +98,15 @@ class Field(object): _creation_counter = 0 default_error_messages = { - 'required': _('This field is required.') + 'required': _('This field is required.'), + 'null': _('This field may not be null.') } default_validators = [] def __init__(self, read_only=False, write_only=False, required=None, default=empty, initial=None, source=None, label=None, help_text=None, style=None, - error_messages=None, validators=[]): + error_messages=None, validators=[], allow_null=False): self._creation_counter = Field._creation_counter Field._creation_counter += 1 @@ -129,6 +130,7 @@ class Field(object): self.help_text = help_text self.style = {} if style is None else style self.validators = validators or self.default_validators[:] + self.allow_null = allow_null # Collect default error message from self and parent classes messages = {} @@ -220,6 +222,11 @@ class Field(object): self.fail('required') return self.get_default() + if data is None: + if not self.allow_null: + self.fail('null') + return None + value = self.to_internal_value(data) self.run_validators(value) return value @@ -315,11 +322,14 @@ class CharField(Field): self.min_length = kwargs.pop('min_length', None) super(CharField, self).__init__(**kwargs) + def run_validation(self, data=empty): + if data == '': + if not self.allow_blank: + self.fail('blank') + return '' + return super(CharField, self).run_validation(data) + def to_internal_value(self, data): - if data == '' and not self.allow_blank: - self.fail('blank') - if data is None: - return None return str(data) def to_representation(self, value): @@ -339,10 +349,6 @@ class EmailField(CharField): self.validators.append(validator) def to_internal_value(self, data): - if data == '' and not self.allow_blank: - self.fail('blank') - if data is None: - return None return str(data).strip() def to_representation(self, value): @@ -437,8 +443,6 @@ class FloatField(Field): self.validators.append(MinValueValidator(min_value, message=message)) def to_internal_value(self, value): - if value is None: - return None try: return float(value) except (TypeError, ValueError): @@ -481,9 +485,6 @@ class DecimalField(Field): than max_digits in the number, and no more than decimal_places digits after the decimal point. """ - if value in (None, ''): - return None - value = smart_text(value).strip() try: value = decimal.Decimal(value) @@ -554,9 +555,6 @@ class DateField(Field): super(DateField, self).__init__(*args, **kwargs) def to_internal_value(self, value): - if value in (None, ''): - return None - if isinstance(value, datetime.datetime): self.fail('datetime') @@ -622,9 +620,6 @@ class DateTimeField(Field): return value def to_internal_value(self, value): - if value in (None, ''): - return None - if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime): self.fail('date') @@ -676,9 +671,6 @@ class TimeField(Field): super(TimeField, self).__init__(*args, **kwargs) def to_internal_value(self, value): - if value in (None, ''): - return None - if isinstance(value, datetime.time): return value diff --git a/tests/test_field_options.py b/tests/test_field_options.py new file mode 100644 index 000000000..444bd4248 --- /dev/null +++ b/tests/test_field_options.py @@ -0,0 +1,55 @@ +from rest_framework import fields +import pytest + + +class TestFieldOptions: + def test_required(self): + """ + By default a field must be included in the input. + """ + field = fields.IntegerField() + with pytest.raises(fields.ValidationError) as exc_info: + field.run_validation() + assert exc_info.value.messages == ['This field is required.'] + + def test_not_required(self): + """ + If `required=False` then a field may be omitted from the input. + """ + field = fields.IntegerField(required=False) + with pytest.raises(fields.SkipField): + field.run_validation() + + def test_disallow_null(self): + """ + By default `None` is not a valid input. + """ + field = fields.IntegerField() + with pytest.raises(fields.ValidationError) as exc_info: + field.run_validation(None) + assert exc_info.value.messages == ['This field may not be null.'] + + def test_allow_null(self): + """ + If `allow_null=True` then `None` is a valid input. + """ + field = fields.IntegerField(allow_null=True) + output = field.run_validation(None) + assert output is None + + def test_disallow_blank(self): + """ + By default '' is not a valid input. + """ + field = fields.CharField() + with pytest.raises(fields.ValidationError) as exc_info: + field.run_validation('') + assert exc_info.value.messages == ['This field may not be blank.'] + + def test_allow_blank(self): + """ + If `allow_blank=True` then '' is a valid input. + """ + field = fields.CharField(allow_blank=True) + output = field.run_validation('') + assert output is '' diff --git a/tests/test_field_values.py b/tests/test_field_values.py new file mode 100644 index 000000000..bac50f0bc --- /dev/null +++ b/tests/test_field_values.py @@ -0,0 +1,607 @@ +from decimal import Decimal +from django.utils import timezone +from rest_framework import fields +import datetime +import django +import pytest + + +def get_items(mapping_or_list_of_two_tuples): + # Tests accept either lists of two tuples, or dictionaries. + if isinstance(mapping_or_list_of_two_tuples, dict): + # {value: expected} + return mapping_or_list_of_two_tuples.items() + # [(value, expected), ...] + return mapping_or_list_of_two_tuples + + +class FieldValues: + """ + Base class for testing valid and invalid input values. + """ + def test_valid_inputs(self): + """ + Ensure that valid values return the expected validated data. + """ + for input_value, expected_output in get_items(self.valid_inputs): + assert self.field.run_validation(input_value) == expected_output + + def test_invalid_inputs(self): + """ + Ensure that invalid values raise the expected validation error. + """ + for input_value, expected_failure in get_items(self.invalid_inputs): + with pytest.raises(fields.ValidationError) as exc_info: + self.field.run_validation(input_value) + assert exc_info.value.messages == expected_failure + + def test_outputs(self): + for output_value, expected_output in get_items(self.outputs): + assert self.field.to_representation(output_value) == expected_output + + +# Boolean types... + +class TestBooleanField(FieldValues): + """ + Valid and invalid values for `BooleanField`. + """ + valid_inputs = { + 'true': True, + 'false': False, + '1': True, + '0': False, + 1: True, + 0: False, + True: True, + False: False, + } + invalid_inputs = { + 'foo': ['`foo` is not a valid boolean.'] + } + outputs = { + 'true': True, + 'false': False, + '1': True, + '0': False, + 1: True, + 0: False, + True: True, + False: False, + 'other': True + } + field = fields.BooleanField() + + +# String types... + +class TestCharField(FieldValues): + """ + Valid and invalid values for `CharField`. + """ + valid_inputs = { + 1: '1', + 'abc': 'abc' + } + invalid_inputs = { + '': ['This field may not be blank.'] + } + outputs = { + 1: '1', + 'abc': 'abc' + } + field = fields.CharField() + + +class TestEmailField(FieldValues): + """ + Valid and invalid values for `EmailField`. + """ + valid_inputs = { + 'example@example.com': 'example@example.com', + ' example@example.com ': 'example@example.com', + } + invalid_inputs = { + 'examplecom': ['Enter a valid email address.'] + } + outputs = {} + field = fields.EmailField() + + +class TestRegexField(FieldValues): + """ + Valid and invalid values for `RegexField`. + """ + valid_inputs = { + 'a9': 'a9', + } + invalid_inputs = { + 'A9': ["This value does not match the required pattern."] + } + outputs = {} + field = fields.RegexField(regex='[a-z][0-9]') + + +class TestSlugField(FieldValues): + """ + Valid and invalid values for `SlugField`. + """ + valid_inputs = { + 'slug-99': 'slug-99', + } + invalid_inputs = { + 'slug 99': ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."] + } + outputs = {} + field = fields.SlugField() + + +class TestURLField(FieldValues): + """ + Valid and invalid values for `URLField`. + """ + valid_inputs = { + 'http://example.com': 'http://example.com', + } + invalid_inputs = { + 'example.com': ['Enter a valid URL.'] + } + outputs = {} + field = fields.URLField() + + +# Number types... + +class TestIntegerField(FieldValues): + """ + Valid and invalid values for `IntegerField`. + """ + valid_inputs = { + '1': 1, + '0': 0, + 1: 1, + 0: 0, + 1.0: 1, + 0.0: 0 + } + invalid_inputs = { + 'abc': ['A valid integer is required.'] + } + outputs = { + '1': 1, + '0': 0, + 1: 1, + 0: 0, + 1.0: 1, + 0.0: 0 + } + field = fields.IntegerField() + + +class TestMinMaxIntegerField(FieldValues): + """ + Valid and invalid values for `IntegerField` with min and max limits. + """ + valid_inputs = { + '1': 1, + '3': 3, + 1: 1, + 3: 3, + } + invalid_inputs = { + 0: ['Ensure this value is greater than or equal to 1.'], + 4: ['Ensure this value is less than or equal to 3.'], + '0': ['Ensure this value is greater than or equal to 1.'], + '4': ['Ensure this value is less than or equal to 3.'], + } + outputs = {} + field = fields.IntegerField(min_value=1, max_value=3) + + +class TestFloatField(FieldValues): + """ + Valid and invalid values for `FloatField`. + """ + valid_inputs = { + '1': 1.0, + '0': 0.0, + 1: 1.0, + 0: 0.0, + 1.0: 1.0, + 0.0: 0.0, + } + invalid_inputs = { + 'abc': ["A valid number is required."] + } + outputs = { + '1': 1.0, + '0': 0.0, + 1: 1.0, + 0: 0.0, + 1.0: 1.0, + 0.0: 0.0, + } + field = fields.FloatField() + + +class TestMinMaxFloatField(FieldValues): + """ + Valid and invalid values for `FloatField` with min and max limits. + """ + valid_inputs = { + '1': 1, + '3': 3, + 1: 1, + 3: 3, + 1.0: 1.0, + 3.0: 3.0, + } + invalid_inputs = { + 0.9: ['Ensure this value is greater than or equal to 1.'], + 3.1: ['Ensure this value is less than or equal to 3.'], + '0.0': ['Ensure this value is greater than or equal to 1.'], + '3.1': ['Ensure this value is less than or equal to 3.'], + } + outputs = {} + field = fields.FloatField(min_value=1, max_value=3) + + +class TestDecimalField(FieldValues): + """ + Valid and invalid values for `DecimalField`. + """ + valid_inputs = { + '12.3': Decimal('12.3'), + '0.1': Decimal('0.1'), + 10: Decimal('10'), + 0: Decimal('0'), + 12.3: Decimal('12.3'), + 0.1: Decimal('0.1'), + } + invalid_inputs = ( + ('abc', ["A valid number is required."]), + (Decimal('Nan'), ["A valid number is required."]), + (Decimal('Inf'), ["A valid number is required."]), + ('12.345', ["Ensure that there are no more than 3 digits in total."]), + ('0.01', ["Ensure that there are no more than 1 decimal places."]), + (123, ["Ensure that there are no more than 2 digits before the decimal point."]) + ) + outputs = { + '1': '1.0', + '0': '0.0', + '1.09': '1.1', + '0.04': '0.0', + 1: '1.0', + 0: '0.0', + Decimal('1.0'): '1.0', + Decimal('0.0'): '0.0', + Decimal('1.09'): '1.1', + Decimal('0.04'): '0.0', + } + field = fields.DecimalField(max_digits=3, decimal_places=1) + + +class TestMinMaxDecimalField(FieldValues): + """ + Valid and invalid values for `DecimalField` with min and max limits. + """ + valid_inputs = { + '10.0': Decimal('10.0'), + '20.0': Decimal('20.0'), + } + invalid_inputs = { + '9.9': ['Ensure this value is greater than or equal to 10.'], + '20.1': ['Ensure this value is less than or equal to 20.'], + } + outputs = {} + field = fields.DecimalField( + max_digits=3, decimal_places=1, + min_value=10, max_value=20 + ) + + +class TestNoStringCoercionDecimalField(FieldValues): + """ + Output values for `DecimalField` with `coerce_to_string=False`. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + 1.09: Decimal('1.1'), + 0.04: Decimal('0.0'), + '1.09': Decimal('1.1'), + '0.04': Decimal('0.0'), + Decimal('1.09'): Decimal('1.1'), + Decimal('0.04'): Decimal('0.0'), + } + field = fields.DecimalField( + max_digits=3, decimal_places=1, + coerce_to_string=False + ) + + +# Date & time fields... + +class TestDateField(FieldValues): + """ + Valid and invalid values for `DateField`. + """ + valid_inputs = { + '2001-01-01': datetime.date(2001, 1, 1), + datetime.date(2001, 1, 1): datetime.date(2001, 1, 1), + } + invalid_inputs = { + 'abc': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]'], + '2001-99-99': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]'], + datetime.datetime(2001, 1, 1, 12, 00): ['Expected a date but got a datetime.'], + } + outputs = { + datetime.date(2001, 1, 1): '2001-01-01', + } + field = fields.DateField() + + +class TestCustomInputFormatDateField(FieldValues): + """ + Valid and invalid values for `DateField` with a cutom input format. + """ + valid_inputs = { + '1 Jan 2001': datetime.date(2001, 1, 1), + } + invalid_inputs = { + '2001-01-01': ['Date has wrong format. Use one of these formats instead: DD [Jan-Dec] YYYY'] + } + outputs = {} + field = fields.DateField(input_formats=['%d %b %Y']) + + +class TestCustomOutputFormatDateField(FieldValues): + """ + Values for `DateField` with a custom output format. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + datetime.date(2001, 1, 1): '01 Jan 2001' + } + field = fields.DateField(format='%d %b %Y') + + +class TestNoOutputFormatDateField(FieldValues): + """ + Values for `DateField` with no output format. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + datetime.date(2001, 1, 1): datetime.date(2001, 1, 1) + } + field = fields.DateField(format=None) + + +class TestDateTimeField(FieldValues): + """ + Valid and invalid values for `DateTimeField`. + """ + valid_inputs = { + '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), + '2001-01-01T13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), + '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), + datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), + datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), + # Note that 1.4 does not support timezone string parsing. + '2001-01-01T14:00+01:00' if (django.VERSION > (1, 4)) else '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()) + } + invalid_inputs = { + 'abc': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'], + '2001-99-99T99:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'], + datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'], + } + outputs = { + datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00', + datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): '2001-01-01T13:00:00Z', + } + field = fields.DateTimeField(default_timezone=timezone.UTC()) + + +class TestCustomInputFormatDateTimeField(FieldValues): + """ + Valid and invalid values for `DateTimeField` with a cutom input format. + """ + valid_inputs = { + '1:35pm, 1 Jan 2001': datetime.datetime(2001, 1, 1, 13, 35, tzinfo=timezone.UTC()), + } + invalid_inputs = { + '2001-01-01T20:50': ['Datetime has wrong format. Use one of these formats instead: hh:mm[AM|PM], DD [Jan-Dec] YYYY'] + } + outputs = {} + field = fields.DateTimeField(default_timezone=timezone.UTC(), input_formats=['%I:%M%p, %d %b %Y']) + + +class TestCustomOutputFormatDateTimeField(FieldValues): + """ + Values for `DateTimeField` with a custom output format. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + datetime.datetime(2001, 1, 1, 13, 00): '01:00PM, 01 Jan 2001', + } + field = fields.DateTimeField(format='%I:%M%p, %d %b %Y') + + +class TestNoOutputFormatDateTimeField(FieldValues): + """ + Values for `DateTimeField` with no output format. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00), + } + field = fields.DateTimeField(format=None) + + +class TestNaiveDateTimeField(FieldValues): + """ + Valid and invalid values for `DateTimeField` with naive datetimes. + """ + valid_inputs = { + datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00), + '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00), + } + invalid_inputs = {} + outputs = {} + field = fields.DateTimeField(default_timezone=None) + + +class TestTimeField(FieldValues): + """ + Valid and invalid values for `TimeField`. + """ + valid_inputs = { + '13:00': datetime.time(13, 00), + datetime.time(13, 00): datetime.time(13, 00), + } + invalid_inputs = { + 'abc': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]'], + '99:99': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]'], + } + outputs = { + datetime.time(13, 00): '13:00:00' + } + field = fields.TimeField() + + +class TestCustomInputFormatTimeField(FieldValues): + """ + Valid and invalid values for `TimeField` with a custom input format. + """ + valid_inputs = { + '1:00pm': datetime.time(13, 00), + } + invalid_inputs = { + '13:00': ['Time has wrong format. Use one of these formats instead: hh:mm[AM|PM]'], + } + outputs = {} + field = fields.TimeField(input_formats=['%I:%M%p']) + + +class TestCustomOutputFormatTimeField(FieldValues): + """ + Values for `TimeField` with a custom output format. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + datetime.time(13, 00): '01:00PM' + } + field = fields.TimeField(format='%I:%M%p') + + +class TestNoOutputFormatTimeField(FieldValues): + """ + Values for `TimeField` with a no output format. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = { + datetime.time(13, 00): datetime.time(13, 00) + } + field = fields.TimeField(format=None) + + +# Choice types... + +class TestChoiceField(FieldValues): + """ + Valid and invalid values for `ChoiceField`. + """ + valid_inputs = { + 'poor': 'poor', + 'medium': 'medium', + 'good': 'good', + } + invalid_inputs = { + 'amazing': ['`amazing` is not a valid choice.'] + } + outputs = { + 'good': 'good' + } + field = fields.ChoiceField( + choices=[ + ('poor', 'Poor quality'), + ('medium', 'Medium quality'), + ('good', 'Good quality'), + ] + ) + + +class TestChoiceFieldWithType(FieldValues): + """ + Valid and invalid values for a `Choice` field that uses an integer type, + instead of a char type. + """ + valid_inputs = { + '1': 1, + 3: 3, + } + invalid_inputs = { + 5: ['`5` is not a valid choice.'], + 'abc': ['`abc` is not a valid choice.'] + } + outputs = { + '1': 1, + 1: 1 + } + field = fields.ChoiceField( + choices=[ + (1, 'Poor quality'), + (2, 'Medium quality'), + (3, 'Good quality'), + ] + ) + + +class TestChoiceFieldWithListChoices(FieldValues): + """ + Valid and invalid values for a `Choice` field that uses a flat 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 = fields.ChoiceField(choices=('poor', 'medium', 'good')) + + +class TestMultipleChoiceField(FieldValues): + """ + Valid and invalid values for `MultipleChoiceField`. + """ + valid_inputs = { + (): set(), + ('aircon',): set(['aircon']), + ('aircon', 'manual'): set(['aircon', 'manual']), + } + invalid_inputs = { + 'abc': ['Expected a list of items but got type `str`'], + ('aircon', 'incorrect'): ['`incorrect` is not a valid choice.'] + } + outputs = [ + (['aircon', 'manual'], set(['aircon', 'manual'])) + ] + field = fields.MultipleChoiceField( + choices=[ + ('aircon', 'AirCon'), + ('manual', 'Manual drive'), + ('diesel', 'Diesel'), + ] + ) diff --git a/tests/test_fields.py b/tests/test_fields.py deleted file mode 100644 index 3cfc1b88f..000000000 --- a/tests/test_fields.py +++ /dev/null @@ -1,1633 +0,0 @@ -from decimal import Decimal -from django.utils import timezone -from rest_framework import fields -import datetime -import django -import pytest - - -def get_items(mapping_or_list_of_two_tuples): - # Tests accept either lists of two tuples, or dictionaries. - if isinstance(mapping_or_list_of_two_tuples, dict): - # {value: expected} - return mapping_or_list_of_two_tuples.items() - # [(value, expected), ...] - return mapping_or_list_of_two_tuples - - -class FieldValues: - """ - Base class for testing valid and invalid input values. - """ - def test_valid_inputs(self): - """ - Ensure that valid values return the expected validated data. - """ - for input_value, expected_output in get_items(self.valid_inputs): - assert self.field.run_validation(input_value) == expected_output - - def test_invalid_inputs(self): - """ - Ensure that invalid values raise the expected validation error. - """ - for input_value, expected_failure in get_items(self.invalid_inputs): - with pytest.raises(fields.ValidationError) as exc_info: - self.field.run_validation(input_value) - assert exc_info.value.messages == expected_failure - - def test_outputs(self): - for output_value, expected_output in get_items(self.outputs): - assert self.field.to_representation(output_value) == expected_output - - -# Boolean types... - -class TestBooleanField(FieldValues): - valid_inputs = { - 'true': True, - 'false': False, - '1': True, - '0': False, - 1: True, - 0: False, - True: True, - False: False, - } - invalid_inputs = { - 'foo': ['`foo` is not a valid boolean.'] - } - outputs = { - 'true': True, - 'false': False, - '1': True, - '0': False, - 1: True, - 0: False, - True: True, - False: False, - 'other': True - } - field = fields.BooleanField() - - -# String types... - -class TestCharField(FieldValues): - valid_inputs = { - 1: '1', - 'abc': 'abc' - } - invalid_inputs = { - '': ['This field may not be blank.'] - } - outputs = { - 1: '1', - 'abc': 'abc' - } - field = fields.CharField() - - -class TestEmailField(FieldValues): - valid_inputs = { - 'example@example.com': 'example@example.com', - ' example@example.com ': 'example@example.com', - } - invalid_inputs = { - 'examplecom': ['Enter a valid email address.'] - } - outputs = {} - field = fields.EmailField() - - -class TestRegexField(FieldValues): - valid_inputs = { - 'a9': 'a9', - } - invalid_inputs = { - 'A9': ["This value does not match the required pattern."] - } - outputs = {} - field = fields.RegexField(regex='[a-z][0-9]') - - -class TestSlugField(FieldValues): - valid_inputs = { - 'slug-99': 'slug-99', - } - invalid_inputs = { - 'slug 99': ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."] - } - outputs = {} - field = fields.SlugField() - - -class TestURLField(FieldValues): - valid_inputs = { - 'http://example.com': 'http://example.com', - } - invalid_inputs = { - 'example.com': ['Enter a valid URL.'] - } - outputs = {} - field = fields.URLField() - - -# Number types... - -class TestIntegerField(FieldValues): - """ - Valid and invalid values for `IntegerField`. - """ - valid_inputs = { - '1': 1, - '0': 0, - 1: 1, - 0: 0, - 1.0: 1, - 0.0: 0 - } - invalid_inputs = { - 'abc': ['A valid integer is required.'] - } - outputs = { - '1': 1, - '0': 0, - 1: 1, - 0: 0, - 1.0: 1, - 0.0: 0 - } - field = fields.IntegerField() - - -class TestMinMaxIntegerField(FieldValues): - """ - Valid and invalid values for `IntegerField` with min and max limits. - """ - valid_inputs = { - '1': 1, - '3': 3, - 1: 1, - 3: 3, - } - invalid_inputs = { - 0: ['Ensure this value is greater than or equal to 1.'], - 4: ['Ensure this value is less than or equal to 3.'], - '0': ['Ensure this value is greater than or equal to 1.'], - '4': ['Ensure this value is less than or equal to 3.'], - } - outputs = {} - field = fields.IntegerField(min_value=1, max_value=3) - - -class TestFloatField(FieldValues): - """ - Valid and invalid values for `FloatField`. - """ - valid_inputs = { - '1': 1.0, - '0': 0.0, - 1: 1.0, - 0: 0.0, - 1.0: 1.0, - 0.0: 0.0, - } - invalid_inputs = { - 'abc': ["A valid number is required."] - } - outputs = { - '1': 1.0, - '0': 0.0, - 1: 1.0, - 0: 0.0, - 1.0: 1.0, - 0.0: 0.0, - } - field = fields.FloatField() - - -class TestMinMaxFloatField(FieldValues): - """ - Valid and invalid values for `FloatField` with min and max limits. - """ - valid_inputs = { - '1': 1, - '3': 3, - 1: 1, - 3: 3, - 1.0: 1.0, - 3.0: 3.0, - } - invalid_inputs = { - 0.9: ['Ensure this value is greater than or equal to 1.'], - 3.1: ['Ensure this value is less than or equal to 3.'], - '0.0': ['Ensure this value is greater than or equal to 1.'], - '3.1': ['Ensure this value is less than or equal to 3.'], - } - outputs = {} - field = fields.FloatField(min_value=1, max_value=3) - - -class TestDecimalField(FieldValues): - """ - Valid and invalid values for `DecimalField`. - """ - valid_inputs = { - '12.3': Decimal('12.3'), - '0.1': Decimal('0.1'), - 10: Decimal('10'), - 0: Decimal('0'), - 12.3: Decimal('12.3'), - 0.1: Decimal('0.1'), - } - invalid_inputs = ( - ('abc', ["A valid number is required."]), - (Decimal('Nan'), ["A valid number is required."]), - (Decimal('Inf'), ["A valid number is required."]), - ('12.345', ["Ensure that there are no more than 3 digits in total."]), - ('0.01', ["Ensure that there are no more than 1 decimal places."]), - (123, ["Ensure that there are no more than 2 digits before the decimal point."]) - ) - outputs = { - '1': '1.0', - '0': '0.0', - '1.09': '1.1', - '0.04': '0.0', - 1: '1.0', - 0: '0.0', - Decimal('1.0'): '1.0', - Decimal('0.0'): '0.0', - Decimal('1.09'): '1.1', - Decimal('0.04'): '0.0', - } - field = fields.DecimalField(max_digits=3, decimal_places=1) - - -class TestMinMaxDecimalField(FieldValues): - """ - Valid and invalid values for `DecimalField` with min and max limits. - """ - valid_inputs = { - '10.0': Decimal('10.0'), - '20.0': Decimal('20.0'), - } - invalid_inputs = { - '9.9': ['Ensure this value is greater than or equal to 10.'], - '20.1': ['Ensure this value is less than or equal to 20.'], - } - outputs = {} - field = fields.DecimalField( - max_digits=3, decimal_places=1, - min_value=10, max_value=20 - ) - - -class TestNoStringCoercionDecimalField(FieldValues): - """ - Output values for `DecimalField` with `coerce_to_string=False`. - """ - valid_inputs = {} - invalid_inputs = {} - outputs = { - 1.09: Decimal('1.1'), - 0.04: Decimal('0.0'), - '1.09': Decimal('1.1'), - '0.04': Decimal('0.0'), - Decimal('1.09'): Decimal('1.1'), - Decimal('0.04'): Decimal('0.0'), - } - field = fields.DecimalField( - max_digits=3, decimal_places=1, - coerce_to_string=False - ) - - -# Date & time fields... - -class TestDateField(FieldValues): - """ - Valid and invalid values for `DateField`. - """ - valid_inputs = { - '2001-01-01': datetime.date(2001, 1, 1), - datetime.date(2001, 1, 1): datetime.date(2001, 1, 1), - } - invalid_inputs = { - 'abc': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]'], - '2001-99-99': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]'], - datetime.datetime(2001, 1, 1, 12, 00): ['Expected a date but got a datetime.'], - } - outputs = { - datetime.date(2001, 1, 1): '2001-01-01', - } - field = fields.DateField() - - -class TestCustomInputFormatDateField(FieldValues): - """ - Valid and invalid values for `DateField` with a cutom input format. - """ - valid_inputs = { - '1 Jan 2001': datetime.date(2001, 1, 1), - } - invalid_inputs = { - '2001-01-01': ['Date has wrong format. Use one of these formats instead: DD [Jan-Dec] YYYY'] - } - outputs = {} - field = fields.DateField(input_formats=['%d %b %Y']) - - -class TestCustomOutputFormatDateField(FieldValues): - """ - Values for `DateField` with a custom output format. - """ - valid_inputs = {} - invalid_inputs = {} - outputs = { - datetime.date(2001, 1, 1): '01 Jan 2001' - } - field = fields.DateField(format='%d %b %Y') - - -class TestNoOutputFormatDateField(FieldValues): - """ - Values for `DateField` with no output format. - """ - valid_inputs = {} - invalid_inputs = {} - outputs = { - datetime.date(2001, 1, 1): datetime.date(2001, 1, 1) - } - field = fields.DateField(format=None) - - -class TestDateTimeField(FieldValues): - """ - Valid and invalid values for `DateTimeField`. - """ - valid_inputs = { - '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), - '2001-01-01T13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), - '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), - datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), - datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), - # Note that 1.4 does not support timezone string parsing. - '2001-01-01T14:00+01:00' if (django.VERSION > (1, 4)) else '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()) - } - invalid_inputs = { - 'abc': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'], - '2001-99-99T99:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'], - datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'], - } - outputs = { - datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00', - datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): '2001-01-01T13:00:00Z', - } - field = fields.DateTimeField(default_timezone=timezone.UTC()) - - -class TestCustomInputFormatDateTimeField(FieldValues): - """ - Valid and invalid values for `DateTimeField` with a cutom input format. - """ - valid_inputs = { - '1:35pm, 1 Jan 2001': datetime.datetime(2001, 1, 1, 13, 35, tzinfo=timezone.UTC()), - } - invalid_inputs = { - '2001-01-01T20:50': ['Datetime has wrong format. Use one of these formats instead: hh:mm[AM|PM], DD [Jan-Dec] YYYY'] - } - outputs = {} - field = fields.DateTimeField(default_timezone=timezone.UTC(), input_formats=['%I:%M%p, %d %b %Y']) - - -class TestCustomOutputFormatDateTimeField(FieldValues): - """ - Values for `DateTimeField` with a custom output format. - """ - valid_inputs = {} - invalid_inputs = {} - outputs = { - datetime.datetime(2001, 1, 1, 13, 00): '01:00PM, 01 Jan 2001', - } - field = fields.DateTimeField(format='%I:%M%p, %d %b %Y') - - -class TestNoOutputFormatDateTimeField(FieldValues): - """ - Values for `DateTimeField` with no output format. - """ - valid_inputs = {} - invalid_inputs = {} - outputs = { - datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00), - } - field = fields.DateTimeField(format=None) - - -class TestNaiveDateTimeField(FieldValues): - """ - Valid and invalid values for `DateTimeField` with naive datetimes. - """ - valid_inputs = { - datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00), - '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00), - } - invalid_inputs = {} - outputs = {} - field = fields.DateTimeField(default_timezone=None) - - -class TestTimeField(FieldValues): - """ - Valid and invalid values for `TimeField`. - """ - valid_inputs = { - '13:00': datetime.time(13, 00), - datetime.time(13, 00): datetime.time(13, 00), - } - invalid_inputs = { - 'abc': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]'], - '99:99': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]'], - } - outputs = { - datetime.time(13, 00): '13:00:00' - } - field = fields.TimeField() - - -class TestCustomInputFormatTimeField(FieldValues): - """ - Valid and invalid values for `TimeField` with a custom input format. - """ - valid_inputs = { - '1:00pm': datetime.time(13, 00), - } - invalid_inputs = { - '13:00': ['Time has wrong format. Use one of these formats instead: hh:mm[AM|PM]'], - } - outputs = {} - field = fields.TimeField(input_formats=['%I:%M%p']) - - -class TestCustomOutputFormatTimeField(FieldValues): - """ - Values for `TimeField` with a custom output format. - """ - valid_inputs = {} - invalid_inputs = {} - outputs = { - datetime.time(13, 00): '01:00PM' - } - field = fields.TimeField(format='%I:%M%p') - - -class TestNoOutputFormatTimeField(FieldValues): - """ - Values for `TimeField` with a no output format. - """ - valid_inputs = {} - invalid_inputs = {} - outputs = { - datetime.time(13, 00): datetime.time(13, 00) - } - field = fields.TimeField(format=None) - - -# Choice types... - -class TestChoiceField(FieldValues): - """ - Valid and invalid values for `ChoiceField`. - """ - valid_inputs = { - 'poor': 'poor', - 'medium': 'medium', - 'good': 'good', - } - invalid_inputs = { - 'amazing': ['`amazing` is not a valid choice.'] - } - outputs = { - 'good': 'good' - } - field = fields.ChoiceField( - choices=[ - ('poor', 'Poor quality'), - ('medium', 'Medium quality'), - ('good', 'Good quality'), - ] - ) - - -class TestChoiceFieldWithType(FieldValues): - """ - Valid and invalid values for a `Choice` field that uses an integer type, - instead of a char type. - """ - valid_inputs = { - '1': 1, - 3: 3, - } - invalid_inputs = { - 5: ['`5` is not a valid choice.'], - 'abc': ['`abc` is not a valid choice.'] - } - outputs = { - '1': 1, - 1: 1 - } - field = fields.ChoiceField( - choices=[ - (1, 'Poor quality'), - (2, 'Medium quality'), - (3, 'Good quality'), - ] - ) - - -class TestChoiceFieldWithListChoices(FieldValues): - """ - Valid and invalid values for a `Choice` field that uses a flat 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 = fields.ChoiceField(choices=('poor', 'medium', 'good')) - - -class TestMultipleChoiceField(FieldValues): - """ - Valid and invalid values for `MultipleChoiceField`. - """ - valid_inputs = { - (): set(), - ('aircon',): set(['aircon']), - ('aircon', 'manual'): set(['aircon', 'manual']), - } - invalid_inputs = { - 'abc': ['Expected a list of items but got type `str`'], - ('aircon', 'incorrect'): ['`incorrect` is not a valid choice.'] - } - outputs = [ - (['aircon', 'manual'], set(['aircon', 'manual'])) - ] - field = fields.MultipleChoiceField( - choices=[ - ('aircon', 'AirCon'), - ('manual', 'Manual drive'), - ('diesel', 'Diesel'), - ] - ) - - -# """ -# General serializer field tests. -# """ -# from __future__ import unicode_literals - -# import datetime -# import re -# from decimal import Decimal -# from uuid import uuid4 -# from django.core import validators -# from django.db import models -# from django.test import TestCase -# from django.utils.datastructures import SortedDict -# from rest_framework import serializers -# from tests.models import RESTFrameworkModel - - -# class TimestampedModel(models.Model): -# added = models.DateTimeField(auto_now_add=True) -# updated = models.DateTimeField(auto_now=True) - - -# class CharPrimaryKeyModel(models.Model): -# id = models.CharField(max_length=20, primary_key=True) - - -# class TimestampedModelSerializer(serializers.ModelSerializer): -# class Meta: -# model = TimestampedModel - - -# class CharPrimaryKeyModelSerializer(serializers.ModelSerializer): -# class Meta: -# model = CharPrimaryKeyModel - - -# class TimeFieldModel(models.Model): -# clock = models.TimeField() - - -# class TimeFieldModelSerializer(serializers.ModelSerializer): -# class Meta: -# model = TimeFieldModel - - -# SAMPLE_CHOICES = [ -# ('red', 'Red'), -# ('green', 'Green'), -# ('blue', 'Blue'), -# ] - - -# class ChoiceFieldModel(models.Model): -# choice = models.CharField(choices=SAMPLE_CHOICES, blank=True, max_length=255) - - -# class ChoiceFieldModelSerializer(serializers.ModelSerializer): -# class Meta: -# model = ChoiceFieldModel - - -# class ChoiceFieldModelWithNull(models.Model): -# choice = models.CharField(choices=SAMPLE_CHOICES, blank=True, null=True, max_length=255) - - -# class ChoiceFieldModelWithNullSerializer(serializers.ModelSerializer): -# class Meta: -# model = ChoiceFieldModelWithNull - - -# class BasicFieldTests(TestCase): -# def test_auto_now_fields_read_only(self): -# """ -# auto_now and auto_now_add fields should be read_only by default. -# """ -# serializer = TimestampedModelSerializer() -# self.assertEqual(serializer.fields['added'].read_only, True) - -# def test_auto_pk_fields_read_only(self): -# """ -# AutoField fields should be read_only by default. -# """ -# serializer = TimestampedModelSerializer() -# self.assertEqual(serializer.fields['id'].read_only, True) - -# def test_non_auto_pk_fields_not_read_only(self): -# """ -# PK fields other than AutoField fields should not be read_only by default. -# """ -# serializer = CharPrimaryKeyModelSerializer() -# self.assertEqual(serializer.fields['id'].read_only, False) - -# def test_dict_field_ordering(self): -# """ -# Field should preserve dictionary ordering, if it exists. -# See: https://github.com/tomchristie/django-rest-framework/issues/832 -# """ -# ret = SortedDict() -# ret['c'] = 1 -# ret['b'] = 1 -# ret['a'] = 1 -# ret['z'] = 1 -# field = serializers.Field() -# keys = list(field.to_native(ret).keys()) -# self.assertEqual(keys, ['c', 'b', 'a', 'z']) - -# def test_widget_html_attributes(self): -# """ -# Make sure widget_html() renders the correct attributes -# """ -# r = re.compile('(\S+)=["\']?((?:.(?!["\']?\s+(?:\S+)=|[>"\']))+.)["\']?') -# form = TimeFieldModelSerializer().data -# attributes = r.findall(form.fields['clock'].widget_html()) -# self.assertIn(('name', 'clock'), attributes) -# self.assertIn(('id', 'clock'), attributes) - - -# class DateFieldTest(TestCase): -# """ -# Tests for the DateFieldTest from_native() and to_native() behavior -# """ - -# def test_from_native_string(self): -# """ -# Make sure from_native() accepts default iso input formats. -# """ -# f = serializers.DateField() -# result_1 = f.from_native('1984-07-31') - -# self.assertEqual(datetime.date(1984, 7, 31), result_1) - -# def test_from_native_datetime_date(self): -# """ -# Make sure from_native() accepts a datetime.date instance. -# """ -# f = serializers.DateField() -# result_1 = f.from_native(datetime.date(1984, 7, 31)) - -# self.assertEqual(result_1, datetime.date(1984, 7, 31)) - -# def test_from_native_custom_format(self): -# """ -# Make sure from_native() accepts custom input formats. -# """ -# f = serializers.DateField(input_formats=['%Y -- %d']) -# result = f.from_native('1984 -- 31') - -# self.assertEqual(datetime.date(1984, 1, 31), result) - -# def test_from_native_invalid_default_on_custom_format(self): -# """ -# Make sure from_native() don't accept default formats if custom format is preset -# """ -# f = serializers.DateField(input_formats=['%Y -- %d']) - -# try: -# f.from_native('1984-07-31') -# except validators.ValidationError as e: -# self.assertEqual(e.messages, ["Date has wrong format. Use one of these formats instead: YYYY -- DD"]) -# else: -# self.fail("ValidationError was not properly raised") - -# def test_from_native_empty(self): -# """ -# Make sure from_native() returns None on empty param. -# """ -# f = serializers.DateField() -# result = f.from_native('') - -# self.assertEqual(result, None) - -# def test_from_native_none(self): -# """ -# Make sure from_native() returns None on None param. -# """ -# f = serializers.DateField() -# result = f.from_native(None) - -# self.assertEqual(result, None) - -# def test_from_native_invalid_date(self): -# """ -# Make sure from_native() raises a ValidationError on passing an invalid date. -# """ -# f = serializers.DateField() - -# try: -# f.from_native('1984-13-31') -# except validators.ValidationError as e: -# self.assertEqual(e.messages, ["Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]"]) -# else: -# self.fail("ValidationError was not properly raised") - -# def test_from_native_invalid_format(self): -# """ -# Make sure from_native() raises a ValidationError on passing an invalid format. -# """ -# f = serializers.DateField() - -# try: -# f.from_native('1984 -- 31') -# except validators.ValidationError as e: -# self.assertEqual(e.messages, ["Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]"]) -# else: -# self.fail("ValidationError was not properly raised") - -# def test_to_native(self): -# """ -# Make sure to_native() returns datetime as default. -# """ -# f = serializers.DateField() - -# result_1 = f.to_native(datetime.date(1984, 7, 31)) - -# self.assertEqual(datetime.date(1984, 7, 31), result_1) - -# def test_to_native_iso(self): -# """ -# Make sure to_native() with 'iso-8601' returns iso formated date. -# """ -# f = serializers.DateField(format='iso-8601') - -# result_1 = f.to_native(datetime.date(1984, 7, 31)) - -# self.assertEqual('1984-07-31', result_1) - -# def test_to_native_custom_format(self): -# """ -# Make sure to_native() returns correct custom format. -# """ -# f = serializers.DateField(format="%Y - %m.%d") - -# result_1 = f.to_native(datetime.date(1984, 7, 31)) - -# self.assertEqual('1984 - 07.31', result_1) - -# def test_to_native_none(self): -# """ -# Make sure from_native() returns None on None param. -# """ -# f = serializers.DateField(required=False) -# self.assertEqual(None, f.to_native(None)) - - -# class DateTimeFieldTest(TestCase): -# """ -# Tests for the DateTimeField from_native() and to_native() behavior -# """ - -# def test_from_native_string(self): -# """ -# Make sure from_native() accepts default iso input formats. -# """ -# f = serializers.DateTimeField() -# result_1 = f.from_native('1984-07-31 04:31') -# result_2 = f.from_native('1984-07-31 04:31:59') -# result_3 = f.from_native('1984-07-31 04:31:59.000200') - -# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31), result_1) -# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59), result_2) -# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59, 200), result_3) - -# def test_from_native_datetime_datetime(self): -# """ -# Make sure from_native() accepts a datetime.datetime instance. -# """ -# f = serializers.DateTimeField() -# result_1 = f.from_native(datetime.datetime(1984, 7, 31, 4, 31)) -# result_2 = f.from_native(datetime.datetime(1984, 7, 31, 4, 31, 59)) -# result_3 = f.from_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) - -# self.assertEqual(result_1, datetime.datetime(1984, 7, 31, 4, 31)) -# self.assertEqual(result_2, datetime.datetime(1984, 7, 31, 4, 31, 59)) -# self.assertEqual(result_3, datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) - -# def test_from_native_custom_format(self): -# """ -# Make sure from_native() accepts custom input formats. -# """ -# f = serializers.DateTimeField(input_formats=['%Y -- %H:%M']) -# result = f.from_native('1984 -- 04:59') - -# self.assertEqual(datetime.datetime(1984, 1, 1, 4, 59), result) - -# def test_from_native_invalid_default_on_custom_format(self): -# """ -# Make sure from_native() don't accept default formats if custom format is preset -# """ -# f = serializers.DateTimeField(input_formats=['%Y -- %H:%M']) - -# try: -# f.from_native('1984-07-31 04:31:59') -# except validators.ValidationError as e: -# self.assertEqual(e.messages, ["Datetime has wrong format. Use one of these formats instead: YYYY -- hh:mm"]) -# else: -# self.fail("ValidationError was not properly raised") - -# def test_from_native_empty(self): -# """ -# Make sure from_native() returns None on empty param. -# """ -# f = serializers.DateTimeField() -# result = f.from_native('') - -# self.assertEqual(result, None) - -# def test_from_native_none(self): -# """ -# Make sure from_native() returns None on None param. -# """ -# f = serializers.DateTimeField() -# result = f.from_native(None) - -# self.assertEqual(result, None) - -# def test_from_native_invalid_datetime(self): -# """ -# Make sure from_native() raises a ValidationError on passing an invalid datetime. -# """ -# f = serializers.DateTimeField() - -# try: -# f.from_native('04:61:59') -# except validators.ValidationError as e: -# self.assertEqual(e.messages, ["Datetime has wrong format. Use one of these formats instead: " -# "YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]"]) -# else: -# self.fail("ValidationError was not properly raised") - -# def test_from_native_invalid_format(self): -# """ -# Make sure from_native() raises a ValidationError on passing an invalid format. -# """ -# f = serializers.DateTimeField() - -# try: -# f.from_native('04 -- 31') -# except validators.ValidationError as e: -# self.assertEqual(e.messages, ["Datetime has wrong format. Use one of these formats instead: " -# "YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]"]) -# else: -# self.fail("ValidationError was not properly raised") - -# def test_to_native(self): -# """ -# Make sure to_native() returns isoformat as default. -# """ -# f = serializers.DateTimeField() - -# result_1 = f.to_native(datetime.datetime(1984, 7, 31)) -# result_2 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31)) -# result_3 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59)) -# result_4 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) - -# self.assertEqual(datetime.datetime(1984, 7, 31), result_1) -# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31), result_2) -# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59), result_3) -# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59, 200), result_4) - -# def test_to_native_iso(self): -# """ -# Make sure to_native() with format=iso-8601 returns iso formatted datetime. -# """ -# f = serializers.DateTimeField(format='iso-8601') - -# result_1 = f.to_native(datetime.datetime(1984, 7, 31)) -# result_2 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31)) -# result_3 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59)) -# result_4 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) - -# self.assertEqual('1984-07-31T00:00:00', result_1) -# self.assertEqual('1984-07-31T04:31:00', result_2) -# self.assertEqual('1984-07-31T04:31:59', result_3) -# self.assertEqual('1984-07-31T04:31:59.000200', result_4) - -# def test_to_native_custom_format(self): -# """ -# Make sure to_native() returns correct custom format. -# """ -# f = serializers.DateTimeField(format="%Y - %H:%M") - -# result_1 = f.to_native(datetime.datetime(1984, 7, 31)) -# result_2 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31)) -# result_3 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59)) -# result_4 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200)) - -# self.assertEqual('1984 - 00:00', result_1) -# self.assertEqual('1984 - 04:31', result_2) -# self.assertEqual('1984 - 04:31', result_3) -# self.assertEqual('1984 - 04:31', result_4) - -# def test_to_native_none(self): -# """ -# Make sure from_native() returns None on None param. -# """ -# f = serializers.DateTimeField(required=False) -# self.assertEqual(None, f.to_native(None)) - - -# class TimeFieldTest(TestCase): -# """ -# Tests for the TimeField from_native() and to_native() behavior -# """ - -# def test_from_native_string(self): -# """ -# Make sure from_native() accepts default iso input formats. -# """ -# f = serializers.TimeField() -# result_1 = f.from_native('04:31') -# result_2 = f.from_native('04:31:59') -# result_3 = f.from_native('04:31:59.000200') - -# self.assertEqual(datetime.time(4, 31), result_1) -# self.assertEqual(datetime.time(4, 31, 59), result_2) -# self.assertEqual(datetime.time(4, 31, 59, 200), result_3) - -# def test_from_native_datetime_time(self): -# """ -# Make sure from_native() accepts a datetime.time instance. -# """ -# f = serializers.TimeField() -# result_1 = f.from_native(datetime.time(4, 31)) -# result_2 = f.from_native(datetime.time(4, 31, 59)) -# result_3 = f.from_native(datetime.time(4, 31, 59, 200)) - -# self.assertEqual(result_1, datetime.time(4, 31)) -# self.assertEqual(result_2, datetime.time(4, 31, 59)) -# self.assertEqual(result_3, datetime.time(4, 31, 59, 200)) - -# def test_from_native_custom_format(self): -# """ -# Make sure from_native() accepts custom input formats. -# """ -# f = serializers.TimeField(input_formats=['%H -- %M']) -# result = f.from_native('04 -- 31') - -# self.assertEqual(datetime.time(4, 31), result) - -# def test_from_native_invalid_default_on_custom_format(self): -# """ -# Make sure from_native() don't accept default formats if custom format is preset -# """ -# f = serializers.TimeField(input_formats=['%H -- %M']) - -# try: -# f.from_native('04:31:59') -# except validators.ValidationError as e: -# self.assertEqual(e.messages, ["Time has wrong format. Use one of these formats instead: hh -- mm"]) -# else: -# self.fail("ValidationError was not properly raised") - -# def test_from_native_empty(self): -# """ -# Make sure from_native() returns None on empty param. -# """ -# f = serializers.TimeField() -# result = f.from_native('') - -# self.assertEqual(result, None) - -# def test_from_native_none(self): -# """ -# Make sure from_native() returns None on None param. -# """ -# f = serializers.TimeField() -# result = f.from_native(None) - -# self.assertEqual(result, None) - -# def test_from_native_invalid_time(self): -# """ -# Make sure from_native() raises a ValidationError on passing an invalid time. -# """ -# f = serializers.TimeField() - -# try: -# f.from_native('04:61:59') -# except validators.ValidationError as e: -# self.assertEqual(e.messages, ["Time has wrong format. Use one of these formats instead: " -# "hh:mm[:ss[.uuuuuu]]"]) -# else: -# self.fail("ValidationError was not properly raised") - -# def test_from_native_invalid_format(self): -# """ -# Make sure from_native() raises a ValidationError on passing an invalid format. -# """ -# f = serializers.TimeField() - -# try: -# f.from_native('04 -- 31') -# except validators.ValidationError as e: -# self.assertEqual(e.messages, ["Time has wrong format. Use one of these formats instead: " -# "hh:mm[:ss[.uuuuuu]]"]) -# else: -# self.fail("ValidationError was not properly raised") - -# def test_to_native(self): -# """ -# Make sure to_native() returns time object as default. -# """ -# f = serializers.TimeField() -# result_1 = f.to_native(datetime.time(4, 31)) -# result_2 = f.to_native(datetime.time(4, 31, 59)) -# result_3 = f.to_native(datetime.time(4, 31, 59, 200)) - -# self.assertEqual(datetime.time(4, 31), result_1) -# self.assertEqual(datetime.time(4, 31, 59), result_2) -# self.assertEqual(datetime.time(4, 31, 59, 200), result_3) - -# def test_to_native_iso(self): -# """ -# Make sure to_native() with format='iso-8601' returns iso formatted time. -# """ -# f = serializers.TimeField(format='iso-8601') -# result_1 = f.to_native(datetime.time(4, 31)) -# result_2 = f.to_native(datetime.time(4, 31, 59)) -# result_3 = f.to_native(datetime.time(4, 31, 59, 200)) - -# self.assertEqual('04:31:00', result_1) -# self.assertEqual('04:31:59', result_2) -# self.assertEqual('04:31:59.000200', result_3) - -# def test_to_native_custom_format(self): -# """ -# Make sure to_native() returns correct custom format. -# """ -# f = serializers.TimeField(format="%H - %S [%f]") -# result_1 = f.to_native(datetime.time(4, 31)) -# result_2 = f.to_native(datetime.time(4, 31, 59)) -# result_3 = f.to_native(datetime.time(4, 31, 59, 200)) - -# self.assertEqual('04 - 00 [000000]', result_1) -# self.assertEqual('04 - 59 [000000]', result_2) -# self.assertEqual('04 - 59 [000200]', result_3) - - -# class DecimalFieldTest(TestCase): -# """ -# Tests for the DecimalField from_native() and to_native() behavior -# """ - -# def test_from_native_string(self): -# """ -# Make sure from_native() accepts string values -# """ -# f = serializers.DecimalField() -# result_1 = f.from_native('9000') -# result_2 = f.from_native('1.00000001') - -# self.assertEqual(Decimal('9000'), result_1) -# self.assertEqual(Decimal('1.00000001'), result_2) - -# def test_from_native_invalid_string(self): -# """ -# Make sure from_native() raises ValidationError on passing invalid string -# """ -# f = serializers.DecimalField() - -# try: -# f.from_native('123.45.6') -# except validators.ValidationError as e: -# self.assertEqual(e.messages, ["Enter a number."]) -# else: -# self.fail("ValidationError was not properly raised") - -# def test_from_native_integer(self): -# """ -# Make sure from_native() accepts integer values -# """ -# f = serializers.DecimalField() -# result = f.from_native(9000) - -# self.assertEqual(Decimal('9000'), result) - -# def test_from_native_float(self): -# """ -# Make sure from_native() accepts float values -# """ -# f = serializers.DecimalField() -# result = f.from_native(1.00000001) - -# self.assertEqual(Decimal('1.00000001'), result) - -# def test_from_native_empty(self): -# """ -# Make sure from_native() returns None on empty param. -# """ -# f = serializers.DecimalField() -# result = f.from_native('') - -# self.assertEqual(result, None) - -# def test_from_native_none(self): -# """ -# Make sure from_native() returns None on None param. -# """ -# f = serializers.DecimalField() -# result = f.from_native(None) - -# self.assertEqual(result, None) - -# def test_to_native(self): -# """ -# Make sure to_native() returns Decimal as string. -# """ -# f = serializers.DecimalField() - -# result_1 = f.to_native(Decimal('9000')) -# result_2 = f.to_native(Decimal('1.00000001')) - -# self.assertEqual(Decimal('9000'), result_1) -# self.assertEqual(Decimal('1.00000001'), result_2) - -# def test_to_native_none(self): -# """ -# Make sure from_native() returns None on None param. -# """ -# f = serializers.DecimalField(required=False) -# self.assertEqual(None, f.to_native(None)) - -# def test_valid_serialization(self): -# """ -# Make sure the serializer works correctly -# """ -# class DecimalSerializer(serializers.Serializer): -# decimal_field = serializers.DecimalField(max_value=9010, -# min_value=9000, -# max_digits=6, -# decimal_places=2) - -# self.assertTrue(DecimalSerializer(data={'decimal_field': '9001'}).is_valid()) -# self.assertTrue(DecimalSerializer(data={'decimal_field': '9001.2'}).is_valid()) -# self.assertTrue(DecimalSerializer(data={'decimal_field': '9001.23'}).is_valid()) - -# self.assertFalse(DecimalSerializer(data={'decimal_field': '8000'}).is_valid()) -# self.assertFalse(DecimalSerializer(data={'decimal_field': '9900'}).is_valid()) -# self.assertFalse(DecimalSerializer(data={'decimal_field': '9001.234'}).is_valid()) - -# def test_raise_max_value(self): -# """ -# Make sure max_value violations raises ValidationError -# """ -# class DecimalSerializer(serializers.Serializer): -# decimal_field = serializers.DecimalField(max_value=100) - -# s = DecimalSerializer(data={'decimal_field': '123'}) - -# self.assertFalse(s.is_valid()) -# self.assertEqual(s.errors, {'decimal_field': ['Ensure this value is less than or equal to 100.']}) - -# def test_raise_min_value(self): -# """ -# Make sure min_value violations raises ValidationError -# """ -# class DecimalSerializer(serializers.Serializer): -# decimal_field = serializers.DecimalField(min_value=100) - -# s = DecimalSerializer(data={'decimal_field': '99'}) - -# self.assertFalse(s.is_valid()) -# self.assertEqual(s.errors, {'decimal_field': ['Ensure this value is greater than or equal to 100.']}) - -# def test_raise_max_digits(self): -# """ -# Make sure max_digits violations raises ValidationError -# """ -# class DecimalSerializer(serializers.Serializer): -# decimal_field = serializers.DecimalField(max_digits=5) - -# s = DecimalSerializer(data={'decimal_field': '123.456'}) - -# self.assertFalse(s.is_valid()) -# self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 5 digits in total.']}) - -# def test_raise_max_decimal_places(self): -# """ -# Make sure max_decimal_places violations raises ValidationError -# """ -# class DecimalSerializer(serializers.Serializer): -# decimal_field = serializers.DecimalField(decimal_places=3) - -# s = DecimalSerializer(data={'decimal_field': '123.4567'}) - -# self.assertFalse(s.is_valid()) -# self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 3 decimal places.']}) - -# def test_raise_max_whole_digits(self): -# """ -# Make sure max_whole_digits violations raises ValidationError -# """ -# class DecimalSerializer(serializers.Serializer): -# decimal_field = serializers.DecimalField(max_digits=4, decimal_places=3) - -# s = DecimalSerializer(data={'decimal_field': '12345.6'}) - -# self.assertFalse(s.is_valid()) -# self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 4 digits in total.']}) - - -# class ChoiceFieldTests(TestCase): -# """ -# Tests for the ChoiceField options generator -# """ -# def test_choices_required(self): -# """ -# Make sure proper choices are rendered if field is required -# """ -# f = serializers.ChoiceField(required=True, choices=SAMPLE_CHOICES) -# self.assertEqual(f.choices, SAMPLE_CHOICES) - -# def test_choices_not_required(self): -# """ -# Make sure proper choices (plus blank) are rendered if the field isn't required -# """ -# f = serializers.ChoiceField(required=False, choices=SAMPLE_CHOICES) -# self.assertEqual(f.choices, models.fields.BLANK_CHOICE_DASH + SAMPLE_CHOICES) - -# def test_blank_choice_display(self): -# blank = 'No Preference' -# f = serializers.ChoiceField( -# required=False, -# choices=SAMPLE_CHOICES, -# blank_display_value=blank, -# ) -# self.assertEqual(f.choices, [('', blank)] + SAMPLE_CHOICES) - -# def test_invalid_choice_model(self): -# s = ChoiceFieldModelSerializer(data={'choice': 'wrong_value'}) -# self.assertFalse(s.is_valid()) -# self.assertEqual(s.errors, {'choice': ['Select a valid choice. wrong_value is not one of the available choices.']}) -# self.assertEqual(s.data['choice'], '') - -# def test_empty_choice_model(self): -# """ -# Test that the 'empty' value is correctly passed and used depending on -# the 'null' property on the model field. -# """ -# s = ChoiceFieldModelSerializer(data={'choice': ''}) -# self.assertTrue(s.is_valid()) -# self.assertEqual(s.data['choice'], '') - -# s = ChoiceFieldModelWithNullSerializer(data={'choice': ''}) -# self.assertTrue(s.is_valid()) -# self.assertEqual(s.data['choice'], None) - -# def test_from_native_empty(self): -# """ -# Make sure from_native() returns an empty string on empty param by default. -# """ -# f = serializers.ChoiceField(choices=SAMPLE_CHOICES) -# self.assertEqual(f.from_native(''), '') -# self.assertEqual(f.from_native(None), '') - -# def test_from_native_empty_override(self): -# """ -# Make sure you can override from_native() behavior regarding empty values. -# """ -# f = serializers.ChoiceField(choices=SAMPLE_CHOICES, empty=None) -# self.assertEqual(f.from_native(''), None) -# self.assertEqual(f.from_native(None), None) - -# def test_metadata_choices(self): -# """ -# Make sure proper choices are included in the field's metadata. -# """ -# choices = [{'value': v, 'display_name': n} for v, n in SAMPLE_CHOICES] -# f = serializers.ChoiceField(choices=SAMPLE_CHOICES) -# self.assertEqual(f.metadata()['choices'], choices) - -# def test_metadata_choices_not_required(self): -# """ -# Make sure proper choices are included in the field's metadata. -# """ -# choices = [{'value': v, 'display_name': n} -# for v, n in models.fields.BLANK_CHOICE_DASH + SAMPLE_CHOICES] -# f = serializers.ChoiceField(required=False, choices=SAMPLE_CHOICES) -# self.assertEqual(f.metadata()['choices'], choices) - - -# class EmailFieldTests(TestCase): -# """ -# Tests for EmailField attribute values -# """ - -# class EmailFieldModel(RESTFrameworkModel): -# email_field = models.EmailField(blank=True) - -# class EmailFieldWithGivenMaxLengthModel(RESTFrameworkModel): -# email_field = models.EmailField(max_length=150, blank=True) - -# def test_default_model_value(self): -# class EmailFieldSerializer(serializers.ModelSerializer): -# class Meta: -# model = self.EmailFieldModel - -# serializer = EmailFieldSerializer(data={}) -# self.assertEqual(serializer.is_valid(), True) -# self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 75) - -# def test_given_model_value(self): -# class EmailFieldSerializer(serializers.ModelSerializer): -# class Meta: -# model = self.EmailFieldWithGivenMaxLengthModel - -# serializer = EmailFieldSerializer(data={}) -# self.assertEqual(serializer.is_valid(), True) -# self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 150) - -# def test_given_serializer_value(self): -# class EmailFieldSerializer(serializers.ModelSerializer): -# email_field = serializers.EmailField(source='email_field', max_length=20, required=False) - -# class Meta: -# model = self.EmailFieldModel - -# serializer = EmailFieldSerializer(data={}) -# self.assertEqual(serializer.is_valid(), True) -# self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 20) - - -# class SlugFieldTests(TestCase): -# """ -# Tests for SlugField attribute values -# """ - -# class SlugFieldModel(RESTFrameworkModel): -# slug_field = models.SlugField(blank=True) - -# class SlugFieldWithGivenMaxLengthModel(RESTFrameworkModel): -# slug_field = models.SlugField(max_length=84, blank=True) - -# def test_default_model_value(self): -# class SlugFieldSerializer(serializers.ModelSerializer): -# class Meta: -# model = self.SlugFieldModel - -# serializer = SlugFieldSerializer(data={}) -# self.assertEqual(serializer.is_valid(), True) -# self.assertEqual(getattr(serializer.fields['slug_field'], 'max_length'), 50) - -# def test_given_model_value(self): -# class SlugFieldSerializer(serializers.ModelSerializer): -# class Meta: -# model = self.SlugFieldWithGivenMaxLengthModel - -# serializer = SlugFieldSerializer(data={}) -# self.assertEqual(serializer.is_valid(), True) -# self.assertEqual(getattr(serializer.fields['slug_field'], 'max_length'), 84) - -# def test_given_serializer_value(self): -# class SlugFieldSerializer(serializers.ModelSerializer): -# slug_field = serializers.SlugField(source='slug_field', -# max_length=20, required=False) - -# class Meta: -# model = self.SlugFieldModel - -# serializer = SlugFieldSerializer(data={}) -# self.assertEqual(serializer.is_valid(), True) -# self.assertEqual(getattr(serializer.fields['slug_field'], -# 'max_length'), 20) - -# def test_invalid_slug(self): -# """ -# Make sure an invalid slug raises ValidationError -# """ -# class SlugFieldSerializer(serializers.ModelSerializer): -# slug_field = serializers.SlugField(source='slug_field', max_length=20, required=True) - -# class Meta: -# model = self.SlugFieldModel - -# s = SlugFieldSerializer(data={'slug_field': 'a b'}) - -# self.assertEqual(s.is_valid(), False) -# self.assertEqual(s.errors, {'slug_field': ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."]}) - - -# class URLFieldTests(TestCase): -# """ -# Tests for URLField attribute values. - -# (Includes test for #1210, checking that validators can be overridden.) -# """ - -# class URLFieldModel(RESTFrameworkModel): -# url_field = models.URLField(blank=True) - -# class URLFieldWithGivenMaxLengthModel(RESTFrameworkModel): -# url_field = models.URLField(max_length=128, blank=True) - -# def test_default_model_value(self): -# class URLFieldSerializer(serializers.ModelSerializer): -# class Meta: -# model = self.URLFieldModel - -# serializer = URLFieldSerializer(data={}) -# self.assertEqual(serializer.is_valid(), True) -# self.assertEqual(getattr(serializer.fields['url_field'], -# 'max_length'), 200) - -# def test_given_model_value(self): -# class URLFieldSerializer(serializers.ModelSerializer): -# class Meta: -# model = self.URLFieldWithGivenMaxLengthModel - -# serializer = URLFieldSerializer(data={}) -# self.assertEqual(serializer.is_valid(), True) -# self.assertEqual(getattr(serializer.fields['url_field'], -# 'max_length'), 128) - -# def test_given_serializer_value(self): -# class URLFieldSerializer(serializers.ModelSerializer): -# url_field = serializers.URLField(source='url_field', -# max_length=20, required=False) - -# class Meta: -# model = self.URLFieldWithGivenMaxLengthModel - -# serializer = URLFieldSerializer(data={}) -# self.assertEqual(serializer.is_valid(), True) -# self.assertEqual(getattr(serializer.fields['url_field'], -# 'max_length'), 20) - -# def test_validators_can_be_overridden(self): -# url_field = serializers.URLField(validators=[]) -# validators = url_field.validators -# self.assertEqual([], validators, 'Passing `validators` kwarg should have overridden default validators') - - -# class FieldMetadata(TestCase): -# def setUp(self): -# self.required_field = serializers.Field() -# self.required_field.label = uuid4().hex -# self.required_field.required = True - -# self.optional_field = serializers.Field() -# self.optional_field.label = uuid4().hex -# self.optional_field.required = False - -# def test_required(self): -# self.assertEqual(self.required_field.metadata()['required'], True) - -# def test_optional(self): -# self.assertEqual(self.optional_field.metadata()['required'], False) - -# def test_label(self): -# for field in (self.required_field, self.optional_field): -# self.assertEqual(field.metadata()['label'], field.label) - - -# class FieldCallableDefault(TestCase): -# def setUp(self): -# self.simple_callable = lambda: 'foo bar' - -# def test_default_can_be_simple_callable(self): -# """ -# Ensure that the 'default' argument can also be a simple callable. -# """ -# field = serializers.WritableField(default=self.simple_callable) -# into = {} -# field.field_from_native({}, {}, 'field', into) -# self.assertEqual(into, {'field': 'foo bar'}) - - -# class CustomIntegerField(TestCase): -# """ -# Test that custom fields apply min_value and max_value constraints -# """ -# def test_custom_fields_can_be_validated_for_value(self): - -# class MoneyField(models.PositiveIntegerField): -# pass - -# class EntryModel(models.Model): -# bank = MoneyField(validators=[validators.MaxValueValidator(100)]) - -# class EntrySerializer(serializers.ModelSerializer): -# class Meta: -# model = EntryModel - -# entry = EntryModel(bank=1) - -# serializer = EntrySerializer(entry, data={"bank": 11}) -# self.assertTrue(serializer.is_valid()) - -# serializer = EntrySerializer(entry, data={"bank": -1}) -# self.assertFalse(serializer.is_valid()) - -# serializer = EntrySerializer(entry, data={"bank": 101}) -# self.assertFalse(serializer.is_valid()) - - -# class BooleanField(TestCase): -# """ -# Tests for BooleanField -# """ -# def test_boolean_required(self): -# class BooleanRequiredSerializer(serializers.Serializer): -# bool_field = serializers.BooleanField(required=True) - -# self.assertFalse(BooleanRequiredSerializer(data={}).is_valid()) - - -# class SerializerMethodFieldTest(TestCase): -# """ -# Tests for the SerializerMethodField field_to_native() behavior -# """ -# class SerializerTest(serializers.Serializer): -# def get_my_test(self, obj): -# return obj.my_test[0:5] - -# class ModelCharField(TestCase): -# """ -# Tests for CharField -# """ -# def test_none_serializing(self): -# class CharFieldSerializer(serializers.Serializer): -# char = serializers.CharField(allow_none=True, required=False) -# serializer = CharFieldSerializer(data={'char': None}) -# self.assertTrue(serializer.is_valid()) -# self.assertIsNone(serializer.object['char']) - - -# class SerializerMethodFieldTest(TestCase): -# """ -# Tests for the SerializerMethodField field_to_native() behavior -# """ -# class SerializerTest(serializers.Serializer): -# def get_my_test(self, obj): -# return obj.my_test[0:5] - -# class Example(): -# my_test = 'Hey, this is a test !' - -# def test_field_to_native(self): -# s = serializers.SerializerMethodField('get_my_test') -# s.initialize(self.SerializerTest(), 'name') -# result = s.field_to_native(self.Example(), None) -# self.assertEqual(result, 'Hey, ') From b187f53453d3885cd918f5f9f4490bcc8e3e2410 Mon Sep 17 00:00:00 2001 From: Danilo Bargen <mail@dbrgn.ch> Date: Mon, 2 Jun 2014 00:41:58 +0200 Subject: [PATCH 075/249] Changed return status for CSRF failures to HTTP 403 By default, Django returns "HTTP 403 Forbidden" responses when CSRF validation failed[1]. CSRF is a case of authorization, not of authentication. Therefore `PermissionDenied` should be raised instead of `AuthenticationFailed`. [1] https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#rejected-requests --- rest_framework/authentication.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py index f3fec05ec..36d74dd9b 100644 --- a/rest_framework/authentication.py +++ b/rest_framework/authentication.py @@ -129,7 +129,7 @@ class SessionAuthentication(BaseAuthentication): reason = CSRFCheck().process_view(request, None, (), {}) if reason: # CSRF failed, bail with explicit error message - raise exceptions.AuthenticationFailed('CSRF Failed: %s' % reason) + raise exceptions.PermissionDenied('CSRF Failed: %s' % reason) class TokenAuthentication(BaseAuthentication): From f22d0afc3dfc7478e084d1d6ed6b53f71641dec6 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Tue, 23 Sep 2014 14:15:00 +0100 Subject: [PATCH 076/249] Tests for field choices --- rest_framework/fields.py | 21 +++--- rest_framework/serializers.py | 3 + rest_framework/utils/field_mapping.py | 58 ++++++++-------- tests/test_field_options.py | 55 --------------- .../{test_field_values.py => test_fields.py} | 67 +++++++++++++++++++ tests/test_model_serializer.py | 47 ++++++++++--- 6 files changed, 149 insertions(+), 102 deletions(-) delete mode 100644 tests/test_field_options.py rename tests/{test_field_values.py => test_fields.py} (88%) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 48a3e1ab9..f5bae7347 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -102,6 +102,7 @@ class Field(object): 'null': _('This field may not be null.') } default_validators = [] + default_empty_html = None def __init__(self, read_only=False, write_only=False, required=None, default=empty, initial=None, source=None, @@ -185,6 +186,11 @@ class Field(object): Given the *incoming* primative data, return the value for this field that should be validated and transformed to a native value. """ + if html.is_html_input(dictionary): + # HTML forms will represent empty fields as '', and cannot + # represent None or False values directly. + ret = dictionary.get(self.field_name, '') + return self.default_empty_html if (ret == '') else ret return dictionary.get(self.field_name, empty) def get_attribute(self, instance): @@ -236,9 +242,6 @@ class Field(object): Test the given value against all the validators on the field, and either raise a `ValidationError` or simply return. """ - if value in (None, '', [], (), {}): - return - errors = [] for validator in self.validators: try: @@ -282,16 +285,10 @@ class BooleanField(Field): default_error_messages = { 'invalid': _('`{input}` is not a valid boolean.') } + default_empty_html = False TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True)) FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False)) - def get_value(self, dictionary): - if html.is_html_input(dictionary): - # HTML forms do not send a `False` value on an empty checkbox, - # so we override the default empty value to be False. - return dictionary.get(self.field_name, False) - return dictionary.get(self.field_name, empty) - def to_internal_value(self, data): if data in self.TRUE_VALUES: return True @@ -315,6 +312,7 @@ class CharField(Field): default_error_messages = { 'blank': _('This field may not be blank.') } + default_empty_html = '' def __init__(self, **kwargs): self.allow_blank = kwargs.pop('allow_blank', False) @@ -323,6 +321,9 @@ class CharField(Field): super(CharField, self).__init__(**kwargs) 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 not self.allow_blank: self.fail('blank') diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index d9f9c8cbc..949f59157 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -411,6 +411,9 @@ class ModelSerializer(Serializer): # `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): + # `allow_blank` is only valid for textual fields. + kwargs.pop('allow_blank', None) elif field_name in info.relations: # Create forward and reverse relationships. diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index be72e444e..1c718ccba 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -49,8 +49,9 @@ def get_field_kwargs(field_name, model_field): kwargs = {} validator_kwarg = model_field.validators - if model_field.null or model_field.blank: - kwargs['required'] = False + # The following will only be used by ModelField classes. + # Gets removed for everything else. + kwargs['model_field'] = model_field if model_field.verbose_name and needs_label(model_field, field_name): kwargs['label'] = capfirst(model_field.verbose_name) @@ -59,23 +60,26 @@ def get_field_kwargs(field_name, model_field): kwargs['help_text'] = model_field.help_text if isinstance(model_field, models.AutoField) or not model_field.editable: + # If this field is read-only, then return early. + # Further keyword arguments are not valid. kwargs['read_only'] = True - # Read only implies that the field is not required. - # We have a cleaner repr on the instance if we don't set it. - kwargs.pop('required', None) + return kwargs if model_field.has_default(): - kwargs['default'] = model_field.get_default() - # Having a default implies that the field is not required. - # We have a cleaner repr on the instance if we don't set it. - kwargs.pop('required', None) + kwargs['required'] = False if model_field.flatchoices: - # If this model field contains choices, then return now, - # any further keyword arguments are not valid. + # 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: + kwargs['allow_null'] = True + + if model_field.blank: + kwargs['allow_blank'] = True + # Ensure that max_length is passed explicitly as a keyword arg, # rather than as a validator. max_length = getattr(model_field, 'max_length', None) @@ -88,7 +92,10 @@ def get_field_kwargs(field_name, model_field): # Ensure that min_length is passed explicitly as a keyword arg, # rather than as a validator. - min_length = getattr(model_field, 'min_length', None) + min_length = next(( + validator.limit_value for validator in validator_kwarg + if isinstance(validator, validators.MinLengthValidator) + ), None) if min_length is not None: kwargs['min_length'] = min_length validator_kwarg = [ @@ -153,20 +160,9 @@ def get_field_kwargs(field_name, model_field): if decimal_places is not None: kwargs['decimal_places'] = decimal_places - if isinstance(model_field, models.BooleanField): - # models.BooleanField has `blank=True`, but *is* actually - # required *unless* a default is provided. - # Also note that Django<1.6 uses `default=False` for - # models.BooleanField, but Django>=1.6 uses `default=None`. - kwargs.pop('required', None) - if validator_kwarg: kwargs['validators'] = validator_kwarg - # The following will only be used by ModelField classes. - # Gets removed for everything else. - kwargs['model_field'] = model_field - return kwargs @@ -188,16 +184,22 @@ def get_relation_kwargs(field_name, relation_info): kwargs.pop('queryset', None) if model_field: - if model_field.null or model_field.blank: - kwargs['required'] = False if model_field.verbose_name and needs_label(model_field, field_name): kwargs['label'] = capfirst(model_field.verbose_name) - if not model_field.editable: - kwargs['read_only'] = True - kwargs.pop('queryset', None) help_text = clean_manytomany_helptext(model_field.help_text) if help_text: kwargs['help_text'] = help_text + if not model_field.editable: + kwargs['read_only'] = True + kwargs.pop('queryset', None) + if kwargs.get('read_only', False): + # If this field is read-only, then return early. + # No further keyword arguments are valid. + return kwargs + if model_field.has_default(): + kwargs['required'] = False + if model_field.null: + kwargs['allow_null'] = True return kwargs diff --git a/tests/test_field_options.py b/tests/test_field_options.py deleted file mode 100644 index 444bd4248..000000000 --- a/tests/test_field_options.py +++ /dev/null @@ -1,55 +0,0 @@ -from rest_framework import fields -import pytest - - -class TestFieldOptions: - def test_required(self): - """ - By default a field must be included in the input. - """ - field = fields.IntegerField() - with pytest.raises(fields.ValidationError) as exc_info: - field.run_validation() - assert exc_info.value.messages == ['This field is required.'] - - def test_not_required(self): - """ - If `required=False` then a field may be omitted from the input. - """ - field = fields.IntegerField(required=False) - with pytest.raises(fields.SkipField): - field.run_validation() - - def test_disallow_null(self): - """ - By default `None` is not a valid input. - """ - field = fields.IntegerField() - with pytest.raises(fields.ValidationError) as exc_info: - field.run_validation(None) - assert exc_info.value.messages == ['This field may not be null.'] - - def test_allow_null(self): - """ - If `allow_null=True` then `None` is a valid input. - """ - field = fields.IntegerField(allow_null=True) - output = field.run_validation(None) - assert output is None - - def test_disallow_blank(self): - """ - By default '' is not a valid input. - """ - field = fields.CharField() - with pytest.raises(fields.ValidationError) as exc_info: - field.run_validation('') - assert exc_info.value.messages == ['This field may not be blank.'] - - def test_allow_blank(self): - """ - If `allow_blank=True` then '' is a valid input. - """ - field = fields.CharField(allow_blank=True) - output = field.run_validation('') - assert output is '' diff --git a/tests/test_field_values.py b/tests/test_fields.py similarity index 88% rename from tests/test_field_values.py rename to tests/test_fields.py index bac50f0bc..6bf9aed4a 100644 --- a/tests/test_field_values.py +++ b/tests/test_fields.py @@ -6,6 +6,73 @@ import django import pytest +# Tests for field keyword arguments and core functionality. +# --------------------------------------------------------- + +class TestFieldOptions: + def test_required(self): + """ + By default a field must be included in the input. + """ + field = fields.IntegerField() + with pytest.raises(fields.ValidationError) as exc_info: + field.run_validation() + assert exc_info.value.messages == ['This field is required.'] + + def test_not_required(self): + """ + If `required=False` then a field may be omitted from the input. + """ + field = fields.IntegerField(required=False) + with pytest.raises(fields.SkipField): + field.run_validation() + + def test_disallow_null(self): + """ + By default `None` is not a valid input. + """ + field = fields.IntegerField() + with pytest.raises(fields.ValidationError) as exc_info: + field.run_validation(None) + assert exc_info.value.messages == ['This field may not be null.'] + + def test_allow_null(self): + """ + If `allow_null=True` then `None` is a valid input. + """ + field = fields.IntegerField(allow_null=True) + output = field.run_validation(None) + assert output is None + + def test_disallow_blank(self): + """ + By default '' is not a valid input. + """ + field = fields.CharField() + with pytest.raises(fields.ValidationError) as exc_info: + field.run_validation('') + assert exc_info.value.messages == ['This field may not be blank.'] + + def test_allow_blank(self): + """ + If `allow_blank=True` then '' is a valid input. + """ + field = fields.CharField(allow_blank=True) + output = field.run_validation('') + assert output is '' + + def test_default(self): + """ + If `default` is set, then omitted values get the default input. + """ + field = fields.IntegerField(default=123) + output = field.run_validation() + assert output is 123 + + +# Tests for field input and output values. +# ---------------------------------------- + def get_items(mapping_or_list_of_two_tuples): # Tests accept either lists of two tuples, or dictionaries. if isinstance(mapping_or_list_of_two_tuples, dict): diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index d9f9efbe7..731ed2fbd 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -6,6 +6,7 @@ These tests deal with ensuring that we correctly map the model fields onto an appropriate set of serializer fields for each case. """ from django.core.exceptions import ImproperlyConfigured +from django.core.validators import MaxValueValidator, MinValueValidator, MinLengthValidator from django.db import models from django.test import TestCase from rest_framework import serializers @@ -15,7 +16,8 @@ def dedent(blocktext): return '\n'.join([line[12:] for line in blocktext.splitlines()[1:-1]]) -# Testing regular field mappings +# Tests for regular field mappings. +# --------------------------------- class CustomField(models.Field): """ @@ -24,9 +26,6 @@ class CustomField(models.Field): pass -COLOR_CHOICES = (('red', 'Red'), ('blue', 'Blue'), ('green', 'Green')) - - class RegularFieldsModel(models.Model): """ A model class for testing regular flat fields. @@ -35,7 +34,6 @@ class RegularFieldsModel(models.Model): big_integer_field = models.BigIntegerField() boolean_field = models.BooleanField(default=False) char_field = models.CharField(max_length=100) - choices_field = models.CharField(max_length=100, choices=COLOR_CHOICES) comma_seperated_integer_field = models.CommaSeparatedIntegerField(max_length=100) date_field = models.DateField() datetime_field = models.DateTimeField() @@ -57,6 +55,19 @@ class RegularFieldsModel(models.Model): return 'method' +COLOR_CHOICES = (('red', 'Red'), ('blue', 'Blue'), ('green', 'Green')) + + +class FieldOptionsModel(models.Model): + value_limit_field = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)]) + length_limit_field = models.CharField(validators=[MinLengthValidator(3)], max_length=12) + blank_field = models.CharField(blank=True, max_length=10) + null_field = models.IntegerField(null=True) + default_field = models.IntegerField(default=0) + descriptive_field = models.IntegerField(help_text='Some help text', verbose_name='A label') + choices_field = models.CharField(max_length=100, choices=COLOR_CHOICES) + + class TestRegularFieldMappings(TestCase): def test_regular_fields(self): """ @@ -70,9 +81,8 @@ class TestRegularFieldMappings(TestCase): TestSerializer(): auto_field = IntegerField(read_only=True) big_integer_field = IntegerField() - boolean_field = BooleanField(default=False) + boolean_field = BooleanField(required=False) char_field = CharField(max_length=100) - choices_field = ChoiceField(choices=[('red', 'Red'), ('blue', 'Blue'), ('green', 'Green')]) comma_seperated_integer_field = CharField(max_length=100, validators=[<django.core.validators.RegexValidator object>]) date_field = DateField() datetime_field = DateTimeField() @@ -80,7 +90,7 @@ class TestRegularFieldMappings(TestCase): email_field = EmailField(max_length=100) float_field = FloatField() integer_field = IntegerField() - null_boolean_field = BooleanField(required=False) + null_boolean_field = BooleanField(allow_null=True) positive_integer_field = IntegerField() positive_small_integer_field = IntegerField() slug_field = SlugField(max_length=100) @@ -92,6 +102,24 @@ class TestRegularFieldMappings(TestCase): """) self.assertEqual(repr(TestSerializer()), expected) + def test_field_options(self): + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = FieldOptionsModel + + expected = dedent(""" + TestSerializer(): + id = IntegerField(label='ID', read_only=True) + value_limit_field = IntegerField(max_value=10, min_value=1) + length_limit_field = CharField(max_length=12, min_length=3) + blank_field = CharField(allow_blank=True, max_length=10) + null_field = IntegerField(allow_null=True) + 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')]) + """) + self.assertEqual(repr(TestSerializer()), expected) + def test_method_field(self): """ Properties and methods on the model should be allowed as `Meta.fields` @@ -178,7 +206,8 @@ class TestRegularFieldMappings(TestCase): assert str(excinfo.exception) == expected -# Testing relational field mappings +# Tests for relational field mappings. +# ------------------------------------ class ForeignKeyTargetModel(models.Model): name = models.CharField(max_length=100) From 0404f09a7e69f533038d47ca25caad90c0c2659f Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Tue, 23 Sep 2014 14:30:17 +0100 Subject: [PATCH 077/249] NullBooleanField --- rest_framework/fields.py | 37 ++++++++++++++++++++++++++- rest_framework/serializers.py | 2 +- rest_framework/utils/field_mapping.py | 2 +- tests/test_fields.py | 29 ++++++++++++++++++++- tests/test_model_serializer.py | 2 +- 5 files changed, 67 insertions(+), 5 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index f5bae7347..f859658a1 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -289,6 +289,10 @@ class BooleanField(Field): TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True)) FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False)) + def __init__(self, **kwargs): + assert 'allow_null' not in kwargs, '`allow_null` is not a valid option. Use `NullBooleanField` instead.' + super(BooleanField, self).__init__(**kwargs) + def to_internal_value(self, data): if data in self.TRUE_VALUES: return True @@ -297,7 +301,38 @@ class BooleanField(Field): self.fail('invalid', input=data) def to_representation(self, value): - if value is None: + if value in self.TRUE_VALUES: + return True + elif value in self.FALSE_VALUES: + return False + return bool(value) + + +class NullBooleanField(Field): + default_error_messages = { + 'invalid': _('`{input}` is not a valid boolean.') + } + default_empty_html = None + TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True)) + FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False)) + NULL_VALUES = set(('n', 'N', 'null', 'Null', 'NULL', '', None)) + + def __init__(self, **kwargs): + assert 'allow_null' not in kwargs, '`allow_null` is not a valid option.' + kwargs['allow_null'] = True + super(NullBooleanField, self).__init__(**kwargs) + + def to_internal_value(self, data): + if data in self.TRUE_VALUES: + return True + elif data in self.FALSE_VALUES: + return False + elif data in self.NULL_VALUES: + return None + self.fail('invalid', input=data) + + def to_representation(self, value): + if value in self.NULL_VALUES: return None if value in self.TRUE_VALUES: return True diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 949f59157..d8d72a4c6 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -333,7 +333,7 @@ class ModelSerializer(Serializer): models.FloatField: FloatField, models.ImageField: ImageField, models.IntegerField: IntegerField, - models.NullBooleanField: BooleanField, + models.NullBooleanField: NullBooleanField, models.PositiveIntegerField: IntegerField, models.PositiveSmallIntegerField: IntegerField, models.SlugField: SlugField, diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index 1c718ccba..c208afdc5 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -74,7 +74,7 @@ def get_field_kwargs(field_name, model_field): kwargs['choices'] = model_field.flatchoices return kwargs - if model_field.null: + if model_field.null and not isinstance(model_field, models.NullBooleanField): kwargs['allow_null'] = True if model_field.blank: diff --git a/tests/test_fields.py b/tests/test_fields.py index 6bf9aed4a..91f3f5db7 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -124,7 +124,8 @@ class TestBooleanField(FieldValues): False: False, } invalid_inputs = { - 'foo': ['`foo` is not a valid boolean.'] + 'foo': ['`foo` is not a valid boolean.'], + None: ['This field may not be null.'] } outputs = { 'true': True, @@ -140,6 +141,32 @@ class TestBooleanField(FieldValues): field = fields.BooleanField() +class TestNullBooleanField(FieldValues): + """ + Valid and invalid values for `BooleanField`. + """ + valid_inputs = { + 'true': True, + 'false': False, + 'null': None, + True: True, + False: False, + None: None + } + invalid_inputs = { + 'foo': ['`foo` is not a valid boolean.'], + } + outputs = { + 'true': True, + 'false': False, + 'null': None, + True: True, + False: False, + None: None + } + field = fields.NullBooleanField() + + # String types... class TestCharField(FieldValues): diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index 731ed2fbd..f74750247 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -90,7 +90,7 @@ class TestRegularFieldMappings(TestCase): email_field = EmailField(max_length=100) float_field = FloatField() integer_field = IntegerField() - null_boolean_field = BooleanField(allow_null=True) + null_boolean_field = NullBooleanField() positive_integer_field = IntegerField() positive_small_integer_field = IntegerField() slug_field = SlugField(max_length=100) From f4b1dcb167be0bbdaae2cc2a92f651536896dc16 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 24 Sep 2014 14:09:49 +0100 Subject: [PATCH 078/249] OPTIONS support --- rest_framework/generics.py | 51 +------- rest_framework/metadata.py | 126 +++++++++++++++++++ rest_framework/serializers.py | 8 +- rest_framework/settings.py | 2 + rest_framework/utils/field_mapping.py | 20 ++-- rest_framework/views.py | 24 +--- tests/test_metadata.py | 166 ++++++++++++++++++++++++++ 7 files changed, 316 insertions(+), 81 deletions(-) create mode 100644 rest_framework/metadata.py create mode 100644 tests/test_metadata.py diff --git a/rest_framework/generics.py b/rest_framework/generics.py index eb6b64efa..f49b0a439 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -4,13 +4,11 @@ Generic views that provide commonly needed behaviour. from __future__ import unicode_literals from django.db.models.query import QuerySet -from django.core.exceptions import PermissionDenied from django.core.paginator import Paginator, InvalidPage from django.http import Http404 from django.shortcuts import get_object_or_404 as _get_object_or_404 from django.utils.translation import ugettext as _ -from rest_framework import views, mixins, exceptions -from rest_framework.request import clone_request +from rest_framework import views, mixins from rest_framework.settings import api_settings @@ -249,53 +247,6 @@ class GenericAPIView(views.APIView): return obj - # The following are placeholder methods, - # and are intended to be overridden. - # - # The are not called by GenericAPIView directly, - # but are used by the mixin methods. - def metadata(self, request): - """ - Return a dictionary of metadata about the view. - Used to return responses for OPTIONS requests. - - We override the default behavior, and add some extra information - about the required request body for POST and PUT operations. - """ - ret = super(GenericAPIView, self).metadata(request) - - actions = {} - for method in ('PUT', 'POST'): - if method not in self.allowed_methods: - continue - - cloned_request = clone_request(request, method) - try: - # Test global permissions - self.check_permissions(cloned_request) - # Test object permissions - if method == 'PUT': - try: - self.get_object() - except Http404: - # Http404 should be acceptable and the serializer - # metadata should be populated. Except this so the - # outer "else" clause of the try-except-else block - # will be executed. - pass - except (exceptions.APIException, PermissionDenied): - pass - else: - # If user has appropriate permissions for the view, include - # appropriate metadata about the fields that should be supplied. - serializer = self.get_serializer() - actions[method] = serializer.metadata() - - if actions: - ret['actions'] = actions - - return ret - # Concrete view classes that provide method handlers # by composing the mixin classes with the base view. diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py new file mode 100644 index 000000000..580259de1 --- /dev/null +++ b/rest_framework/metadata.py @@ -0,0 +1,126 @@ +""" +The metadata API is used to allow cusomization of how `OPTIONS` requests +are handled. We currently provide a single default implementation that returns +some fairly ad-hoc information about the view. + +Future implementations might use JSON schema or other definations in order +to return this information in a more standardized way. +""" +from __future__ import unicode_literals + +from django.core.exceptions import PermissionDenied +from django.http import Http404 +from django.utils import six +from django.utils.datastructures import SortedDict +from rest_framework import exceptions, serializers +from rest_framework.compat import force_text +from rest_framework.request import clone_request +from rest_framework.utils.field_mapping import ClassLookupDict + + +class BaseMetadata(object): + def determine_metadata(self, request, view): + """ + Return a dictionary of metadata about the view. + Used to return responses for OPTIONS requests. + """ + raise NotImplementedError(".determine_metadata() must be overridden.") + + +class SimpleMetadata(BaseMetadata): + """ + This is the default metadata implementation. + It returns an ad-hoc set of information about the view. + There are not any formalized standards for `OPTIONS` responses + for us to base this on. + """ + label_lookup = ClassLookupDict({ + serializers.Field: 'field', + serializers.BooleanField: 'boolean', + serializers.CharField: 'string', + serializers.URLField: 'url', + serializers.EmailField: 'email', + serializers.RegexField: 'regex', + serializers.SlugField: 'slug', + serializers.IntegerField: 'integer', + serializers.FloatField: 'float', + serializers.DecimalField: 'decimal', + serializers.DateField: 'date', + serializers.DateTimeField: 'datetime', + serializers.TimeField: 'time', + serializers.ChoiceField: 'choice', + serializers.MultipleChoiceField: 'multiple choice', + serializers.FileField: 'file upload', + serializers.ImageField: 'image upload', + }) + + def determine_metadata(self, request, view): + metadata = SortedDict() + metadata['name'] = view.get_view_name() + metadata['description'] = view.get_view_description() + metadata['renders'] = [renderer.media_type for renderer in view.renderer_classes] + metadata['parses'] = [parser.media_type for parser in view.parser_classes] + if hasattr(view, 'get_serializer'): + actions = self.determine_actions(request, view) + if actions: + metadata['actions'] = actions + return metadata + + def determine_actions(self, request, view): + """ + For generic class based views we return information about + the fields that are accepted for 'PUT' and 'POST' methods. + """ + actions = {} + for method in set(['PUT', 'POST']) & set(view.allowed_methods): + view.request = clone_request(request, method) + try: + # Test global permissions + if hasattr(view, 'check_permissions'): + view.check_permissions(view.request) + # Test object permissions + if method == 'PUT' and hasattr(view, 'get_object'): + view.get_object() + except (exceptions.APIException, PermissionDenied, Http404): + pass + else: + # If user has appropriate permissions for the view, include + # appropriate metadata about the fields that should be supplied. + serializer = view.get_serializer() + actions[method] = self.get_serializer_info(serializer) + finally: + view.request = request + + return actions + + def get_serializer_info(self, serializer): + """ + Given an instance of a serializer, return a dictionary of metadata + about its fields. + """ + return SortedDict([ + (field_name, self.get_field_info(field)) + for field_name, field in six.iteritems(serializer.fields) + ]) + + def get_field_info(self, field): + """ + Given an instance of a serializer field, return a dictionary + of metadata about it. + """ + field_info = SortedDict() + field_info['type'] = self.label_lookup[field] + field_info['required'] = getattr(field, 'required', False) + + for attr in ['read_only', 'label', 'help_text', 'min_length', 'max_length']: + value = getattr(field, attr, None) + if value is not None and value != '': + field_info[attr] = force_text(value, strings_only=True) + + if hasattr(field, 'choices'): + field_info['choices'] = [ + {'value': choice_value, 'display_name': choice_name} + for choice_value, choice_name in field.choices.items() + ] + + return field_info diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index d8d72a4c6..8902294bc 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -21,7 +21,7 @@ from rest_framework.utils import html, model_meta, representation from rest_framework.utils.field_mapping import ( get_url_kwargs, get_field_kwargs, get_relation_kwargs, get_nested_relation_kwargs, - lookup_class + ClassLookupDict ) import copy import inspect @@ -318,7 +318,7 @@ class ListSerializer(BaseSerializer): class ModelSerializer(Serializer): - _field_mapping = { + _field_mapping = ClassLookupDict({ models.AutoField: IntegerField, models.BigIntegerField: IntegerField, models.BooleanField: BooleanField, @@ -341,7 +341,7 @@ class ModelSerializer(Serializer): models.TextField: CharField, models.TimeField: TimeField, models.URLField: URLField, - } + }) _related_class = PrimaryKeyRelatedField def create(self, attrs): @@ -400,7 +400,7 @@ class ModelSerializer(Serializer): elif field_name in info.fields_and_pk: # Create regular model fields. model_field = info.fields_and_pk[field_name] - field_cls = lookup_class(self._field_mapping, model_field) + 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` diff --git a/rest_framework/settings.py b/rest_framework/settings.py index 421e146c8..d7fb0a436 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -45,6 +45,7 @@ DEFAULTS = { ), 'DEFAULT_THROTTLE_CLASSES': (), 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'rest_framework.negotiation.DefaultContentNegotiation', + 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata', # Genric view behavior 'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.ModelSerializer', @@ -121,6 +122,7 @@ IMPORT_STRINGS = ( 'DEFAULT_PERMISSION_CLASSES', 'DEFAULT_THROTTLE_CLASSES', 'DEFAULT_CONTENT_NEGOTIATION_CLASS', + 'DEFAULT_METADATA_CLASS', 'DEFAULT_MODEL_SERIALIZER_CLASS', 'DEFAULT_PAGINATION_SERIALIZER_CLASS', 'DEFAULT_FILTER_BACKENDS', diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index c208afdc5..c37940832 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -9,17 +9,21 @@ from rest_framework.compat import clean_manytomany_helptext import inspect -def lookup_class(mapping, instance): +class ClassLookupDict(object): """ - Takes a dictionary with classes as keys, and an object. - Traverses the object's inheritance hierarchy in method - resolution order, and returns the first matching value + Takes a dictionary with classes as keys. + Lookups against this object will traverses the object's inheritance + hierarchy in method resolution order, and returns the first matching value from the dictionary or raises a KeyError if nothing matches. """ - for cls in inspect.getmro(instance.__class__): - if cls in mapping: - return mapping[cls] - raise KeyError('Class %s not found in lookup.', cls.__name__) + def __init__(self, mapping): + self.mapping = mapping + + def __getitem__(self, key): + for cls in inspect.getmro(key.__class__): + if cls in self.mapping: + return self.mapping[cls] + raise KeyError('Class %s not found in lookup.', cls.__name__) def needs_label(model_field, field_name): diff --git a/rest_framework/views.py b/rest_framework/views.py index 9f08a4ad5..835e223a7 100644 --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -5,7 +5,6 @@ from __future__ import unicode_literals from django.core.exceptions import PermissionDenied, ValidationError, NON_FIELD_ERRORS from django.http import Http404 -from django.utils.datastructures import SortedDict from django.views.decorators.csrf import csrf_exempt from rest_framework import status, exceptions from rest_framework.compat import smart_text, HttpResponseBase, View @@ -99,6 +98,7 @@ class APIView(View): throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS + metadata_class = api_settings.DEFAULT_METADATA_CLASS # Allow dependancy injection of other settings to make testing easier. settings = api_settings @@ -418,22 +418,8 @@ class APIView(View): def options(self, request, *args, **kwargs): """ Handler method for HTTP 'OPTIONS' request. - We may as well implement this as Django will otherwise provide - a less useful default implementation. """ - return Response(self.metadata(request), status=status.HTTP_200_OK) - - def metadata(self, request): - """ - Return a dictionary of metadata about the view. - Used to return responses for OPTIONS requests. - """ - # By default we can't provide any form-like information, however the - # generic views override this implementation and add additional - # information for POST and PUT methods, based on the serializer. - ret = SortedDict() - ret['name'] = self.get_view_name() - ret['description'] = self.get_view_description() - ret['renders'] = [renderer.media_type for renderer in self.renderer_classes] - ret['parses'] = [parser.media_type for parser in self.parser_classes] - return ret + if self.metadata_class is None: + return self.http_method_not_allowed(request, *args, **kwargs) + data = self.metadata_class().determine_metadata(request, self) + return Response(data, status=status.HTTP_200_OK) diff --git a/tests/test_metadata.py b/tests/test_metadata.py new file mode 100644 index 000000000..0ebea935f --- /dev/null +++ b/tests/test_metadata.py @@ -0,0 +1,166 @@ +from __future__ import unicode_literals + +from rest_framework import exceptions, serializers, views +from rest_framework.request import Request +from rest_framework.test import APIRequestFactory +import pytest + +request = Request(APIRequestFactory().options('/')) + + +class TestMetadata: + def test_metadata(self): + """ + OPTIONS requests to views should return a valid 200 response. + """ + class ExampleView(views.APIView): + """Example view.""" + pass + + response = ExampleView().options(request=request) + expected = { + 'name': 'Example', + 'description': 'Example view.', + 'renders': [ + 'application/json', + 'text/html' + ], + 'parses': [ + 'application/json', + 'application/x-www-form-urlencoded', + 'multipart/form-data' + ] + } + assert response.status_code == 200 + assert response.data == expected + + def test_none_metadata(self): + """ + OPTIONS requests to views where `metadata_class = None` should raise + a MethodNotAllowed exception, which will result in an HTTP 405 response. + """ + class ExampleView(views.APIView): + metadata_class = None + + with pytest.raises(exceptions.MethodNotAllowed): + ExampleView().options(request=request) + + def test_actions(self): + """ + On generic views OPTIONS should return an 'actions' key with metadata + on the fields that may be supplied to PUT and POST requests. + """ + class ExampleSerializer(serializers.Serializer): + choice_field = serializers.ChoiceField(['red', 'green', 'blue']) + integer_field = serializers.IntegerField(max_value=10) + char_field = serializers.CharField(required=False) + + class ExampleView(views.APIView): + """Example view.""" + def post(self, request): + pass + + def get_serializer(self): + return ExampleSerializer() + + response = ExampleView().options(request=request) + expected = { + 'name': 'Example', + 'description': 'Example view.', + 'renders': [ + 'application/json', + 'text/html' + ], + 'parses': [ + 'application/json', + 'application/x-www-form-urlencoded', + 'multipart/form-data' + ], + 'actions': { + 'POST': { + 'choice_field': { + 'type': 'choice', + 'required': True, + 'read_only': False, + 'label': 'Choice field', + 'choices': [ + {'display_name': 'blue', 'value': 'blue'}, + {'display_name': 'green', 'value': 'green'}, + {'display_name': 'red', 'value': 'red'} + ] + }, + 'integer_field': { + 'type': 'integer', + 'required': True, + 'read_only': False, + 'label': 'Integer field' + }, + 'char_field': { + 'type': 'string', + 'required': False, + 'read_only': False, + 'label': 'Char field' + } + } + } + } + assert response.status_code == 200 + assert response.data == expected + + def test_global_permissions(self): + """ + If a user does not have global permissions on an action, then any + metadata associated with it should not be included in OPTION responses. + """ + class ExampleSerializer(serializers.Serializer): + choice_field = serializers.ChoiceField(['red', 'green', 'blue']) + integer_field = serializers.IntegerField(max_value=10) + char_field = serializers.CharField(required=False) + + class ExampleView(views.APIView): + """Example view.""" + def post(self, request): + pass + + def put(self, request): + pass + + def get_serializer(self): + return ExampleSerializer() + + def check_permissions(self, request): + if request.method == 'POST': + raise exceptions.PermissionDenied() + + response = ExampleView().options(request=request) + assert response.status_code == 200 + assert list(response.data['actions'].keys()) == ['PUT'] + + def test_object_permissions(self): + """ + If a user does not have object permissions on an action, then any + metadata associated with it should not be included in OPTION responses. + """ + class ExampleSerializer(serializers.Serializer): + choice_field = serializers.ChoiceField(['red', 'green', 'blue']) + integer_field = serializers.IntegerField(max_value=10) + char_field = serializers.CharField(required=False) + + class ExampleView(views.APIView): + """Example view.""" + def post(self, request): + pass + + def put(self, request): + pass + + def get_serializer(self): + return ExampleSerializer() + + def get_object(self): + if self.request.method == 'PUT': + raise exceptions.PermissionDenied() + + response = ExampleView().options(request=request) + assert response.status_code == 200 + assert list(response.data['actions'].keys()) == ['POST'] From 358445c174629bdd55894c48eaf965bbfd4414b2 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 24 Sep 2014 14:52:34 +0100 Subject: [PATCH 079/249] Drop redundant OPTIONS tests --- tests/test_generics.py | 180 ----------------------------------------- 1 file changed, 180 deletions(-) diff --git a/tests/test_generics.py b/tests/test_generics.py index 51004edfe..89f9def01 100644 --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -23,25 +23,16 @@ class ForeignKeySerializer(serializers.ModelSerializer): class RootView(generics.ListCreateAPIView): - """ - Example description for OPTIONS. - """ queryset = BasicModel.objects.all() serializer_class = BasicSerializer class InstanceView(generics.RetrieveUpdateDestroyAPIView): - """ - Example description for OPTIONS. - """ queryset = BasicModel.objects.exclude(text='filtered out') serializer_class = BasicSerializer class FKInstanceView(generics.RetrieveUpdateDestroyAPIView): - """ - FK: example description for OPTIONS. - """ queryset = ForeignKeySource.objects.all() serializer_class = ForeignKeySerializer @@ -122,47 +113,6 @@ class TestRootView(TestCase): self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) self.assertEqual(response.data, {"detail": "Method 'DELETE' not allowed."}) - # def test_options_root_view(self): - # """ - # OPTIONS requests to ListCreateAPIView should return metadata - # """ - # request = factory.options('/') - # with self.assertNumQueries(0): - # response = self.view(request).render() - # expected = { - # 'parses': [ - # 'application/json', - # 'application/x-www-form-urlencoded', - # 'multipart/form-data' - # ], - # 'renders': [ - # 'application/json', - # 'text/html' - # ], - # 'name': 'Root', - # 'description': 'Example description for OPTIONS.', - # 'actions': { - # 'POST': { - # 'text': { - # 'max_length': 100, - # 'read_only': False, - # 'required': True, - # 'type': 'string', - # "label": "Text comes here", - # "help_text": "Text description." - # }, - # 'id': { - # 'read_only': True, - # 'required': False, - # 'type': 'integer', - # 'label': 'ID', - # }, - # } - # } - # } - # self.assertEqual(response.status_code, status.HTTP_200_OK) - # self.assertEqual(response.data, expected) - def test_post_cannot_set_id(self): """ POST requests to create a new object should not be able to set the id. @@ -256,89 +206,6 @@ class TestInstanceView(TestCase): ids = [obj.id for obj in self.objects.all()] self.assertEqual(ids, [2, 3]) - # def test_options_instance_view(self): - # """ - # OPTIONS requests to RetrieveUpdateDestroyAPIView should return metadata - # """ - # request = factory.options('/1') - # with self.assertNumQueries(1): - # response = self.view(request, pk=1).render() - # expected = { - # 'parses': [ - # 'application/json', - # 'application/x-www-form-urlencoded', - # 'multipart/form-data' - # ], - # 'renders': [ - # 'application/json', - # 'text/html' - # ], - # 'name': 'Instance', - # 'description': 'Example description for OPTIONS.', - # 'actions': { - # 'PUT': { - # 'text': { - # 'max_length': 100, - # 'read_only': False, - # 'required': True, - # 'type': 'string', - # 'label': 'Text comes here', - # 'help_text': 'Text description.' - # }, - # 'id': { - # 'read_only': True, - # 'required': False, - # 'type': 'integer', - # 'label': 'ID', - # }, - # } - # } - # } - # self.assertEqual(response.status_code, status.HTTP_200_OK) - # self.assertEqual(response.data, expected) - - # def test_options_before_instance_create(self): - # """ - # OPTIONS requests to RetrieveUpdateDestroyAPIView should return metadata - # before the instance has been created - # """ - # request = factory.options('/999') - # with self.assertNumQueries(1): - # response = self.view(request, pk=999).render() - # expected = { - # 'parses': [ - # 'application/json', - # 'application/x-www-form-urlencoded', - # 'multipart/form-data' - # ], - # 'renders': [ - # 'application/json', - # 'text/html' - # ], - # 'name': 'Instance', - # 'description': 'Example description for OPTIONS.', - # 'actions': { - # 'PUT': { - # 'text': { - # 'max_length': 100, - # 'read_only': False, - # 'required': True, - # 'type': 'string', - # 'label': 'Text comes here', - # 'help_text': 'Text description.' - # }, - # 'id': { - # 'read_only': True, - # 'required': False, - # 'type': 'integer', - # 'label': 'ID', - # }, - # } - # } - # } - # self.assertEqual(response.status_code, status.HTTP_200_OK) - # self.assertEqual(response.data, expected) - def test_get_instance_view_incorrect_arg(self): """ GET requests with an incorrect pk type, should raise 404, not 500. @@ -415,53 +282,6 @@ class TestFKInstanceView(TestCase): ] self.view = FKInstanceView.as_view() - # def test_options_root_view(self): - # """ - # OPTIONS requests to ListCreateAPIView should return metadata - # """ - # request = factory.options('/999') - # with self.assertNumQueries(1): - # response = self.view(request, pk=999).render() - # expected = { - # 'name': 'Fk Instance', - # 'description': 'FK: example description for OPTIONS.', - # 'renders': [ - # 'application/json', - # 'text/html' - # ], - # 'parses': [ - # 'application/json', - # 'application/x-www-form-urlencoded', - # 'multipart/form-data' - # ], - # 'actions': { - # 'PUT': { - # 'id': { - # 'type': 'integer', - # 'required': False, - # 'read_only': True, - # 'label': 'ID' - # }, - # 'name': { - # 'type': 'string', - # 'required': True, - # 'read_only': False, - # 'label': 'name', - # 'max_length': 100 - # }, - # 'target': { - # 'type': 'field', - # 'required': True, - # 'read_only': False, - # 'label': 'Target', - # 'help_text': 'Target' - # } - # } - # } - # } - # self.assertEqual(response.status_code, status.HTTP_200_OK) - # self.assertEqual(response.data, expected) - class TestOverriddenGetObject(TestCase): """ From 127c0bd3d68860dd6567d81047257fbc3e70b4b9 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 24 Sep 2014 20:25:59 +0100 Subject: [PATCH 080/249] Custom deepcopy on Field classes --- rest_framework/fields.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index f859658a1..1f7d964a5 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -9,6 +9,7 @@ from rest_framework import ISO_8601 from rest_framework.compat import smart_text, EmailValidator, MinValueValidator, MaxValueValidator, URLValidator from rest_framework.settings import api_settings from rest_framework.utils import html, representation, humanize_datetime +import copy import datetime import decimal import inspect @@ -150,6 +151,11 @@ class Field(object): instance._kwargs = kwargs return instance + def __deepcopy__(self, memo): + args = copy.deepcopy(self._args) + kwargs = copy.deepcopy(self._kwargs) + return self.__class__(*args, **kwargs) + def bind(self, field_name, parent, root): """ Setup the context for the field instance. From fb1546ee50953faae8af505a0c90da00ac08ad92 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 24 Sep 2014 20:53:37 +0100 Subject: [PATCH 081/249] Enforce field_name != source --- rest_framework/fields.py | 11 +++++++++++ tests/test_fields.py | 13 ++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 1f7d964a5..9280ea3a3 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -160,6 +160,17 @@ class Field(object): """ Setup the context for the field instance. """ + + # In order to enforce a consistent style, we error if a redundant + # 'source' argument has been used. For example: + # my_field = serializer.CharField(source='my_field') + assert self._kwargs.get('source') != field_name, ( + "It is redundant to specify `source='%s'` on field '%s' in " + "serializer '%s', as it is the same the field name. " + "Remove the `source` keyword argument." % + (field_name, self.__class__.__name__, parent.__class__.__name__) + ) + self.field_name = field_name self.parent = parent self.root = root diff --git a/tests/test_fields.py b/tests/test_fields.py index 91f3f5db7..c2e030239 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1,6 +1,6 @@ from decimal import Decimal from django.utils import timezone -from rest_framework import fields +from rest_framework import fields, serializers import datetime import django import pytest @@ -69,6 +69,17 @@ class TestFieldOptions: output = field.run_validation() assert output is 123 + def test_redundant_source(self): + class ExampleSerializer(serializers.Serializer): + example_field = serializers.CharField(source='example_field') + with pytest.raises(AssertionError) as exc_info: + ExampleSerializer() + assert str(exc_info.value) == ( + "It is redundant to specify `source='example_field'` on field " + "'CharField' in serializer 'ExampleSerializer', as it is the " + "same the field name. Remove the `source` keyword argument." + ) + # Tests for field input and output values. # ---------------------------------------- From 1420c76453c37c023a901dd0938d717b7b5e52ca Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 25 Sep 2014 10:49:25 +0100 Subject: [PATCH 082/249] Ensure proper sorting of 'choices' attribute on ChoiceField --- rest_framework/fields.py | 9 ++++++--- tests/test_fields.py | 4 ++-- tests/test_metadata.py | 4 ++-- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 9280ea3a3..d1aebbafc 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -2,6 +2,7 @@ from django.conf import settings from django.core import validators from django.core.exceptions import ValidationError from django.utils import timezone +from django.utils.datastructures import SortedDict from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.encoding import is_protected_type from django.utils.translation import ugettext_lazy as _ @@ -166,7 +167,7 @@ class Field(object): # my_field = serializer.CharField(source='my_field') assert self._kwargs.get('source') != field_name, ( "It is redundant to specify `source='%s'` on field '%s' in " - "serializer '%s', as it is the same the field name. " + "serializer '%s', because it is the same as the field name. " "Remove the `source` keyword argument." % (field_name, self.__class__.__name__, parent.__class__.__name__) ) @@ -303,6 +304,7 @@ class BooleanField(Field): 'invalid': _('`{input}` is not a valid boolean.') } default_empty_html = False + initial = False TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True)) FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False)) @@ -365,6 +367,7 @@ class CharField(Field): 'blank': _('This field may not be blank.') } default_empty_html = '' + initial = '' def __init__(self, **kwargs): self.allow_blank = kwargs.pop('allow_blank', False) @@ -775,9 +778,9 @@ class ChoiceField(Field): for item in choices ] if all(pairs): - self.choices = dict([(key, display_value) for key, display_value in choices]) + self.choices = SortedDict([(key, display_value) for key, display_value in choices]) else: - self.choices = dict([(item, item) for item in choices]) + self.choices = SortedDict([(item, item) for item in choices]) # Map the string representation of choices to the underlying value. # Allows us to deal with eg. integer choices while supporting either diff --git a/tests/test_fields.py b/tests/test_fields.py index c2e030239..ebb88d3d6 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -76,8 +76,8 @@ class TestFieldOptions: ExampleSerializer() assert str(exc_info.value) == ( "It is redundant to specify `source='example_field'` on field " - "'CharField' in serializer 'ExampleSerializer', as it is the " - "same the field name. Remove the `source` keyword argument." + "'CharField' in serializer 'ExampleSerializer', because it is the " + "same as the field name. Remove the `source` keyword argument." ) diff --git a/tests/test_metadata.py b/tests/test_metadata.py index 0ebea935f..5ff59c723 100644 --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -84,9 +84,9 @@ class TestMetadata: 'read_only': False, 'label': 'Choice field', 'choices': [ - {'display_name': 'blue', 'value': 'blue'}, + {'display_name': 'red', 'value': 'red'}, {'display_name': 'green', 'value': 'green'}, - {'display_name': 'red', 'value': 'red'} + {'display_name': 'blue', 'value': 'blue'} ] }, 'integer_field': { From b22c9602fa0f717b688fdb35e4f6f42c189af3f3 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 25 Sep 2014 11:04:18 +0100 Subject: [PATCH 083/249] Automatic field binding --- rest_framework/metadata.py | 3 +-- rest_framework/pagination.py | 1 - rest_framework/serializers.py | 30 +++++++++++++++++++++++++----- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py index 580259de1..af4bc396b 100644 --- a/rest_framework/metadata.py +++ b/rest_framework/metadata.py @@ -10,7 +10,6 @@ from __future__ import unicode_literals from django.core.exceptions import PermissionDenied from django.http import Http404 -from django.utils import six from django.utils.datastructures import SortedDict from rest_framework import exceptions, serializers from rest_framework.compat import force_text @@ -100,7 +99,7 @@ class SimpleMetadata(BaseMetadata): """ return SortedDict([ (field_name, self.get_field_info(field)) - for field_name, field in six.iteritems(serializer.fields) + for field_name, field in serializer.fields.items() ]) def get_field_info(self, field): diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index c5a9270a4..fb4512854 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -72,7 +72,6 @@ class BasePaginationSerializer(serializers.Serializer): child=object_serializer(), source='object_list' ) - self.fields[results_field].bind(results_field, self, self) class PaginationSerializer(BasePaginationSerializer): diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 8902294bc..12e380900 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -149,6 +149,28 @@ class SerializerMetaclass(type): return super(SerializerMetaclass, cls).__new__(cls, name, bases, attrs) +class BindingDict(object): + def __init__(self, serializer): + self.serializer = serializer + self.fields = SortedDict() + + def __setitem__(self, key, field): + self.fields[key] = field + field.bind(field_name=key, parent=self.serializer, root=self.serializer) + + def __getitem__(self, key): + return self.fields[key] + + def __delitem__(self, key): + del self.fields[key] + + def items(self): + return self.fields.items() + + def values(self): + return self.fields.values() + + @six.add_metaclass(SerializerMetaclass) class Serializer(BaseSerializer): def __init__(self, *args, **kwargs): @@ -161,11 +183,9 @@ class Serializer(BaseSerializer): # Every new serializer is created with a clone of the field instances. # This allows users to dynamically modify the fields on a serializer # instance without affecting every other serializer class. - self.fields = self._get_base_fields() - - # Setup all the child fields, to provide them with the current context. - for field_name, field in self.fields.items(): - field.bind(field_name, self, self) + self.fields = BindingDict(self) + for key, value in self._get_base_fields().items(): + self.fields[key] = value def __new__(cls, *args, **kwargs): # We override this method in order to automagically create From 64632da3718f501cb8174243385d38b547c2fefd Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 25 Sep 2014 11:40:32 +0100 Subject: [PATCH 084/249] Clean up bind - no longer needs to be called multiple times in nested fields --- rest_framework/fields.py | 21 ++++++++++++++++----- rest_framework/relations.py | 5 ----- rest_framework/serializers.py | 26 +++++++++----------------- tests/test_relations.py | 8 ++++---- 4 files changed, 29 insertions(+), 31 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index d1aebbafc..446732c3a 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -109,7 +109,8 @@ class Field(object): def __init__(self, read_only=False, write_only=False, required=None, default=empty, initial=None, source=None, label=None, help_text=None, style=None, - error_messages=None, validators=[], allow_null=False): + error_messages=None, validators=[], allow_null=False, + context=None): self._creation_counter = Field._creation_counter Field._creation_counter += 1 @@ -135,6 +136,11 @@ class Field(object): self.validators = validators or self.default_validators[:] self.allow_null = allow_null + # These are set up by `.bind()` when the field is added to a serializer. + self.field_name = None + self.parent = None + self._context = {} if (context is None) else context + # Collect default error message from self and parent classes messages = {} for cls in reversed(self.__class__.__mro__): @@ -157,7 +163,14 @@ class Field(object): kwargs = copy.deepcopy(self._kwargs) return self.__class__(*args, **kwargs) - def bind(self, field_name, parent, root): + @property + def context(self): + root = self + while root.parent is not None: + root = root.parent + return root._context + + def bind(self, field_name, parent): """ Setup the context for the field instance. """ @@ -174,10 +187,8 @@ class Field(object): self.field_name = field_name self.parent = parent - self.root = root - self.context = parent.context - # `self.label` should deafult to being based on the field name. + # `self.label` should default to being based on the field name. if self.label is None: self.label = field_name.replace('_', ' ').capitalize() diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 5aa1f8bd8..b37a6fedd 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -243,11 +243,6 @@ class ManyRelation(Field): assert child_relation is not None, '`child_relation` is a required argument.' super(ManyRelation, self).__init__(*args, **kwargs) - def bind(self, field_name, parent, root): - # ManyRelation needs to provide the current context to the child relation. - super(ManyRelation, self).bind(field_name, parent, root) - self.child_relation.bind(field_name, parent, root) - def to_internal_value(self, data): return [ self.child_relation.to_internal_value(item) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 12e380900..04721c7a3 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -150,13 +150,20 @@ class SerializerMetaclass(type): class BindingDict(object): + """ + This dict-like object is used to store fields on a serializer. + + This ensures that whenever fields are added to the serializer we call + `field.bind()` so that the `field_name` and `parent` attributes + can be set correctly. + """ def __init__(self, serializer): self.serializer = serializer self.fields = SortedDict() def __setitem__(self, key, field): self.fields[key] = field - field.bind(field_name=key, parent=self.serializer, root=self.serializer) + field.bind(field_name=key, parent=self.serializer) def __getitem__(self, key): return self.fields[key] @@ -174,7 +181,6 @@ class BindingDict(object): @six.add_metaclass(SerializerMetaclass) class Serializer(BaseSerializer): def __init__(self, *args, **kwargs): - self.context = kwargs.pop('context', {}) kwargs.pop('partial', None) kwargs.pop('many', None) @@ -198,13 +204,6 @@ class Serializer(BaseSerializer): def _get_base_fields(self): return copy.deepcopy(self._declared_fields) - def bind(self, field_name, parent, root): - # If the serializer is used as a field then when it becomes bound - # it also needs to bind all its child fields. - super(Serializer, self).bind(field_name, parent, root) - for field_name, field in self.fields.items(): - field.bind(field_name, self, root) - def get_initial(self): return dict([ (field.field_name, field.get_initial()) @@ -290,17 +289,10 @@ class ListSerializer(BaseSerializer): 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.' - self.context = kwargs.pop('context', {}) kwargs.pop('partial', None) super(ListSerializer, self).__init__(*args, **kwargs) - self.child.bind('', self, self) - - def bind(self, field_name, parent, root): - # If the list is used as a field then it needs to provide - # the current context to the child serializer. - super(ListSerializer, self).bind(field_name, parent, root) - self.child.bind(field_name, self, root) + self.child.bind(field_name='', parent=self) def get_value(self, dictionary): # We override the default field access in order to support diff --git a/tests/test_relations.py b/tests/test_relations.py index c29618ce2..2d11672b8 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -51,7 +51,7 @@ class TestHyperlinkedIdentityField(APISimpleTestCase): self.instance = MockObject(pk=1, name='foo') self.field = serializers.HyperlinkedIdentityField(view_name='example') self.field.reverse = mock_reverse - self.field.context = {'request': True} + self.field._context = {'request': True} def test_representation(self): representation = self.field.to_representation(self.instance) @@ -62,7 +62,7 @@ class TestHyperlinkedIdentityField(APISimpleTestCase): assert representation is None def test_representation_with_format(self): - self.field.context['format'] = 'xml' + self.field._context['format'] = 'xml' representation = self.field.to_representation(self.instance) assert representation == 'http://example.org/example/1.xml/' @@ -91,14 +91,14 @@ class TestHyperlinkedIdentityFieldWithFormat(APISimpleTestCase): self.instance = MockObject(pk=1, name='foo') self.field = serializers.HyperlinkedIdentityField(view_name='example', format='json') self.field.reverse = mock_reverse - self.field.context = {'request': True} + self.field._context = {'request': True} def test_representation(self): representation = self.field.to_representation(self.instance) assert representation == 'http://example.org/example/1/' def test_representation_with_format(self): - self.field.context['format'] = 'xml' + self.field._context['format'] = 'xml' representation = self.field.to_representation(self.instance) assert representation == 'http://example.org/example/1.json/' From b47ca158b9ba9733baad080e648d24b0465ec697 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 25 Sep 2014 12:09:12 +0100 Subject: [PATCH 085/249] Check for redundant on SerializerMethodField --- rest_framework/fields.py | 29 ++++++++++++++++++++++------- tests/test_fields.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 7 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 446732c3a..328e93eff 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -178,7 +178,7 @@ class Field(object): # In order to enforce a consistent style, we error if a redundant # 'source' argument has been used. For example: # my_field = serializer.CharField(source='my_field') - assert self._kwargs.get('source') != field_name, ( + assert self.source != field_name, ( "It is redundant to specify `source='%s'` on field '%s' in " "serializer '%s', because it is the same as the field name. " "Remove the `source` keyword argument." % @@ -883,17 +883,32 @@ class SerializerMethodField(Field): def get_extra_info(self, obj): return ... # Calculate some data to return. """ - def __init__(self, method_attr=None, **kwargs): - self.method_attr = method_attr + def __init__(self, method_name=None, **kwargs): + self.method_name = method_name kwargs['source'] = '*' kwargs['read_only'] = True super(SerializerMethodField, self).__init__(**kwargs) + def bind(self, field_name, parent): + # In order to enforce a consistent style, we error if a redundant + # 'method_name' argument has been used. For example: + # my_field = serializer.CharField(source='my_field') + default_method_name = 'get_{field_name}'.format(field_name=field_name) + assert self.method_name != default_method_name, ( + "It is redundant to specify `%s` on SerializerMethodField '%s' in " + "serializer '%s', because it is the same as the default method name. " + "Remove the `method_name` argument." % + (self.method_name, field_name, parent.__class__.__name__) + ) + + # The method name should default to `get_{field_name}`. + if self.method_name is None: + self.method_name = default_method_name + + super(SerializerMethodField, self).bind(field_name, parent) + def to_representation(self, value): - method_attr = self.method_attr - if method_attr is None: - method_attr = 'get_{field_name}'.format(field_name=self.field_name) - method = getattr(self.parent, method_attr) + method = getattr(self.parent, self.method_name) return method(value) diff --git a/tests/test_fields.py b/tests/test_fields.py index ebb88d3d6..003b4b8c6 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -710,3 +710,33 @@ class TestMultipleChoiceField(FieldValues): ('diesel', 'Diesel'), ] ) + + +# Tests for SerializerMethodField. +# -------------------------------- + +class TestSerializerMethodField: + def test_serializer_method_field(self): + class ExampleSerializer(serializers.Serializer): + example_field = serializers.SerializerMethodField() + + def get_example_field(self, obj): + return 'ran get_example_field(%d)' % obj['example_field'] + + serializer = ExampleSerializer({'example_field': 123}) + assert serializer.data == { + 'example_field': 'ran get_example_field(123)' + } + + def test_redundant_method_name(self): + class ExampleSerializer(serializers.Serializer): + example_field = serializers.SerializerMethodField('get_example_field') + + with pytest.raises(AssertionError) as exc_info: + ExampleSerializer() + assert str(exc_info.value) == ( + "It is redundant to specify `get_example_field` on " + "SerializerMethodField 'example_field' in serializer " + "'ExampleSerializer', because it is the same as the default " + "method name. Remove the `method_name` argument." + ) From 8ee92f8a18c3a31a2a95233f36754203dc60bb18 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 25 Sep 2014 13:10:33 +0100 Subject: [PATCH 086/249] Refuse to downcast from datetime to date or time --- rest_framework/fields.py | 150 +++++++++++++++++++++------------------ tests/test_fields.py | 3 +- 2 files changed, 83 insertions(+), 70 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 328e93eff..d855e6fdc 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -608,6 +608,71 @@ class DecimalField(Field): # Date & time fields... +class DateTimeField(Field): + default_error_messages = { + 'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}'), + 'date': _('Expected a datetime but got a date.'), + } + format = api_settings.DATETIME_FORMAT + input_formats = api_settings.DATETIME_INPUT_FORMATS + default_timezone = timezone.get_default_timezone() if settings.USE_TZ else None + + def __init__(self, format=empty, input_formats=None, default_timezone=None, *args, **kwargs): + self.format = format if format is not empty else self.format + self.input_formats = input_formats if input_formats is not None else self.input_formats + self.default_timezone = default_timezone if default_timezone is not None else self.default_timezone + super(DateTimeField, self).__init__(*args, **kwargs) + + def enforce_timezone(self, value): + """ + When `self.default_timezone` is `None`, always return naive datetimes. + When `self.default_timezone` is not `None`, always return aware datetimes. + """ + if (self.default_timezone is not None) and not timezone.is_aware(value): + return timezone.make_aware(value, self.default_timezone) + elif (self.default_timezone is None) and timezone.is_aware(value): + return timezone.make_naive(value, timezone.UTC()) + return value + + def to_internal_value(self, value): + if (isinstance(value, datetime.date) and not isinstance(value, datetime.datetime): + self.fail('date') + + if isinstance(value, datetime.datetime): + return self.enforce_timezone(value) + + for format in self.input_formats: + if format.lower() == ISO_8601: + try: + parsed = parse_datetime(value) + except (ValueError, TypeError): + pass + else: + if parsed is not None: + return self.enforce_timezone(parsed) + else: + try: + parsed = datetime.datetime.strptime(value, format) + except (ValueError, TypeError): + pass + else: + return self.enforce_timezone(parsed) + + humanized_format = humanize_datetime.datetime_formats(self.input_formats) + self.fail('invalid', format=humanized_format) + + def to_representation(self, value): + if value is None or self.format is None: + return value + + if self.format.lower() == ISO_8601: + ret = value.isoformat() + if ret.endswith('+00:00'): + ret = ret[:-6] + 'Z' + return ret + return value.strftime(self.format) + + class DateField(Field): default_error_messages = { 'invalid': _('Date has wrong format. Use one of these formats instead: {format}'), @@ -652,79 +717,20 @@ class DateField(Field): if value is None or self.format is None: return value - if isinstance(value, datetime.datetime): - value = value.date() + # Applying a `DateField` to a datetime value is almost always + # not a sensible thing to do, as it means naively dropping + # any explicit or implicit timezone info. + assert not isinstance(value, datetime.datetime), ( + 'Expected a `date`, but got a `datetime`. Refusing to coerce, ' + 'as this may mean losing timezone information. Use a custom ' + 'read-only field and deal with timezone issues explicitly.' + ) if self.format.lower() == ISO_8601: return value.isoformat() return value.strftime(self.format) -class DateTimeField(Field): - default_error_messages = { - 'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}'), - 'date': _('Expected a datetime but got a date.'), - } - format = api_settings.DATETIME_FORMAT - input_formats = api_settings.DATETIME_INPUT_FORMATS - default_timezone = timezone.get_default_timezone() if settings.USE_TZ else None - - def __init__(self, format=empty, input_formats=None, default_timezone=None, *args, **kwargs): - self.format = format if format is not empty else self.format - self.input_formats = input_formats if input_formats is not None else self.input_formats - self.default_timezone = default_timezone if default_timezone is not None else self.default_timezone - super(DateTimeField, self).__init__(*args, **kwargs) - - def enforce_timezone(self, value): - """ - When `self.default_timezone` is `None`, always return naive datetimes. - When `self.default_timezone` is not `None`, always return aware datetimes. - """ - if (self.default_timezone is not None) and not timezone.is_aware(value): - return timezone.make_aware(value, self.default_timezone) - elif (self.default_timezone is None) and timezone.is_aware(value): - return timezone.make_naive(value, timezone.UTC()) - return value - - def to_internal_value(self, value): - if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime): - self.fail('date') - - if isinstance(value, datetime.datetime): - return self.enforce_timezone(value) - - for format in self.input_formats: - if format.lower() == ISO_8601: - try: - parsed = parse_datetime(value) - except (ValueError, TypeError): - pass - else: - if parsed is not None: - return self.enforce_timezone(parsed) - else: - try: - parsed = datetime.datetime.strptime(value, format) - except (ValueError, TypeError): - pass - else: - return self.enforce_timezone(parsed) - - humanized_format = humanize_datetime.datetime_formats(self.input_formats) - self.fail('invalid', format=humanized_format) - - def to_representation(self, value): - if value is None or self.format is None: - return value - - if self.format.lower() == ISO_8601: - ret = value.isoformat() - if ret.endswith('+00:00'): - ret = ret[:-6] + 'Z' - return ret - return value.strftime(self.format) - - class TimeField(Field): default_error_messages = { 'invalid': _('Time has wrong format. Use one of these formats instead: {format}'), @@ -765,8 +771,14 @@ class TimeField(Field): if value is None or self.format is None: return value - if isinstance(value, datetime.datetime): - value = value.time() + # Applying a `TimeField` to a datetime value is almost always + # not a sensible thing to do, as it means naively dropping + # any explicit or implicit timezone info. + assert not isinstance(value, datetime.datetime), ( + 'Expected a `time`, but got a `datetime`. Refusing to coerce, ' + 'as this may mean losing timezone information. Use a custom ' + 'read-only field and deal with timezone issues explicitly.' + ) if self.format.lower() == ISO_8601: return value.isoformat() diff --git a/tests/test_fields.py b/tests/test_fields.py index 003b4b8c6..b29acad81 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -173,7 +173,8 @@ class TestNullBooleanField(FieldValues): 'null': None, True: True, False: False, - None: None + None: None, + 'other': True } field = fields.NullBooleanField() From 3a5335f09f58439f8e3c0bddbed8e4c7eeb32482 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 25 Sep 2014 13:12:02 +0100 Subject: [PATCH 087/249] Fix syntax error --- rest_framework/fields.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index d855e6fdc..7beccbb71 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -635,7 +635,7 @@ class DateTimeField(Field): return value def to_internal_value(self, value): - if (isinstance(value, datetime.date) and not isinstance(value, datetime.datetime): + if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime): self.fail('date') if isinstance(value, datetime.datetime): From 417fe1b675bd1d42518fb89a6f81547caef5b735 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 25 Sep 2014 13:37:26 +0100 Subject: [PATCH 088/249] Partial support --- rest_framework/fields.py | 35 +++++++++++++++++++++++++---------- rest_framework/serializers.py | 6 ++++-- tests/test_serializer.py | 33 ++++++++++++++++++++++++++++++++- 3 files changed, 61 insertions(+), 13 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 7beccbb71..032bfd048 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -109,8 +109,7 @@ class Field(object): def __init__(self, read_only=False, write_only=False, required=None, default=empty, initial=None, source=None, label=None, help_text=None, style=None, - error_messages=None, validators=[], allow_null=False, - context=None): + error_messages=None, validators=[], allow_null=False): self._creation_counter = Field._creation_counter Field._creation_counter += 1 @@ -139,7 +138,6 @@ class Field(object): # These are set up by `.bind()` when the field is added to a serializer. self.field_name = None self.parent = None - self._context = {} if (context is None) else context # Collect default error message from self and parent classes messages = {} @@ -163,13 +161,6 @@ class Field(object): kwargs = copy.deepcopy(self._kwargs) return self.__class__(*args, **kwargs) - @property - def context(self): - root = self - while root.parent is not None: - root = root.parent - return root._context - def bind(self, field_name, parent): """ Setup the context for the field instance. @@ -254,6 +245,8 @@ class Field(object): """ if data is empty: if self.required: + if getattr(self.root, 'partial', False): + raise SkipField() self.fail('required') return self.get_default() @@ -304,7 +297,29 @@ class Field(object): raise AssertionError(msg) raise ValidationError(msg.format(**kwargs)) + @property + def root(self): + """ + Returns the top-level serializer for this field. + """ + root = self + while root.parent is not None: + root = root.parent + return root + + @property + def context(self): + """ + Returns the context as passed to the root serializer on initialization. + """ + return getattr(self.root, '_context', {}) + def __repr__(self): + """ + Fields are represented using their initial calling arguments. + This allows us to create descriptive representations for serializer + instances that show all the declared fields on the serializer. + """ return representation.field_repr(self) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 04721c7a3..b6a1898ca 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -181,8 +181,9 @@ class BindingDict(object): @six.add_metaclass(SerializerMetaclass) class Serializer(BaseSerializer): def __init__(self, *args, **kwargs): - kwargs.pop('partial', None) kwargs.pop('many', None) + self.partial = kwargs.pop('partial', False) + self._context = kwargs.pop('context', {}) super(Serializer, self).__init__(*args, **kwargs) @@ -289,7 +290,8 @@ class ListSerializer(BaseSerializer): 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.' - kwargs.pop('partial', None) + self.partial = kwargs.pop('partial', False) + self._context = kwargs.pop('context', {}) super(ListSerializer, self).__init__(*args, **kwargs) self.child.bind(field_name='', parent=self) diff --git a/tests/test_serializer.py b/tests/test_serializer.py index b0eb4e270..5646f9940 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -1,3 +1,35 @@ +from rest_framework import serializers + + +# Tests for core functionality. +# ----------------------------- + +class TestSerializer: + def setup(self): + class ExampleSerializer(serializers.Serializer): + char = serializers.CharField() + integer = serializers.IntegerField() + self.Serializer = ExampleSerializer + + def test_valid_serializer(self): + serializer = self.Serializer(data={'char': 'abc', 'integer': 123}) + assert serializer.is_valid() + assert serializer.validated_data == {'char': 'abc', 'integer': 123} + assert serializer.errors == {} + + def test_invalid_serializer(self): + serializer = self.Serializer(data={'char': 'abc'}) + assert not serializer.is_valid() + assert serializer.validated_data == {} + assert serializer.errors == {'integer': ['This field is required.']} + + def test_partial_validation(self): + serializer = self.Serializer(data={'char': 'abc'}, partial=True) + assert serializer.is_valid() + assert serializer.validated_data == {'char': 'abc'} + assert serializer.errors == {} + + # # -*- coding: utf-8 -*- # from __future__ import unicode_literals # from django.db import models @@ -334,7 +366,6 @@ # Check _data attribute is cleared on `save()` # Regression test for #1116 -# — id field is not populated if `data` is accessed prior to `save()` # """ # serializer = ActionItemSerializer(self.actionitem) # self.assertIsNone(serializer.data.get('id', None), 'New instance. `id` should not be set.') From 2859eaf524bca23f27e666d24a0b63ba61698a76 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 10:46:52 +0100 Subject: [PATCH 089/249] request.data attribute --- docs/topics/3.0-announcement.md | 344 ++++++++++++++++++++++++++++-- rest_framework/authtoken/views.py | 2 +- rest_framework/fields.py | 51 +++-- rest_framework/filters.py | 6 +- rest_framework/generics.py | 4 +- rest_framework/mixins.py | 6 +- rest_framework/negotiation.py | 4 +- rest_framework/renderers.py | 4 +- rest_framework/request.py | 37 +++- rest_framework/serializers.py | 21 +- tests/test_fields.py | 140 +++++++++++- tests/test_generics.py | 2 +- tests/test_serializer.py | 62 ++++++ 13 files changed, 610 insertions(+), 73 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index cd883cdd8..1795611c0 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -4,36 +4,65 @@ See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-fr # REST framework 3.0 -**Note incremental nature, discuss upgrading.** +**TODO**: Note incremental nature, discuss upgrading, motivation, features. -## Motivation - -**TODO** +* Serializer reprs. +* Non-magical model serializers. +* Base serializer class. +* Clean logic in views, serializers, fields. --- ## Request objects -#### The `request.data` property. +#### The `.data` and `.query_params` properties. -**TODO** +The usage of `request.DATA` and `request.FILES` is now discouraged in favor of a single `request.data` attribute that contains *all* the parsed data. -#### The parser API. +Having seperate attributes is reasonable for web applications that only ever parse URL encoded or MultiPart requests, but makes less sense for the general-purpose request parsing that REST framework supports. -**TODO** +You may now pass all the request data to a serializer class in a single argument: + + ExampleSerializer(data=request.data) + +Instead of passing the files argument seperately: + + # Don't do this... + ExampleSerializer(data=request.DATA, files=request.FILES) + + +The usage of `request.QUERY_PARAMS` is now discouraged in favor of the lowercased `request.query_params`. ## Serializers #### Single-step object creation. +#### The `.create()` and `.update()` methods. + **TODO**: Drop `.restore_object()`, use `.create()` and `.update()` which should save the instance. -**TODO**: Drop`.object`, use `.validated_data` or get the instance with `.save()`. +#### Use `.validated_data` instead of `.object`. -#### The `BaseSerializer` class. +You must now use the `.validated_data` attribute if you need to inspect the data before saving, rather than using the `.object` attribute, which no longer exists. -**TODO** +For example the following code *is no longer valid*: + if serializer.is_valid(): + name = serializer.object.name # Inspect validated field data. + logging.info('Creating ticket "%s"' % name) + serializer.object.user = request.user # Include the user when saving. + serializer.save() + +Instead of using `.object` to inspect a partially constructed instance, you would now use `.validated_data` to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the `.save()` method using the `extras` keyword argument. + +The corresponding code would now look like this: + + if serializer.is_valid(): + name = serializer.validated_data['name'] # Inspect validated field data. + logging.info('Creating ticket "%s"' % name) + extras = {'user': request.user} # Include the user when saving. + serializer.save(extras=extras) + #### Always use `fields`, not `exclude`. The `exclude` option is no longer available. You should use the more explicit `fields` option instead. @@ -111,42 +140,287 @@ These fields will be mapped to `serializers.ReadOnlyField()` instances. message = CharField(max_length=1000) expiry_date = ReadOnlyField() +#### The `ListSerializer` class. + +The `ListSerializer` class has now been added, and allows you to create base serializer classes for only accepting multiple inputs. + + class MultipleUserSerializer(ListSerializer): + child = UserSerializer() + +You can also still use the `many=True` argument to serializer classes. It's worth noting that `many=True` argument transparently creates a `ListSerializer` instance, allowing the validation logic for list and non-list data to be cleanly seperated in the REST framework codebase. + +See also the new `ListField` class, which validates input in the same way, but does not include the serializer interfaces of `.is_valid()`, `.data`, `.save()` and so on. + +#### The `BaseSerializer` class. + +REST framework now includes a simple `BaseSerializer` class that can be used to easily support alternative serialization and deserialization styles. + +This class implements the same basic API as the `Serializer` class: + +* `.data` - Returns the outgoing primative representation. +* `.is_valid()` - Deserializes and validates incoming data. +* `.validated_data` - Returns the validated incoming data. +* `.errors` - Returns an errors during validation. +* `.save()` - Persists the validated data into an object instance. + +There are four mathods that can be overriding, depending on what functionality you want the serializer class to support: + +* `.to_representation()` - Override this to support serialization, for read operations. +* `.to_internal_value()` - Override this to support deserialization, for write operations. +* `.create()` and `.update()` - Overide either or both of these to support saving instances. + +##### Read-only serializers. + +To implement a read-only serializer using the `BaseSerializer` class, we just need to override the `.to_representation()` method. Let's take a look at an example using a simple Django model: + + class HighScore(models.Model): + created = models.DateTimeField(auto_now_add=True) + player_name = models.CharField(max_length=10) + score = models.IntegerField() + +It's simple to create a read-only serializer for converting `HighScore` instances into primative data types. + + class HighScoreSerializer(serializers.BaseSerializer): + def to_representation(self, obj): + return { + 'score': obj.score, + 'player_name': obj.player_name + } + +We can now use this class to serialize single `HighScore` instances: + + @api_view(['GET']) + def high_score(request, pk): + instance = HighScore.objects.get(pk=pk) + serializer = HighScoreSerializer(instance) + return Response(serializer.data) + +Or use it to serialize multiple instances: + + @api_view(['GET']) + def all_high_scores(request): + queryset = HighScore.objects.order_by('-score') + serializer = HighScoreSerializer(queryset, many=True) + return Response(serializer.data) + +##### Read-write serializers. + +To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `ValidationError` if the supplied data is in an incorrect format. + +Once you've implemented `.to_internal_value()`, the basic validation API will be available on the serializer, and you will be able to use `.is_valid()`, `.validated_data` and `.errors`. + +If you want to also support `.save()` you'll need to also implement either or both of the `.create()` and `.update()` methods. + +Here's a complete example of our previous `HighScoreSerializer`, that's been updated to support both read and write operations. + + class HighScoreSerializer(serializers.BaseSerializer): + def to_internal_value(self, data): + score = data.get('score') + player_name = data.get('player_name') + + # Perform the data validation. + if not score: + raise ValidationError({ + 'score': 'This field is required.' + }) + if not player_name: + raise ValidationError({ + 'player_name': 'This field is required.' + }) + if len(player_name) > 10: + raise ValidationError({ + 'player_name': 'May not be more than 10 characters.' + }) + + # Return the validated values. This will be available as + # the `.validated_data` property. + return { + 'score': int(score), + 'player_name': player_name + } + + def to_representation(self, obj): + return { + 'score': obj.score, + 'player_name': obj.player_name + } + + def create(self, validated_data): + return HighScore.objects.create(**validated_data) + +#### Creating new base classes with `BaseSerializer`. + +The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles or for integrating with different storage backends. + +The following class is an example of a generic serializer that can handle coercing aribitrary objects into primative representations. + + class ObjectSerializer(serializers.BaseSerializer): + """ + A read-only serializer that coerces arbitrary complex objects + into primative representations. + """ + def to_representation(self, obj): + for attribute_name in dir(obj): + attribute = getattr(obj, attribute_name) + if attribute_name('_'): + # Ignore private attributes. + pass + elif hasattr(attribute, '__call__'): + # Ignore methods and other callables. + pass + elif isinstance(attribute, (str, int, bool, float, type(None))): + # Primative types can be passed through unmodified. + output[attribute_name] = attribute + elif isinstance(attribute, list): + # Recursivly deal with items in lists. + output[attribute_name] = [ + self.to_representation(item) for item in attribute + ] + elif isinstance(attribute, dict): + # Recursivly deal with items in dictionarys. + output[attribute_name] = { + str(key): self.to_representation(value) + for key, value in attribute.items() + } + else: + # Force anything else to its string representation. + output[attribute_name] = str(attribute) ## Serializer fields #### The `Field` and `ReadOnly` field classes. -**TODO** +There are some minor tweaks to the field base classes. + +Previously we had these two base classes: + +* `Field` as the base class for read-only fields. A default implementation was included for serializing data. +* `WriteableField` as the base class for read-write fields. + +We now use the following: + +* `Field` is the base class for all fields. It does not include any default implementation for either serializing or deserializing data. +* `ReadOnlyField` is a concrete implementation for read-only fields that simply returns the attribute value without modification. + +#### The `required`, `allow_none`, `allow_blank` and `default` arguments. + +REST framework now has more explict and clear control over validating empty values for fields. + +Previously the meaning of the `required=False` keyword argument was underspecified. In practice it's use meant that a field could either be not included in the input, or it could be included, but be `None`. + +We now have a better seperation, with seperate `required` and `allow_none` arguments. + +The following set of arguments are used to control validation of empty values: + +* `required=False`: The value does not need to be present in the input, and will not be passed to `.create()` or `.update()` if it is not seen. +* `default=<value>`: The value does not need to be present in the input, and a default value will be passed to `.create()` or `.update()` if it is not seen. +* `allow_none=True`: `None` is a valid input. +* `allow_blank=True`: `''` is valid input. For `CharField` and subclasses only. + +Typically you'll want to use `required=False` if the corresponding model field has a default value, and additionally set either `allow_none=True` or `allow_blank=True` if required. + +The `default` argument is there if you need it, but you'll more typically want defaults to be set on model fields, rather than serializer fields. #### Coercing output types. -**TODO** +The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an `IntegerField` would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior. -#### The `ListSerializer` class. +#### The `ListField` class. -**TODO** +The `ListField` class has now been added. This field validates list input. It takes a `child` keyword argument which is used to specify the field used to validate each item in the list. For example: + + scores = ListField(child=IntegerField(min_value=0, max_value=100)) + +You can also use a declarative style to create new subclasses of `ListField`, like this: + + class ScoresField(ListField): + child = IntegerField(min_value=0, max_value=100) + +We can now use the `ScoresField` class inside another serializer: + + scores = ScoresField() + +See also the new `ListSerializer` class, which validates input in the same way, but also includes the serializer interfaces of `.is_valid()`, `.data`, `.save()` and so on. + +#### The `ChoiceField` class may now accept a flat list. + +The `ChoiceField` class may now accept a list of choices in addition to the existing style of using a list of pairs of `(name, display_value)`. The following is now valid: + + color = ChoiceField(choices=['red', 'green', 'blue']) #### The `MultipleChoiceField` class. -**TODO** +The `MultipleChoiceField` class has been added. This field acts like `ChoiceField`, but returns a set, which may include none, one or many of the valid choices. #### Changes to the custom field API. -**TODO** `to_representation`, `to_internal_value`. +The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_representation(self, value)` and `to_internal_value(self, data)`. -#### Explicit `querysets` required on relational fields. +The `field_from_native()` and `field_to_native()` methods are removed. -**TODO** +#### Explicit `queryset` required on relational fields. + +Previously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a `ModelSerializer`. + +This code *would be valid* in `2.4.3`: + + class AccountSerializer(serializers.ModelSerializer): + organisations = serializers.SlugRelatedField(slug_field='name') + + class Meta: + model = Account + +However this code *would not be valid* in `2.4.3`: + + # Missing `queryset` + class AccountSerializer(serializers.Serializer): + organisations = serializers.SlugRelatedField(slug_field='name') + + def restore_object(self, attrs, instance=None): + # ... + +The queryset argument is now always required for writable relational fields. +This removes some magic and makes it easier and more obvious to move between implict `ModelSerializer` classes and explicit `Serializer` classes. + + class AccountSerializer(serializers.ModelSerializer): + organisations = serializers.SlugRelatedField( + slug_field='name', + queryset=Organisation.objects.all() + ) + + class Meta: + model = Account + +The `queryset` argument is only ever required for writable fields, and is not required or valid for fields with `read_only=True`. #### Optional argument to `SerializerMethodField`. -**TODO** +The argument to `SerializerMethodField` is now optional, and defaults to `get_<field_name>`. For example the following is valid: + + class AccountSerializer(serializers.Serializer): + # `method_name='get_billing_details'` by default. + billing_details = serializers.SerializerMethodField() + + def get_billing_details(self, account): + return calculate_billing(account) + +In order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code *will raise an error*: + + billing_details = serializers.SerializerMethodField('get_billing_details') + +#### Enforcing consistent `source` usage. + +I've see several codebases that unneccessarily include the `source` argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that `source` is usually not required. + +The following usage will *now raise an error*: + + email = serializers.EmailField(source='email') ## Generic views #### Simplification of view logic. -**TODO** +The view logic for the default method handlers has been significantly simplified, due to the new serializers API. #### Removal of pre/post save hooks. @@ -169,6 +443,20 @@ I would personally recommend that developers treat view instances as immutable o #### PUT as create. +Allowing `PUT` as create operations is problematic, as it neccessarily exposes information about the existence or non-existance of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is neccessarily a better default behavior than simply returning `404` responses. + +Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but we've now opted for the 404 behavior as the default, due to it being simpler and more obvious. + +If you need to restore the previous behavior you can include the `AllowPUTAsCreateMixin` class in your view. This class can be imported from `rest_framework.mixins`. + +#### Customizing error responses. + +The generic views now raise `ValidationError` for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a `400 Bad Request` response directly. + +This change means that you can now easily cusomize the style of error responses across your entire API, without having to modify any of the generic views. + +## The metadata API + **TODO** ## API style @@ -241,3 +529,17 @@ Or modify it on an individual serializer field, using the `corece_to_string` key ) The default JSON renderer will return float objects for uncoerced `Decimal` instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs. + +## What's coming next. + +3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes. + +The 3.1 release is planned to address improvements in the following components: + +* Request parsing, mediatypes & the implementation of the browsable API. +* Introduction of a new pagination API. +* Better support for API versioning. + +The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API. + +You can follow development on the GitHub site, where we use [milestones to indicate planning timescales](https://github.com/tomchristie/django-rest-framework/milestones). diff --git a/rest_framework/authtoken/views.py b/rest_framework/authtoken/views.py index 94e6f061f..103abb27c 100644 --- a/rest_framework/authtoken/views.py +++ b/rest_framework/authtoken/views.py @@ -16,7 +16,7 @@ class ObtainAuthToken(APIView): model = Token def post(self, request): - serializer = self.serializer_class(data=request.DATA) + 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) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 032bfd048..ec07a4134 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -56,7 +56,7 @@ def get_attribute(instance, attrs): except AttributeError as exc: try: return instance[attr] - except (KeyError, TypeError): + except (KeyError, TypeError, AttributeError): raise exc return instance @@ -90,6 +90,7 @@ NOT_READ_ONLY_WRITE_ONLY = 'May not set both `read_only` and `write_only`' NOT_READ_ONLY_REQUIRED = 'May not set both `read_only` and `required`' NOT_READ_ONLY_DEFAULT = 'May not set both `read_only` and `default`' NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`' +USE_READONLYFIELD = 'Field(read_only=True) should be ReadOnlyField' MISSING_ERROR_MESSAGE = ( 'ValidationError raised by `{class_name}`, but error key `{key}` does ' 'not exist in the `error_messages` dictionary.' @@ -105,9 +106,10 @@ class Field(object): } default_validators = [] default_empty_html = None + initial = None def __init__(self, read_only=False, write_only=False, - required=None, default=empty, initial=None, source=None, + required=None, default=empty, initial=empty, source=None, label=None, help_text=None, style=None, error_messages=None, validators=[], allow_null=False): self._creation_counter = Field._creation_counter @@ -122,13 +124,14 @@ class Field(object): assert not (read_only and required), NOT_READ_ONLY_REQUIRED assert not (read_only and default is not empty), NOT_READ_ONLY_DEFAULT assert not (required and default is not empty), NOT_REQUIRED_DEFAULT + assert not (read_only and self.__class__ == Field), USE_READONLYFIELD self.read_only = read_only self.write_only = write_only self.required = required self.default = default self.source = source - self.initial = initial + self.initial = self.initial if (initial is empty) else initial self.label = label self.help_text = help_text self.style = {} if style is None else style @@ -146,24 +149,10 @@ class Field(object): messages.update(error_messages or {}) self.error_messages = messages - def __new__(cls, *args, **kwargs): - """ - When a field is instantiated, we store the arguments that were used, - so that we can present a helpful representation of the object. - """ - instance = super(Field, cls).__new__(cls) - instance._args = args - instance._kwargs = kwargs - return instance - - def __deepcopy__(self, memo): - args = copy.deepcopy(self._args) - kwargs = copy.deepcopy(self._kwargs) - return self.__class__(*args, **kwargs) - def bind(self, field_name, parent): """ - Setup the context for the field instance. + Initializes the field name and parent for the field instance. + Called when a field is added to the parent serializer instance. """ # In order to enforce a consistent style, we error if a redundant @@ -244,9 +233,9 @@ class Field(object): validated data. """ if data is empty: + if getattr(self.root, 'partial', False): + raise SkipField() if self.required: - if getattr(self.root, 'partial', False): - raise SkipField() self.fail('required') return self.get_default() @@ -314,6 +303,25 @@ class Field(object): """ return getattr(self.root, '_context', {}) + def __new__(cls, *args, **kwargs): + """ + When a field is instantiated, we store the arguments that were used, + so that we can present a helpful representation of the object. + """ + instance = super(Field, cls).__new__(cls) + instance._args = args + instance._kwargs = kwargs + return instance + + def __deepcopy__(self, memo): + """ + When cloning fields we instantiate using the arguments it was + originally created with, rather than copying the complete state. + """ + args = copy.deepcopy(self._args) + kwargs = copy.deepcopy(self._kwargs) + return self.__class__(*args, **kwargs) + def __repr__(self): """ Fields are represented using their initial calling arguments. @@ -358,6 +366,7 @@ class NullBooleanField(Field): 'invalid': _('`{input}` is not a valid boolean.') } default_empty_html = None + initial = None TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True)) FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False)) NULL_VALUES = set(('n', 'N', 'null', 'Null', 'NULL', '', None)) diff --git a/rest_framework/filters.py b/rest_framework/filters.py index c580f9351..085dfe659 100644 --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -64,7 +64,7 @@ class DjangoFilterBackend(BaseFilterBackend): filter_class = self.get_filter_class(view, queryset) if filter_class: - return filter_class(request.QUERY_PARAMS, queryset=queryset).qs + return filter_class(request.query_params, queryset=queryset).qs return queryset @@ -78,7 +78,7 @@ class SearchFilter(BaseFilterBackend): Search terms are set by a ?search=... query parameter, and may be comma and/or whitespace delimited. """ - params = request.QUERY_PARAMS.get(self.search_param, '') + params = request.query_params.get(self.search_param, '') return params.replace(',', ' ').split() def construct_search(self, field_name): @@ -121,7 +121,7 @@ class OrderingFilter(BaseFilterBackend): the `ordering_param` value on the OrderingFilter or by specifying an `ORDERING_PARAM` value in the API settings. """ - params = request.QUERY_PARAMS.get(self.ordering_param) + params = request.query_params.get(self.ordering_param) if params: return [param.strip() for param in params.split(',')] diff --git a/rest_framework/generics.py b/rest_framework/generics.py index f49b0a439..cf903dab3 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -112,7 +112,7 @@ class GenericAPIView(views.APIView): paginator = self.paginator_class(queryset, page_size) page_kwarg = self.kwargs.get(self.page_kwarg) - page_query_param = self.request.QUERY_PARAMS.get(self.page_kwarg) + page_query_param = self.request.query_params.get(self.page_kwarg) page = page_kwarg or page_query_param or 1 try: page_number = paginator.validate_number(page) @@ -166,7 +166,7 @@ class GenericAPIView(views.APIView): if self.paginate_by_param: try: return strict_positive_int( - self.request.QUERY_PARAMS[self.paginate_by_param], + self.request.query_params[self.paginate_by_param], cutoff=self.max_paginate_by ) except (KeyError, ValueError): diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index 14a6b44b1..04b7a7636 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -18,7 +18,7 @@ class CreateModelMixin(object): Create a model instance. """ def create(self, request, *args, **kwargs): - serializer = self.get_serializer(data=request.DATA) + serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() headers = self.get_success_headers(serializer.data) @@ -62,7 +62,7 @@ class UpdateModelMixin(object): def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() - serializer = self.get_serializer(instance, data=request.DATA, partial=partial) + serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) @@ -95,7 +95,7 @@ class AllowPUTAsCreateMixin(object): def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object_or_none() - serializer = self.get_serializer(instance, data=request.DATA, partial=partial) + serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) if instance is None: diff --git a/rest_framework/negotiation.py b/rest_framework/negotiation.py index ca7b53978..1838130a9 100644 --- a/rest_framework/negotiation.py +++ b/rest_framework/negotiation.py @@ -38,7 +38,7 @@ class DefaultContentNegotiation(BaseContentNegotiation): """ # Allow URL style format override. eg. "?format=json format_query_param = self.settings.URL_FORMAT_OVERRIDE - format = format_suffix or request.QUERY_PARAMS.get(format_query_param) + format = format_suffix or request.query_params.get(format_query_param) if format: renderers = self.filter_renderers(renderers, format) @@ -87,5 +87,5 @@ class DefaultContentNegotiation(BaseContentNegotiation): Allows URL style accept override. eg. "?accept=application/json" """ header = request.META.get('HTTP_ACCEPT', '*/*') - header = request.QUERY_PARAMS.get(self.settings.URL_ACCEPT_OVERRIDE, header) + header = request.query_params.get(self.settings.URL_ACCEPT_OVERRIDE, header) return [token.strip() for token in header.split(',')] diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 3bf03e62c..225f9fe8f 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -120,7 +120,7 @@ class JSONPRenderer(JSONRenderer): Determine the name of the callback to wrap around the json output. """ request = renderer_context.get('request', None) - params = request and request.QUERY_PARAMS or {} + params = request and request.query_params or {} return params.get(self.callback_parameter, self.default_callback) def render(self, data, accepted_media_type=None, renderer_context=None): @@ -426,7 +426,7 @@ class BrowsableAPIRenderer(BaseRenderer): """ if request.method == method: try: - data = request.DATA + data = request.data # files = request.FILES except ParseError: data = None diff --git a/rest_framework/request.py b/rest_framework/request.py index 275326614..d80baa705 100644 --- a/rest_framework/request.py +++ b/rest_framework/request.py @@ -4,7 +4,7 @@ The Request class is used as a wrapper around the standard request object. The wrapped request then offers a richer API, in particular : - content automatically parsed according to `Content-Type` header, - and available as `request.DATA` + and available as `request.data` - full support of PUT method, including support for file uploads - form overloading of HTTP method, content type and content """ @@ -13,6 +13,7 @@ from django.conf import settings from django.http import QueryDict from django.http.multipartparser import parse_header from django.utils.datastructures import MultiValueDict +from django.utils.datastructures import MergeDict as DjangoMergeDict from rest_framework import HTTP_HEADER_ENCODING from rest_framework import exceptions from rest_framework.compat import BytesIO @@ -58,6 +59,15 @@ class override_method(object): self.view.action = self.action +class MergeDict(DjangoMergeDict, dict): + """ + Using this as a workaround until the parsers API is properly + addressed in 3.1. + """ + def __init__(self, *dicts): + self.dicts = dicts + + class Empty(object): """ Placeholder for unset attributes. @@ -82,6 +92,7 @@ def clone_request(request, method): parser_context=request.parser_context) ret._data = request._data ret._files = request._files + ret._full_data = request._full_data ret._content_type = request._content_type ret._stream = request._stream ret._method = method @@ -133,6 +144,7 @@ class Request(object): self.parser_context = parser_context self._data = Empty self._files = Empty + self._full_data = Empty self._method = Empty self._content_type = Empty self._stream = Empty @@ -186,12 +198,25 @@ class Request(object): return self._stream @property - def QUERY_PARAMS(self): + def query_params(self): """ More semantically correct name for request.GET. """ return self._request.GET + @property + def QUERY_PARAMS(self): + """ + Synonym for `.query_params`, for backwards compatibility. + """ + return self._request.GET + + @property + def data(self): + if not _hasattr(self, '_full_data'): + self._load_data_and_files() + return self._full_data + @property def DATA(self): """ @@ -272,6 +297,10 @@ class Request(object): if not _hasattr(self, '_data'): self._data, self._files = self._parse() + if self._files: + self._full_data = MergeDict(self._data, self._files) + else: + self._full_data = self._data def _load_method_and_content_type(self): """ @@ -333,6 +362,7 @@ class Request(object): # At this point we're committed to parsing the request as form data. self._data = self._request.POST self._files = self._request.FILES + self._full_data = MergeDict(self._data, self._files) # Method overloading - change the method and remove the param from the content. if ( @@ -350,7 +380,7 @@ class Request(object): ): self._content_type = self._data[self._CONTENTTYPE_PARAM] self._stream = BytesIO(self._data[self._CONTENT_PARAM].encode(self.parser_context['encoding'])) - self._data, self._files = (Empty, Empty) + self._data, self._files, self._full_data = (Empty, Empty, Empty) def _parse(self): """ @@ -380,6 +410,7 @@ class Request(object): # logging the request or similar. self._data = QueryDict('', encoding=self._request._encoding) self._files = MultiValueDict() + self._full_data = self._data raise # Parser classes may return the raw data, or a diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index b6a1898ca..a2b878ecb 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -57,21 +57,24 @@ class BaseSerializer(Field): def to_representation(self, instance): raise NotImplementedError('`to_representation()` must be implemented.') - def update(self, instance, attrs): + def update(self, instance, validated_data): raise NotImplementedError('`update()` must be implemented.') - def create(self, attrs): + def create(self, validated_data): raise NotImplementedError('`create()` must be implemented.') def save(self, extras=None): - attrs = self.validated_data + validated_data = self.validated_data if extras is not None: - attrs = dict(list(attrs.items()) + list(extras.items())) + validated_data = dict( + list(validated_data.items()) + + list(extras.items()) + ) if self.instance is not None: - self.update(self.instance, attrs) + self.update(self.instance, validated_data) else: - self.instance = self.create(attrs) + self.instance = self.create(validated_data) return self.instance @@ -321,12 +324,6 @@ class ListSerializer(BaseSerializer): def create(self, attrs_list): return [self.child.create(attrs) for attrs in attrs_list] - def save(self): - if self.instance is not None: - self.update(self.instance, self.validated_data) - self.instance = self.create(self.validated_data) - return self.instance - def __repr__(self): return representation.list_repr(self, indent=1) diff --git a/tests/test_fields.py b/tests/test_fields.py index b29acad81..1539a210e 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -9,7 +9,10 @@ import pytest # Tests for field keyword arguments and core functionality. # --------------------------------------------------------- -class TestFieldOptions: +class TestEmpty: + """ + Tests for `required`, `allow_null`, `allow_blank`, `default`. + """ def test_required(self): """ By default a field must be included in the input. @@ -69,6 +72,17 @@ class TestFieldOptions: output = field.run_validation() assert output is 123 + +class TestSource: + def test_source(self): + class ExampleSerializer(serializers.Serializer): + example_field = serializers.CharField(source='other') + serializer = ExampleSerializer(data={'example_field': 'abc'}) + print serializer.is_valid() + print serializer.data + assert serializer.is_valid() + assert serializer.validated_data == {'other': 'abc'} + def test_redundant_source(self): class ExampleSerializer(serializers.Serializer): example_field = serializers.CharField(source='example_field') @@ -81,6 +95,128 @@ class TestFieldOptions: ) +class TestReadOnly: + def setup(self): + class TestSerializer(serializers.Serializer): + read_only = fields.ReadOnlyField() + writable = fields.IntegerField() + self.Serializer = TestSerializer + + def test_validate_read_only(self): + """ + Read-only fields should not be included in validation. + """ + data = {'read_only': 123, 'writable': 456} + serializer = self.Serializer(data=data) + assert serializer.is_valid() + assert serializer.validated_data == {'writable': 456} + + def test_serialize_read_only(self): + """ + Read-only fields should be serialized. + """ + instance = {'read_only': 123, 'writable': 456} + serializer = self.Serializer(instance) + assert serializer.data == {'read_only': 123, 'writable': 456} + + +class TestWriteOnly: + def setup(self): + class TestSerializer(serializers.Serializer): + write_only = fields.IntegerField(write_only=True) + readable = fields.IntegerField() + self.Serializer = TestSerializer + + def test_validate_write_only(self): + """ + Write-only fields should be included in validation. + """ + data = {'write_only': 123, 'readable': 456} + serializer = self.Serializer(data=data) + assert serializer.is_valid() + assert serializer.validated_data == {'write_only': 123, 'readable': 456} + + def test_serialize_write_only(self): + """ + Write-only fields should not be serialized. + """ + instance = {'write_only': 123, 'readable': 456} + serializer = self.Serializer(instance) + assert serializer.data == {'readable': 456} + + +class TestInitial: + def setup(self): + class TestSerializer(serializers.Serializer): + initial_field = fields.IntegerField(initial=123) + blank_field = fields.IntegerField() + self.serializer = TestSerializer() + + def test_initial(self): + """ + Initial values should be included when serializing a new representation. + """ + assert self.serializer.data == { + 'initial_field': 123, + 'blank_field': None + } + + +class TestLabel: + def setup(self): + class TestSerializer(serializers.Serializer): + labeled = fields.IntegerField(label='My label') + self.serializer = TestSerializer() + + def test_label(self): + """ + A field's label may be set with the `label` argument. + """ + fields = self.serializer.fields + assert fields['labeled'].label == 'My label' + + +class TestInvalidErrorKey: + def setup(self): + class ExampleField(serializers.Field): + def to_native(self, data): + self.fail('incorrect') + self.field = ExampleField() + + def test_invalid_error_key(self): + """ + If a field raises a validation error, but does not have a corresponding + error message, then raise an appropriate assertion error. + """ + with pytest.raises(AssertionError) as exc_info: + self.field.to_native(123) + expected = ( + 'ValidationError raised by `ExampleField`, but error key ' + '`incorrect` does not exist in the `error_messages` dictionary.' + ) + assert str(exc_info.value) == expected + + +class TestBooleanHTMLInput: + def setup(self): + class TestSerializer(serializers.Serializer): + archived = fields.BooleanField() + 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 == {'archived': False} + + # Tests for field input and output values. # ---------------------------------------- @@ -495,7 +631,7 @@ class TestDateTimeField(FieldValues): '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()), - # Note that 1.4 does not support timezone string parsing. + # Django 1.4 does not support timezone string parsing. '2001-01-01T14:00+01:00' if (django.VERSION > (1, 4)) else '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()) } invalid_inputs = { diff --git a/tests/test_generics.py b/tests/test_generics.py index 89f9def01..2690fb47c 100644 --- a/tests/test_generics.py +++ b/tests/test_generics.py @@ -38,7 +38,7 @@ class FKInstanceView(generics.RetrieveUpdateDestroyAPIView): class SlugSerializer(serializers.ModelSerializer): - slug = serializers.Field(read_only=True) + slug = serializers.ReadOnlyField() class Meta: model = SlugBasedModel diff --git a/tests/test_serializer.py b/tests/test_serializer.py index 5646f9940..256a12e68 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -1,4 +1,5 @@ from rest_framework import serializers +import pytest # Tests for core functionality. @@ -29,6 +30,67 @@ class TestSerializer: assert serializer.validated_data == {'char': 'abc'} assert serializer.errors == {} + def test_empty_serializer(self): + serializer = self.Serializer() + assert serializer.data == {'char': '', 'integer': None} + + def test_missing_attribute_during_serialization(self): + class MissingAttributes: + pass + instance = MissingAttributes() + serializer = self.Serializer(instance) + with pytest.raises(AttributeError): + serializer.data + + +class TestStarredSource: + """ + Tests for `source='*'` argument, which is used for nested representations. + + For example: + + nested_field = NestedField(source='*') + """ + data = { + 'nested1': {'a': 1, 'b': 2}, + 'nested2': {'c': 3, 'd': 4} + } + + def setup(self): + class NestedSerializer1(serializers.Serializer): + a = serializers.IntegerField() + b = serializers.IntegerField() + + class NestedSerializer2(serializers.Serializer): + c = serializers.IntegerField() + d = serializers.IntegerField() + + class TestSerializer(serializers.Serializer): + nested1 = NestedSerializer1(source='*') + nested2 = NestedSerializer2(source='*') + + self.Serializer = TestSerializer + + def test_nested_validate(self): + """ + A nested representation is validated into a flat internal object. + """ + serializer = self.Serializer(data=self.data) + assert serializer.is_valid() + assert serializer.validated_data == { + 'a': 1, + 'b': 2, + 'c': 3, + 'd': 4 + } + + def test_nested_serialize(self): + """ + An object can be serialized into a nested representation. + """ + instance = {'a': 1, 'b': 2, 'c': 3, 'd': 4} + serializer = self.Serializer(instance) + assert serializer.data == self.data # # -*- coding: utf-8 -*- # from __future__ import unicode_literals From 43e80c74b225e17edfe8a90da893823bf50b946f Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 11:56:29 +0100 Subject: [PATCH 090/249] Release notes --- docs/topics/3.0-announcement.md | 79 ++++++++++++++++++++++++++++++--- rest_framework/serializers.py | 3 ++ 2 files changed, 75 insertions(+), 7 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 1795611c0..35d725ffb 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -4,12 +4,25 @@ See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-fr # REST framework 3.0 -**TODO**: Note incremental nature, discuss upgrading, motivation, features. +The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views. -* Serializer reprs. -* Non-magical model serializers. -* Base serializer class. -* Clean logic in views, serializers, fields. +This release is incremental in nature. There *are* some breaking API changes, and upgrading *will* require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward. + +The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier. + +## New features + +Notable features of this new release include: + +* Printable representations on serializers that allow you to inspect exactly what fields are present on the instance. +* Simple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit `ModelSerializer` class and the explicit `Serializer` class. +* A new `BaseSerializer` class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic. +* A cleaner fields API plus new `ListField` and `MultipleChoiceField` classes. +* Super simple default implementations for the generic views. +* Support for overriding how validation errors are handled by your API. +* A metadata API that allows you to customize how `OPTIONS` requests are handled by your API. + +Below is an in-depth guide to the API changes and migration notes for 3.0. --- @@ -37,9 +50,59 @@ The usage of `request.QUERY_PARAMS` is now discouraged in favor of the lowercase #### Single-step object creation. +Previously the serializers used a two-step object creation, as follows: + +1. Validating the data would create an object instance. This instance would be available as `serializer.object`. +2. Calling `serializer.save()` would then save the object instance to the database. + +This style is in line with how the `ModelForm` class works in Django, but is problematic for a number of reasons: + +* Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been save. This type of data needed to be hidden in some undocumentated state on the object instance, or kept as state on the serializer instance so that it could be used when `.save()` is called. +* Instantiating model instances directly means that you cannot use model manager classes for instance creation, eg `ExampleModel.objects.create(...)`. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints. +* The two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save? + +We now use single-step object creation, like so: + +1. Validating the data makes the cleaned data available as `serializer.validated_data`. +2. Calling `serializer.save()` then saves and returns the new object instance. + +The resulting API changes are further detailed below. + #### The `.create()` and `.update()` methods. -**TODO**: Drop `.restore_object()`, use `.create()` and `.update()` which should save the instance. +The `.restore_object()` method is now replaced with two seperate methods, `.create()` and `.update()`. + +When using the `.create()` and `.update()` methods you should both create *and save* the object instance. This is in contrast to the previous `.restore_object()` behavior that would instantiate the object but not save it. + +The following example from the tutorial previously used `restore_object()` to handle both creating and updating object instances. + + def restore_object(self, attrs, instance=None): + if instance: + # Update existing instance + instance.title = attrs.get('title', instance.title) + instance.code = attrs.get('code', instance.code) + instance.linenos = attrs.get('linenos', instance.linenos) + instance.language = attrs.get('language', instance.language) + instance.style = attrs.get('style', instance.style) + return instance + + # Create new instance + return Snippet(**attrs) + +This would now be split out into two seperate methods. + + def update(self, instance, validated_attrs) + instance.title = validated_attrs.get('title', instance.title) + instance.code = validated_attrs.get('code', instance.code) + instance.linenos = validated_attrs.get('linenos', instance.linenos) + instance.language = validated_attrs.get('language', instance.language) + instance.style = validated_attrs.get('style', instance.style) + instance.save() + + def create(self, validated_attrs): + return Snippet.objects.create(**validated_attrs) + +Note that the `.create` method should return the newly created object instance. #### Use `.validated_data` instead of `.object`. @@ -457,7 +520,9 @@ This change means that you can now easily cusomize the style of error responses ## The metadata API -**TODO** +Behavior for dealing with `OPTIONS` requests was previously built directly into the class based views. This has now been properly seperated out into a Metadata API that allows the same pluggable style as other API policies in REST framework. + +This makes it far easier to use a different style for `OPTIONS` responses throughout your API, and makes it possible to create third-party metadata policies. ## API style diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index a2b878ecb..86bed773b 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -75,6 +75,9 @@ class BaseSerializer(Field): self.update(self.instance, validated_data) else: self.instance = self.create(validated_data) + assert self.instance is not None, ( + '`create()` did not return an object instance.' + ) return self.instance From e8af73d144d73a55aecde6a1fda8516f15f027c1 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 12:17:20 +0100 Subject: [PATCH 091/249] Release notes --- docs/topics/3.0-announcement.md | 35 +++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 35d725ffb..144d35503 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -125,14 +125,41 @@ The corresponding code would now look like this: logging.info('Creating ticket "%s"' % name) extras = {'user': request.user} # Include the user when saving. serializer.save(extras=extras) - + +#### Printable serializer reprensentations. + +Serializer instances now support a printable representation that allows you to inspect the fields present on the instance. + +For instance, given the following example model: + + class LocationRating(models.Model): + location = models.CharField(max_length=100) + rating = models.IntegerField() + created_by = models.ForeignKey(User) + +Let's create a simple `ModelSerializer` class c. + + class LocationRatingSerializer(serializer.ModelSerializer): + class Meta: + model = LocationRating + +We can now inspect its representation in the Django shell, using `python manage.py shell`... + + >>> serializer = LocationRatingSerializer() + >>> print(serializer) # Or use `print serializer` in Python 2.x + LocationRatingSerializer(): + id = IntegerField(label='ID', read_only=True) + location = CharField(max_length=100) + rating = IntegerField() + created_by = PrimaryKeyRelatedField(queryset=User.objects.all()) + #### Always use `fields`, not `exclude`. -The `exclude` option is no longer available. You should use the more explicit `fields` option instead. +The `exclude` option on `ModelSerializer` is no longer available. You should use the more explicit `fields` option instead. #### The `extra_kwargs` option. -The `read_only_fields` and `write_only_fields` options have been removed and replaced with a more generic `extra_kwargs`. +The `read_only_fields` and `write_only_fields` options on `ModelSerializer` have been removed and replaced with a more generic `extra_kwargs`. class MySerializer(serializer.ModelSerializer): class Meta: @@ -177,7 +204,7 @@ Alternatively, specify the field explicitly on the serializer class: #### Fields for model methods and properties. -You can now specify field names in the `fields` option that refer to model methods or properties. For example, suppose you have the following model: +With `ModelSerilizer` you can now specify field names in the `fields` option that refer to model methods or properties. For example, suppose you have the following model: class Invitation(models.Model): created = models.DateTimeField() From 90311357add780433c79e97346ed85f1f4224877 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 12:18:27 +0100 Subject: [PATCH 092/249] Release notes --- docs/topics/3.0-announcement.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 144d35503..daacbba07 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -137,13 +137,13 @@ For instance, given the following example model: rating = models.IntegerField() created_by = models.ForeignKey(User) -Let's create a simple `ModelSerializer` class c. +Let's create a simple `ModelSerializer` class corresponding to the `LocationRating` model. class LocationRatingSerializer(serializer.ModelSerializer): class Meta: model = LocationRating -We can now inspect its representation in the Django shell, using `python manage.py shell`... +We can now inspect the serializer representation in the Django shell, using `python manage.py shell`... >>> serializer = LocationRatingSerializer() >>> print(serializer) # Or use `print serializer` in Python 2.x From fde934d33c8692bab5e0e7b6009d358101a25dd7 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 12:21:05 +0100 Subject: [PATCH 093/249] Release notes --- docs/topics/3.0-announcement.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index daacbba07..a4e4db148 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -21,6 +21,7 @@ Notable features of this new release include: * Super simple default implementations for the generic views. * Support for overriding how validation errors are handled by your API. * A metadata API that allows you to customize how `OPTIONS` requests are handled by your API. +* A more compact JSON output with unicode style encoding turned on by default. Below is an in-depth guide to the API changes and migration notes for 3.0. From 8b8623c5f84d443d26804cac52a793a3037a1dd0 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 12:48:20 +0100 Subject: [PATCH 094/249] Allow many, partial and context in BaseSerializer --- docs/topics/3.0-announcement.md | 7 ++++ rest_framework/serializers.py | 28 +++++++--------- tests/test_serializer.py | 58 +++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 16 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index a4e4db148..faba2d356 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -2,6 +2,13 @@ See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-framework/pull/1800) for more details. +Most notable outstanding issues still to resolved on the `version-3.0` branch. + +* `FileField` and `ImageField` support. +* Forms support for serializers and in the browsable API. +* Enforcing uniqueness on `unique=True` and `unique_together` fields. +* Optimisations for serialializing primary keys. + # REST framework 3.0 The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views. diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 86bed773b..245ec26f1 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -47,9 +47,20 @@ class BaseSerializer(Field): """ def __init__(self, instance=None, data=None, **kwargs): - super(BaseSerializer, self).__init__(**kwargs) self.instance = instance self._initial_data = data + self.partial = kwargs.pop('partial', False) + self._context = kwargs.pop('context', {}) + kwargs.pop('many', None) + super(BaseSerializer, self).__init__(**kwargs) + + def __new__(cls, *args, **kwargs): + # We override this method in order to automagically create + # `ListSerializer` classes instead when `many=True` is set. + if kwargs.pop('many', False): + kwargs['child'] = cls() + return ListSerializer(*args, **kwargs) + return super(BaseSerializer, cls).__new__(cls, *args, **kwargs) def to_internal_value(self, data): raise NotImplementedError('`to_internal_value()` must be implemented.') @@ -187,10 +198,6 @@ class BindingDict(object): @six.add_metaclass(SerializerMetaclass) class Serializer(BaseSerializer): def __init__(self, *args, **kwargs): - kwargs.pop('many', None) - self.partial = kwargs.pop('partial', False) - self._context = kwargs.pop('context', {}) - super(Serializer, self).__init__(*args, **kwargs) # Every new serializer is created with a clone of the field instances. @@ -200,14 +207,6 @@ class Serializer(BaseSerializer): for key, value in self._get_base_fields().items(): self.fields[key] = value - def __new__(cls, *args, **kwargs): - # We override this method in order to automagically create - # `ListSerializer` classes instead when `many=True` is set. - if kwargs.pop('many', False): - kwargs['child'] = cls() - return ListSerializer(*args, **kwargs) - return super(Serializer, cls).__new__(cls, *args, **kwargs) - def _get_base_fields(self): return copy.deepcopy(self._declared_fields) @@ -296,9 +295,6 @@ class ListSerializer(BaseSerializer): 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.' - self.partial = kwargs.pop('partial', False) - self._context = kwargs.pop('context', {}) - super(ListSerializer, self).__init__(*args, **kwargs) self.child.bind(field_name='', parent=self) diff --git a/tests/test_serializer.py b/tests/test_serializer.py index 256a12e68..4df1b7364 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -43,6 +43,64 @@ class TestSerializer: serializer.data +class TestBaseSerializer: + def setup(self): + class ExampleSerializer(serializers.BaseSerializer): + def to_representation(self, obj): + return { + 'id': obj['id'], + 'email': obj['name'] + '@' + obj['domain'] + } + + def to_internal_value(self, data): + name, domain = str(data['email']).split('@') + return { + 'id': int(data['id']), + 'name': name, + 'domain': domain, + } + + self.Serializer = ExampleSerializer + + def test_serialize_instance(self): + instance = {'id': 1, 'name': 'tom', 'domain': 'example.com'} + serializer = self.Serializer(instance) + assert serializer.data == {'id': 1, 'email': 'tom@example.com'} + + def test_serialize_list(self): + instances = [ + {'id': 1, 'name': 'tom', 'domain': 'example.com'}, + {'id': 2, 'name': 'ann', 'domain': 'example.com'}, + ] + serializer = self.Serializer(instances, many=True) + assert serializer.data == [ + {'id': 1, 'email': 'tom@example.com'}, + {'id': 2, 'email': 'ann@example.com'} + ] + + def test_validate_data(self): + data = {'id': 1, 'email': 'tom@example.com'} + serializer = self.Serializer(data=data) + assert serializer.is_valid() + assert serializer.validated_data == { + 'id': 1, + 'name': 'tom', + 'domain': 'example.com' + } + + def test_validate_list(self): + data = [ + {'id': 1, 'email': 'tom@example.com'}, + {'id': 2, 'email': 'ann@example.com'}, + ] + serializer = self.Serializer(data=data, many=True) + assert serializer.is_valid() + assert serializer.validated_data == [ + {'id': 1, 'name': 'tom', 'domain': 'example.com'}, + {'id': 2, 'name': 'ann', 'domain': 'example.com'} + ] + + class TestStarredSource: """ Tests for `source='*'` argument, which is used for nested representations. From 2e87de01430d7fec83f00948e60c8d61b317053b Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 13:08:20 +0100 Subject: [PATCH 095/249] Added ListField --- rest_framework/fields.py | 38 +++++++++++++++++++++++++++++++++++ rest_framework/serializers.py | 6 ++++-- tests/test_fields.py | 19 ++++++++++++++++++ 3 files changed, 61 insertions(+), 2 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index ec07a4134..cf42d36cb 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -881,6 +881,44 @@ class ImageField(Field): # Advanced field types... +class ListField(Field): + child = None + initial = [] + default_error_messages = { + 'not_a_list': _('Expected a list of items but got type `{input_type}`') + } + + 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) + + 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): + """ + List of dicts of native values <- List of dicts of primitive datatypes. + """ + if html.is_html_input(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__) + return [self.child.run_validation(item) for item in data] + + def to_representation(self, data): + """ + List of object instances -> List of dicts of primitive datatypes. + """ + return [self.child.to_representation(item) for item in data] + + class ReadOnlyField(Field): """ A read-only field that simply returns the field value. diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 245ec26f1..fa2e8fb10 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -287,6 +287,9 @@ class Serializer(BaseSerializer): return representation.serializer_repr(self, indent=1) +# There's some replication of `ListField` here, +# but that's probably better than obfuscating the call hierarchy. + class ListSerializer(BaseSerializer): child = None initial = [] @@ -301,7 +304,7 @@ class ListSerializer(BaseSerializer): def get_value(self, dictionary): # We override the default field access in order to support # lists in HTML forms. - if is_html_input(dictionary): + if html.is_html_input(dictionary): return html.parse_html_list(dictionary, prefix=self.field_name) return dictionary.get(self.field_name, empty) @@ -311,7 +314,6 @@ class ListSerializer(BaseSerializer): """ if html.is_html_input(data): data = html.parse_html_list(data) - return [self.child.run_validation(item) for item in data] def to_representation(self, data): diff --git a/tests/test_fields.py b/tests/test_fields.py index 1539a210e..681127484 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -849,6 +849,25 @@ class TestMultipleChoiceField(FieldValues): ) +class TestListField(FieldValues): + """ + Values for `ListField`. + """ + valid_inputs = [ + ([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`']), + ([1, 2, 'error'], ['A valid integer is required.']) + ] + outputs = [ + ([1, 2, 3], [1, 2, 3]), + (['1', '2', '3'], [1, 2, 3]) + ] + field = fields.ListField(child=fields.IntegerField()) + + # Tests for SerializerMethodField. # -------------------------------- From 0eb6a4de8a3293c3b326fadccf7aa0be67c2f5b5 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 13:10:58 +0100 Subject: [PATCH 096/249] Release notes --- docs/topics/3.0-announcement.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index faba2d356..9769e8844 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -8,6 +8,7 @@ Most notable outstanding issues still to resolved on the `version-3.0` branch. * Forms support for serializers and in the browsable API. * Enforcing uniqueness on `unique=True` and `unique_together` fields. * Optimisations for serialializing primary keys. +* Refine style of validation errors in some cases, such as validation errors in `ListField`. # REST framework 3.0 From 24f7db2fc156b0af7749a5cc17c1df3f5522bf88 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 13:12:10 +0100 Subject: [PATCH 097/249] Release notes --- docs/topics/3.0-announcement.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 9769e8844..a48d22ead 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -2,13 +2,15 @@ See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-framework/pull/1800) for more details. -Most notable outstanding issues still to resolved on the `version-3.0` branch. +The most notable outstanding issues still to resolved on the `version-3.0` branch are as follows: * `FileField` and `ImageField` support. * Forms support for serializers and in the browsable API. * Enforcing uniqueness on `unique=True` and `unique_together` fields. * Optimisations for serialializing primary keys. * Refine style of validation errors in some cases, such as validation errors in `ListField`. +* `.validate()` method on fields. +* `.transform_<field>()` method on serializers. # REST framework 3.0 From 33ccf40b76ddae790c34c294a133219e68efb946 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 13:14:08 +0100 Subject: [PATCH 098/249] Update version number --- rest_framework/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py index 7f724c185..261c9c984 100644 --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -8,7 +8,7 @@ ______ _____ _____ _____ __ """ __title__ = 'Django REST framework' -__version__ = '2.4.3' +__version__ = '3.0.0' __author__ = 'Tom Christie' __license__ = 'BSD 2-Clause' __copyright__ = 'Copyright 2011-2014 Tom Christie' From ee79b453974f3dc8ead83bff86784366d59a4fb1 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 13:19:32 +0100 Subject: [PATCH 099/249] Prepend some pre-release notes --- docs/topics/3.0-announcement.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index a48d22ead..21052ca03 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -1,6 +1,10 @@ -**THIS DOCUMENT IS CURRENTLY A WORK IN PROGRESS** +## Pre-release notes: -See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-framework/pull/1800) for more details. +The 3.0 release is now ready for some tentative testing and upgrades for super keen early adopters. You can install the development version directly from GitHub like so: + + pip install https://github.com/tomchristie/django-rest-framework/archive/version-3.0.zip + +See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-framework/pull/1800) for more details on remaining work. The most notable outstanding issues still to resolved on the `version-3.0` branch are as follows: @@ -12,6 +16,12 @@ The most notable outstanding issues still to resolved on the `version-3.0` branc * `.validate()` method on fields. * `.transform_<field>()` method on serializers. +**Your feedback on the upgrade process and 3.0 changes is hugely important!** + +Please do get in touch via twitter, IRC, a GitHub ticket, or the discussion group. + +--- + # REST framework 3.0 The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views. From 8be4496586519f84b839b07efc74148a3559349e Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 13:59:37 +0100 Subject: [PATCH 100/249] Drop erronous print statements --- tests/test_fields.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/test_fields.py b/tests/test_fields.py index 681127484..342ae1927 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -78,8 +78,6 @@ class TestSource: class ExampleSerializer(serializers.Serializer): example_field = serializers.CharField(source='other') serializer = ExampleSerializer(data={'example_field': 'abc'}) - print serializer.is_valid() - print serializer.data assert serializer.is_valid() assert serializer.validated_data == {'other': 'abc'} From 609014460861fdfe82054551790d6439292dde7b Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 14:32:44 +0100 Subject: [PATCH 101/249] Simplify serialization slightly --- rest_framework/fields.py | 11 +++++++---- rest_framework/serializers.py | 3 +-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index cf42d36cb..4c49aabaa 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -202,12 +202,15 @@ class Field(object): return self.default_empty_html if (ret == '') else ret return dictionary.get(self.field_name, empty) - def get_attribute(self, instance): + def get_field_representation(self, instance): """ - Given the *outgoing* object instance, return the value for this field - that should be returned as a primative value. + Given the outgoing object instance, return the primative value + that should be used for this field. """ - return get_attribute(instance, self.source_attrs) + attribute = get_attribute(instance, self.source_attrs) + if attribute is None: + return None + return self.to_representation(attribute) def get_default(self): """ diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index fa2e8fb10..080b958d5 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -268,8 +268,7 @@ class Serializer(BaseSerializer): fields = [field for field in self.fields.values() if not field.write_only] for field in fields: - native_value = field.get_attribute(instance) - ret[field.field_name] = field.to_representation(native_value) + ret[field.field_name] = field.get_field_representation(instance) return ret From dee3f78cb688b1bee892ef78d6eec23ccf67a80e Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 17:06:20 +0100 Subject: [PATCH 102/249] FileField and ImageField --- requirements-test.txt | 1 - rest_framework/compat.py | 9 ---- rest_framework/fields.py | 82 +++++++++++++++++++++++++-------- rest_framework/settings.py | 3 +- tests/test_fields.py | 93 ++++++++++++++++++++++++++++++++++++-- tox.ini | 16 ------- 6 files changed, 156 insertions(+), 48 deletions(-) diff --git a/requirements-test.txt b/requirements-test.txt index d6ee5c6fd..06c8849a8 100644 --- a/requirements-test.txt +++ b/requirements-test.txt @@ -13,4 +13,3 @@ django-filter>=0.5.4 django-oauth-plus>=2.2.1 oauth2>=1.5.211 django-oauth2-provider>=0.2.4 -Pillow==2.3.0 diff --git a/rest_framework/compat.py b/rest_framework/compat.py index 7303c32a6..89af9b485 100644 --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -84,15 +84,6 @@ except ImportError: from collections import UserDict from collections import MutableMapping as DictMixin -# Try to import PIL in either of the two ways it can end up installed. -try: - from PIL import Image -except ImportError: - try: - import Image - except ImportError: - Image = None - def get_model_name(model_cls): try: diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 4c49aabaa..f4b53279a 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1,3 +1,4 @@ +from django import forms from django.conf import settings from django.core import validators from django.core.exceptions import ValidationError @@ -427,8 +428,6 @@ class CharField(Field): return str(data) def to_representation(self, value): - if value is None: - return None return str(value) @@ -446,8 +445,6 @@ class EmailField(CharField): return str(data).strip() def to_representation(self, value): - if value is None: - return None return str(value).strip() @@ -513,8 +510,6 @@ class IntegerField(Field): return data def to_representation(self, value): - if value is None: - return None return int(value) @@ -543,8 +538,6 @@ class FloatField(Field): self.fail('invalid') def to_representation(self, value): - if value is None: - return None return float(value) @@ -616,9 +609,6 @@ class DecimalField(Field): return value def to_representation(self, value): - if value in (None, ''): - return None - if not isinstance(value, decimal.Decimal): value = decimal.Decimal(str(value).strip()) @@ -689,7 +679,7 @@ class DateTimeField(Field): self.fail('invalid', format=humanized_format) def to_representation(self, value): - if value is None or self.format is None: + if self.format is None: return value if self.format.lower() == ISO_8601: @@ -741,7 +731,7 @@ class DateField(Field): self.fail('invalid', format=humanized_format) def to_representation(self, value): - if value is None or self.format is None: + if self.format is None: return value # Applying a `DateField` to a datetime value is almost always @@ -795,7 +785,7 @@ class TimeField(Field): self.fail('invalid', format=humanized_format) def to_representation(self, value): - if value is None or self.format is None: + if self.format is None: return value # Applying a `TimeField` to a datetime value is almost always @@ -875,14 +865,68 @@ class MultipleChoiceField(ChoiceField): # File types... class FileField(Field): - pass # TODO + default_error_messages = { + 'required': _("No file was submitted."), + 'invalid': _("The submitted data was not a file. Check the encoding type on the form."), + 'no_name': _("No filename could be determined."), + 'empty': _("The submitted file is empty."), + 'max_length': _('Ensure this filename has at most {max_length} characters (it has {length}).'), + } + use_url = api_settings.UPLOADED_FILES_USE_URL + + def __init__(self, *args, **kwargs): + self.max_length = kwargs.pop('max_length', None) + self.allow_empty_file = kwargs.pop('allow_empty_file', False) + self.use_url = kwargs.pop('use_url', self.use_url) + super(FileField, self).__init__(*args, **kwargs) + + def to_internal_value(self, data): + try: + # `UploadedFile` objects should have name and size attributes. + file_name = data.name + file_size = data.size + except AttributeError: + self.fail('invalid') + + if not file_name: + self.fail('no_name') + if not self.allow_empty_file and not file_size: + self.fail('empty') + if self.max_length and len(file_name) > self.max_length: + self.fail('max_length', max_length=self.max_length, length=len(file_name)) + + return data + + def to_representation(self, value): + if self.use_url: + return settings.MEDIA_URL + value.url + return value.name -class ImageField(Field): - pass # TODO +class ImageField(FileField): + default_error_messages = { + 'invalid_image': _( + 'Upload a valid image. The file you uploaded was either not an ' + 'image or a corrupted image.' + ), + } + + def __init__(self, *args, **kwargs): + self._DjangoImageField = kwargs.pop('_DjangoImageField', forms.ImageField) + super(ImageField, self).__init__(*args, **kwargs) + + def to_internal_value(self, data): + # Image validation is a bit grungy, so we'll just outright + # defer to Django's implementation so we don't need to + # consider it, or treat PIL as a test dependancy. + file_object = super(ImageField, self).to_internal_value(data) + django_field = self._DjangoImageField() + django_field.error_messages = self.error_messages + django_field.to_python(file_object) + return file_object -# Advanced field types... +# Composite field types... class ListField(Field): child = None @@ -922,6 +966,8 @@ class ListField(Field): return [self.child.to_representation(item) for item in data] +# Miscellaneous field types... + class ReadOnlyField(Field): """ A read-only field that simply returns the field value. diff --git a/rest_framework/settings.py b/rest_framework/settings.py index d7fb0a436..1e8c27fc3 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -110,7 +110,8 @@ DEFAULTS = { # Encoding 'UNICODE_JSON': True, 'COMPACT_JSON': True, - 'COERCE_DECIMAL_TO_STRING': True + 'COERCE_DECIMAL_TO_STRING': True, + 'UPLOADED_FILES_USE_URL': True } diff --git a/tests/test_fields.py b/tests/test_fields.py index 342ae1927..aa8c3a68c 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1,4 +1,5 @@ from decimal import Decimal +from django.core.exceptions import ValidationError from django.utils import timezone from rest_framework import fields, serializers import datetime @@ -516,7 +517,7 @@ class TestDecimalField(FieldValues): Decimal('1.0'): '1.0', Decimal('0.0'): '0.0', Decimal('1.09'): '1.1', - Decimal('0.04'): '0.0', + Decimal('0.04'): '0.0' } field = fields.DecimalField(max_digits=3, decimal_places=1) @@ -576,7 +577,7 @@ 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' } field = fields.DateField() @@ -639,7 +640,7 @@ 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' } field = fields.DateTimeField(default_timezone=timezone.UTC()) @@ -847,6 +848,92 @@ class TestMultipleChoiceField(FieldValues): ) +# File fields... + +class MockFile: + def __init__(self, name='', size=0, url=''): + self.name = name + self.size = size + self.url = url + + def __eq__(self, other): + return ( + isinstance(other, MockFile) and + self.name == other.name and + self.size == other.size and + self.url == other.url + ) + + +class TestFileField(FieldValues): + """ + Values for `FileField`. + """ + valid_inputs = [ + (MockFile(name='example', size=10), MockFile(name='example', size=10)) + ] + invalid_inputs = [ + ('invalid', ['The submitted data was not a file. Check the encoding type on the form.']), + (MockFile(name='example.txt', size=0), ['The submitted file is empty.']), + (MockFile(name='', size=10), ['No filename could be determined.']), + (MockFile(name='x' * 100, size=10), ['Ensure this filename has at most 10 characters (it has 100).']) + ] + outputs = [ + (MockFile(name='example.txt', url='/example.txt'), '/example.txt') + ] + field = fields.FileField(max_length=10) + + +class TestFieldFieldWithName(FieldValues): + """ + Values for `FileField` with a filename output instead of URLs. + """ + valid_inputs = {} + invalid_inputs = {} + outputs = [ + (MockFile(name='example.txt', url='/example.txt'), 'example.txt') + ] + field = fields.FileField(use_url=False) + + +# Stub out mock Django `forms.ImageField` class so we don't *actually* +# call into it's regular validation, or require PIL for testing. +class FailImageValidation(object): + def to_python(self, value): + raise ValidationError(self.error_messages['invalid_image']) + + +class PassImageValidation(object): + def to_python(self, value): + return value + + +class TestInvalidImageField(FieldValues): + """ + Values for an invalid `ImageField`. + """ + valid_inputs = {} + invalid_inputs = [ + (MockFile(name='example.txt', size=10), ['Upload a valid image. The file you uploaded was either not an image or a corrupted image.']) + ] + outputs = {} + field = fields.ImageField(_DjangoImageField=FailImageValidation) + + +class TestValidImageField(FieldValues): + """ + Values for an valid `ImageField`. + """ + valid_inputs = [ + (MockFile(name='example.txt', size=10), MockFile(name='example.txt', size=10)) + ] + invalid_inputs = {} + outputs = {} + field = fields.ImageField(_DjangoImageField=PassImageValidation) + + +# Composite fields... + class TestListField(FieldValues): """ Values for `ListField`. diff --git a/tox.ini b/tox.ini index d40a70799..5b9a0ffef 100644 --- a/tox.ini +++ b/tox.ini @@ -21,7 +21,6 @@ basepython = python3.4 deps = Django==1.7 django-filter==0.7 defusedxml==0.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py3.3-django1.7] @@ -29,7 +28,6 @@ basepython = python3.3 deps = Django==1.7 django-filter==0.7 defusedxml==0.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py3.2-django1.7] @@ -37,7 +35,6 @@ basepython = python3.2 deps = Django==1.7 django-filter==0.7 defusedxml==0.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py2.7-django1.7] @@ -49,7 +46,6 @@ deps = Django==1.7 # oauth2==1.5.211 # django-oauth2-provider==0.2.4 django-guardian==1.2.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py3.4-django1.6] @@ -57,7 +53,6 @@ basepython = python3.4 deps = Django==1.6.3 django-filter==0.7 defusedxml==0.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py3.3-django1.6] @@ -65,7 +60,6 @@ basepython = python3.3 deps = Django==1.6.3 django-filter==0.7 defusedxml==0.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py3.2-django1.6] @@ -73,7 +67,6 @@ basepython = python3.2 deps = Django==1.6.3 django-filter==0.7 defusedxml==0.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py2.7-django1.6] @@ -85,7 +78,6 @@ deps = Django==1.6.3 oauth2==1.5.211 django-oauth2-provider==0.2.4 django-guardian==1.2.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py2.6-django1.6] @@ -97,7 +89,6 @@ deps = Django==1.6.3 oauth2==1.5.211 django-oauth2-provider==0.2.4 django-guardian==1.2.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py3.4-django1.5] @@ -105,7 +96,6 @@ basepython = python3.4 deps = django==1.5.6 django-filter==0.7 defusedxml==0.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py3.3-django1.5] @@ -113,7 +103,6 @@ basepython = python3.3 deps = django==1.5.6 django-filter==0.7 defusedxml==0.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py3.2-django1.5] @@ -121,7 +110,6 @@ basepython = python3.2 deps = django==1.5.6 django-filter==0.7 defusedxml==0.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py2.7-django1.5] @@ -133,7 +121,6 @@ deps = django==1.5.6 oauth2==1.5.211 django-oauth2-provider==0.2.3 django-guardian==1.2.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py2.6-django1.5] @@ -145,7 +132,6 @@ deps = django==1.5.6 oauth2==1.5.211 django-oauth2-provider==0.2.3 django-guardian==1.2.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py2.7-django1.4] @@ -157,7 +143,6 @@ deps = django==1.4.11 oauth2==1.5.211 django-oauth2-provider==0.2.3 django-guardian==1.2.3 - Pillow==2.3.0 pytest-django==2.6.1 [testenv:py2.6-django1.4] @@ -169,5 +154,4 @@ deps = django==1.4.11 oauth2==1.5.211 django-oauth2-provider==0.2.3 django-guardian==1.2.3 - Pillow==2.3.0 pytest-django==2.6.1 From ce04d59a53df45715c4805831406b2105c9594a8 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 26 Sep 2014 17:07:47 +0100 Subject: [PATCH 103/249] Update release notes --- docs/topics/3.0-announcement.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 21052ca03..24f4ed4c2 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -8,7 +8,6 @@ See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-fr The most notable outstanding issues still to resolved on the `version-3.0` branch are as follows: -* `FileField` and `ImageField` support. * Forms support for serializers and in the browsable API. * Enforcing uniqueness on `unique=True` and `unique_together` fields. * Optimisations for serialializing primary keys. From 43fd5a873051c99600386c1fdc9fa368edeb6eda Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 29 Sep 2014 09:24:03 +0100 Subject: [PATCH 104/249] Uniqueness validation --- rest_framework/fields.py | 4 ++ rest_framework/utils/field_mapping.py | 5 +++ rest_framework/validators.py | 57 +++++++++++++++++++++++++++ tests/test_validators.py | 35 ++++++++++++++++ 4 files changed, 101 insertions(+) create mode 100644 rest_framework/validators.py create mode 100644 tests/test_validators.py diff --git a/rest_framework/fields.py b/rest_framework/fields.py index f4b53279a..231f693ca 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -150,6 +150,10 @@ class Field(object): messages.update(error_messages or {}) self.error_messages = messages + for validator in validators: + if getattr(validator, 'requires_context', False): + validator.serializer_field = self + def bind(self, field_name, parent): """ Initializes the field name and parent for the field instance. diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index c37940832..cf9d910aa 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -6,6 +6,7 @@ from django.core import validators from django.db import models from django.utils.text import capfirst from rest_framework.compat import clean_manytomany_helptext +from rest_framework.validators import UniqueValidator import inspect @@ -156,6 +157,10 @@ def get_field_kwargs(field_name, model_field): if validator is not validators.validate_slug ] + if getattr(model_field, 'unique', False): + validator = UniqueValidator(queryset=model_field.model._default_manager) + validator_kwarg.append(validator) + max_digits = getattr(model_field, 'max_digits', None) if max_digits is not None: kwargs['max_digits'] = max_digits diff --git a/rest_framework/validators.py b/rest_framework/validators.py new file mode 100644 index 000000000..f5fbeb3ca --- /dev/null +++ b/rest_framework/validators.py @@ -0,0 +1,57 @@ +from django.core.exceptions import ValidationError + + +class UniqueValidator: + # Validators with `requires_context` will have the field instance + # passed to them when the field is instantiated. + requires_context = True + + def __init__(self, queryset): + self.queryset = queryset + self.serializer_field = None + + def get_queryset(self): + return self.queryset.all() + + def __call__(self, value): + field = self.serializer_field + + # Determine the model field name that the serializer field corresponds to. + field_name = field.source_attrs[0] if field.source_attrs else field.field_name + + # Determine the existing instance, if this is an update operation. + instance = getattr(field.parent, 'instance', None) + + # Ensure uniqueness. + filter_kwargs = {field_name: value} + queryset = self.get_queryset().filter(**filter_kwargs) + if instance: + queryset = queryset.exclude(pk=instance.pk) + if queryset.exists(): + raise ValidationError('This field must be unique.') + + +class UniqueTogetherValidator: + requires_context = True + + def __init__(self, queryset, fields): + self.queryset = queryset + self.fields = fields + self.serializer_field = None + + def __call__(self, value): + serializer = self.serializer_field + + # Determine the existing instance, if this is an update operation. + instance = getattr(serializer, 'instance', None) + + # Ensure uniqueness. + filter_kwargs = dict([ + (field_name, value[field_name]) for field_name in self.fields + ]) + queryset = self.get_queryset().filter(**filter_kwargs) + if instance: + queryset = queryset.exclude(pk=instance.pk) + if queryset.exists(): + field_names = ' and '.join(self.fields) + raise ValidationError('The fields %s must make a unique set.' % field_names) diff --git a/tests/test_validators.py b/tests/test_validators.py new file mode 100644 index 000000000..a1366a1ad --- /dev/null +++ b/tests/test_validators.py @@ -0,0 +1,35 @@ +from django.db import models +from django.test import TestCase +from rest_framework import serializers + + +class ExampleModel(models.Model): + username = models.CharField(unique=True, max_length=100) + + +class ExampleSerializer(serializers.ModelSerializer): + class Meta: + model = ExampleModel + + +class TestUniquenessValidation(TestCase): + def setUp(self): + self.instance = ExampleModel.objects.create(username='existing') + + def test_is_not_unique(self): + data = {'username': 'existing'} + serializer = ExampleSerializer(data=data) + assert not serializer.is_valid() + assert serializer.errors == {'username': ['This field must be unique.']} + + def test_is_unique(self): + data = {'username': 'other'} + serializer = ExampleSerializer(data=data) + assert serializer.is_valid() + assert serializer.validated_data == {'username': 'other'} + + def test_updated_instance_excluded(self): + data = {'username': 'existing'} + serializer = ExampleSerializer(self.instance, data=data) + assert serializer.is_valid() + assert serializer.validated_data == {'username': 'existing'} From 9805a085fb115785f272489dc24b51ba6f8e6329 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 29 Sep 2014 11:23:02 +0100 Subject: [PATCH 105/249] UniqueTogetherValidator --- rest_framework/serializers.py | 80 ++++++++++++++++++--- rest_framework/validators.py | 38 +++++++--- tests/test_validators.py | 129 ++++++++++++++++++++++++++++++++-- 3 files changed, 223 insertions(+), 24 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 080b958d5..09ad376a2 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -23,6 +23,7 @@ from rest_framework.utils.field_mapping import ( get_relation_kwargs, get_nested_relation_kwargs, ClassLookupDict ) +from rest_framework.validators import UniqueTogetherValidator import copy import inspect @@ -95,7 +96,7 @@ class BaseSerializer(Field): def is_valid(self, raise_exception=False): if not hasattr(self, '_validated_data'): try: - self._validated_data = self.to_internal_value(self._initial_data) + self._validated_data = self.run_validation(self._initial_data) except ValidationError as exc: self._validated_data = {} self._errors = exc.message_dict @@ -223,15 +224,43 @@ class Serializer(BaseSerializer): return html.parse_html_dict(dictionary, prefix=self.field_name) return dictionary.get(self.field_name, empty) - def to_internal_value(self, data): + def run_validation(self, data=empty): """ - Dict of native values <- Dict of primitive datatypes. + 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. """ + 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): raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: ['Invalid data'] }) + value = self.to_internal_value(data) + try: + self.run_validators(value) + self.validate(value) + except ValidationError as exc: + raise ValidationError({ + api_settings.NON_FIELD_ERRORS_KEY: exc.messages + }) + return value + + def to_internal_value(self, data): + """ + Dict of native values <- Dict of primitive datatypes. + """ ret = {} errors = {} fields = [field for field in self.fields.values() if not field.read_only] @@ -253,12 +282,7 @@ class Serializer(BaseSerializer): if errors: raise ValidationError(errors) - try: - return self.validate(ret) - except ValidationError as exc: - raise ValidationError({ - api_settings.NON_FIELD_ERRORS_KEY: exc.messages - }) + return ret def to_representation(self, instance): """ @@ -355,6 +379,14 @@ class ModelSerializer(Serializer): }) _related_class = PrimaryKeyRelatedField + def __init__(self, *args, **kwargs): + super(ModelSerializer, self).__init__(*args, **kwargs) + if 'validators' not in kwargs: + validators = self.get_unique_together_validators() + if validators: + self.validators.extend(validators) + self._kwargs['validators'] = validators + def create(self, attrs): ModelClass = self.Meta.model @@ -381,6 +413,36 @@ class ModelSerializer(Serializer): setattr(obj, attr, value) obj.save() + def get_unique_together_validators(self): + field_names = set([ + field.source for field in self.fields.values() + if (field.source != '*') and ('.' not in field.source) + ]) + + validators = [] + model_class = self.Meta.model + + for unique_together in model_class._meta.unique_together: + if field_names.issuperset(set(unique_together)): + validator = UniqueTogetherValidator( + queryset=model_class._default_manager, + fields=unique_together + ) + validator.serializer_field = self + validators.append(validator) + + for parent_class in 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 + ) + validator.serializer_field = self + validators.append(validator) + + return validators + def _get_base_fields(self): declared_fields = copy.deepcopy(self._declared_fields) diff --git a/rest_framework/validators.py b/rest_framework/validators.py index f5fbeb3ca..20de4b427 100644 --- a/rest_framework/validators.py +++ b/rest_framework/validators.py @@ -1,18 +1,26 @@ +""" +We perform uniqueness checks explicitly on the serializer class, rather +the using Django's `.full_clean()`. + +This gives us better seperation of concerns, allows us to use single-step +object creation, and makes it possible to switch between using the implicit +`ModelSerializer` class and an equivelent explicit `Serializer` class. +""" from django.core.exceptions import ValidationError +from django.utils.translation import ugettext_lazy as _ +from rest_framework.utils.representation import smart_repr class UniqueValidator: # Validators with `requires_context` will have the field instance # passed to them when the field is instantiated. requires_context = True + message = _('This field must be unique.') def __init__(self, queryset): self.queryset = queryset self.serializer_field = None - def get_queryset(self): - return self.queryset.all() - def __call__(self, value): field = self.serializer_field @@ -24,15 +32,22 @@ class UniqueValidator: # Ensure uniqueness. filter_kwargs = {field_name: value} - queryset = self.get_queryset().filter(**filter_kwargs) + queryset = self.queryset.filter(**filter_kwargs) if instance: queryset = queryset.exclude(pk=instance.pk) if queryset.exists(): - raise ValidationError('This field must be unique.') + raise ValidationError(self.message) + + def __repr__(self): + return '<%s(queryset=%s)>' % ( + self.__class__.__name__, + smart_repr(self.queryset) + ) class UniqueTogetherValidator: requires_context = True + message = _('The fields {field_names} must make a unique set.') def __init__(self, queryset, fields): self.queryset = queryset @@ -49,9 +64,16 @@ class UniqueTogetherValidator: filter_kwargs = dict([ (field_name, value[field_name]) for field_name in self.fields ]) - queryset = self.get_queryset().filter(**filter_kwargs) + queryset = self.queryset.filter(**filter_kwargs) if instance: queryset = queryset.exclude(pk=instance.pk) if queryset.exists(): - field_names = ' and '.join(self.fields) - raise ValidationError('The fields %s must make a unique set.' % field_names) + field_names = ', '.join(self.fields) + raise ValidationError(self.message.format(field_names=field_names)) + + def __repr__(self): + return '<%s(queryset=%s, fields=%s)>' % ( + self.__class__.__name__, + smart_repr(self.queryset), + smart_repr(self.fields) + ) diff --git a/tests/test_validators.py b/tests/test_validators.py index a1366a1ad..c35ecb514 100644 --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -3,33 +3,148 @@ from django.test import TestCase from rest_framework import serializers -class ExampleModel(models.Model): +def dedent(blocktext): + return '\n'.join([line[12:] for line in blocktext.splitlines()[1:-1]]) + + +# Tests for `UniqueValidator` +# --------------------------- + +class UniquenessModel(models.Model): username = models.CharField(unique=True, max_length=100) -class ExampleSerializer(serializers.ModelSerializer): +class UniquenessSerializer(serializers.ModelSerializer): class Meta: - model = ExampleModel + model = UniquenessModel class TestUniquenessValidation(TestCase): def setUp(self): - self.instance = ExampleModel.objects.create(username='existing') + self.instance = UniquenessModel.objects.create(username='existing') + + def test_repr(self): + serializer = UniquenessSerializer() + expected = dedent(""" + UniquenessSerializer(): + id = IntegerField(label='ID', read_only=True) + username = CharField(max_length=100, validators=[<UniqueValidator(queryset=UniquenessModel.objects.all())>]) + """) + assert repr(serializer) == expected def test_is_not_unique(self): data = {'username': 'existing'} - serializer = ExampleSerializer(data=data) + serializer = UniquenessSerializer(data=data) assert not serializer.is_valid() assert serializer.errors == {'username': ['This field must be unique.']} def test_is_unique(self): data = {'username': 'other'} - serializer = ExampleSerializer(data=data) + serializer = UniquenessSerializer(data=data) assert serializer.is_valid() assert serializer.validated_data == {'username': 'other'} def test_updated_instance_excluded(self): data = {'username': 'existing'} - serializer = ExampleSerializer(self.instance, data=data) + serializer = UniquenessSerializer(self.instance, data=data) assert serializer.is_valid() assert serializer.validated_data == {'username': 'existing'} + + +# Tests for `UniqueTogetherValidator` +# ----------------------------------- + +class UniquenessTogetherModel(models.Model): + race_name = models.CharField(max_length=100) + position = models.IntegerField() + + class Meta: + unique_together = ('race_name', 'position') + + +class UniquenessTogetherSerializer(serializers.ModelSerializer): + class Meta: + model = UniquenessTogetherModel + + +class TestUniquenessTogetherValidation(TestCase): + def setUp(self): + self.instance = UniquenessTogetherModel.objects.create( + race_name='example', + position=1 + ) + UniquenessTogetherModel.objects.create( + race_name='example', + position=2 + ) + UniquenessTogetherModel.objects.create( + race_name='other', + position=1 + ) + + def test_repr(self): + serializer = UniquenessTogetherSerializer() + expected = dedent(""" + UniquenessTogetherSerializer(validators=[<UniqueTogetherValidator(queryset=UniquenessTogetherModel.objects.all(), fields=('race_name', 'position'))>]): + id = IntegerField(label='ID', read_only=True) + race_name = CharField(max_length=100) + position = IntegerField() + """) + assert repr(serializer) == expected + + def test_is_not_unique_together(self): + """ + Failing unique together validation should result in non field errors. + """ + data = {'race_name': 'example', 'position': 2} + serializer = UniquenessTogetherSerializer(data=data) + print serializer.validators + assert not serializer.is_valid() + assert serializer.errors == { + 'non_field_errors': [ + 'The fields race_name, position must make a unique set.' + ] + } + + def test_is_unique_together(self): + """ + In a unique together validation, one field may be non-unique + so long as the set as a whole is unique. + """ + data = {'race_name': 'other', 'position': 2} + serializer = UniquenessTogetherSerializer(data=data) + assert serializer.is_valid() + assert serializer.validated_data == { + 'race_name': 'other', + 'position': 2 + } + + def test_updated_instance_excluded_from_unique_together(self): + """ + When performing an update, the existing instance does not count + as a match against uniqueness. + """ + data = {'race_name': 'example', 'position': 1} + serializer = UniquenessTogetherSerializer(self.instance, data=data) + assert serializer.is_valid() + assert serializer.validated_data == { + 'race_name': 'example', + 'position': 1 + } + + def test_ignore_exlcuded_fields(self): + """ + When model fields are not included in a serializer, then uniqueness + validtors should not be added for that field. + """ + class ExcludedFieldSerializer(serializers.ModelSerializer): + class Meta: + model = UniquenessTogetherModel + fields = ('id', 'race_name',) + serializer = ExcludedFieldSerializer() + expected = dedent(""" + ExcludedFieldSerializer(): + id = IntegerField(label='ID', read_only=True) + race_name = CharField(max_length=100) + """) + assert repr(serializer) == expected From d2d412993f537952fd7809ded3e981f85ec318e9 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 29 Sep 2014 11:24:21 +0100 Subject: [PATCH 106/249] .validate() on serializer fields --- rest_framework/fields.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 231f693ca..fee6080aa 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -254,6 +254,7 @@ class Field(object): value = self.to_internal_value(data) self.run_validators(value) + self.validate(value) return value def run_validators(self, value): @@ -270,6 +271,9 @@ class Field(object): if errors: raise ValidationError(errors) + def validate(self, value): + pass + def to_internal_value(self, data): """ Transform the *incoming* primative data into a native value. From 4798df52df5d59cc570043e3eb7e26f7ce57b54f Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 29 Sep 2014 12:57:05 +0100 Subject: [PATCH 107/249] Update release notes --- docs/topics/3.0-announcement.md | 44 +++++++++++++++++++++++++++++---- tests/test_validators.py | 1 - 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 24f4ed4c2..92062552a 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -146,7 +146,41 @@ The corresponding code would now look like this: extras = {'user': request.user} # Include the user when saving. serializer.save(extras=extras) -#### Printable serializer reprensentations. +#### Limitations of ModelSerializer validation. + +This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner seperation, and ensures that there's no automatic validation behavior on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes. + +This change comes with the following limitations: + +* The model `.clean()` method will not be called as part of serializer validation. Use the serializer `.validate()` method to perform a final validation step on incoming data where required. +* The `.unique_for_date`, `.unique_for_month` and `.unique_for_year` options on model fields are not automatically validated. Again, you'll need to handle these explicitly on the serializer if required. + +#### Writable nested serialization. + +REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic: + +* There can be complex dependancies involved in order of saving multiple related model instances. +* It's unclear what behavior the user should expect when related models are passed `None` data. +* It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records. + +Using the `depth` option on `ModelSerializer` will now create **read-only nested serializers** by default. To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the `create()` and/or `update()` methods explicitly. + + class UserSerializer(serializers.ModelSerializer): + profile = ProfileSerializer() + + class Meta: + model = User + fields = ('username', 'email', 'profile') + + def create(self, validated_data): + profile_data = validated_data.pop['profile'] + user = User.objects.create(**validated_data) + profile = Profile.objects.create(user=user, **profile_data) + return user + +The single-step object creation makes this far simpler and more obvious than the previous `.restore_object()` behavior. + +#### Printable serializer representations. Serializer instances now support a printable representation that allows you to inspect the fields present on the instance. @@ -279,7 +313,7 @@ There are four mathods that can be overriding, depending on what functionality y * `.to_internal_value()` - Override this to support deserialization, for write operations. * `.create()` and `.update()` - Overide either or both of these to support saving instances. -##### Read-only serializers. +##### Read-only `BaseSerializer` classes. To implement a read-only serializer using the `BaseSerializer` class, we just need to override the `.to_representation()` method. Let's take a look at an example using a simple Django model: @@ -313,7 +347,7 @@ Or use it to serialize multiple instances: serializer = HighScoreSerializer(queryset, many=True) return Response(serializer.data) -##### Read-write serializers. +##### Read-write `BaseSerializer` classes. To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `ValidationError` if the supplied data is in an incorrect format. @@ -358,9 +392,9 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd def create(self, validated_data): return HighScore.objects.create(**validated_data) -#### Creating new base classes with `BaseSerializer`. +#### Creating new generic serializers with `BaseSerializer`. -The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles or for integrating with different storage backends. +The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends. The following class is an example of a generic serializer that can handle coercing aribitrary objects into primative representations. diff --git a/tests/test_validators.py b/tests/test_validators.py index c35ecb514..ac04d2b4c 100644 --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -98,7 +98,6 @@ class TestUniquenessTogetherValidation(TestCase): """ data = {'race_name': 'example', 'position': 2} serializer = UniquenessTogetherSerializer(data=data) - print serializer.validators assert not serializer.is_valid() assert serializer.errors == { 'non_field_errors': [ From 657d1de032bfa392609d53751e89366b972cd678 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 29 Sep 2014 14:12:09 +0100 Subject: [PATCH 108/249] Latest release notes --- docs/topics/3.0-announcement.md | 39 +++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 92062552a..584c49794 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -560,6 +560,35 @@ The following usage will *now raise an error*: email = serializers.EmailField(source='email') +#### The `UniqueValidator` and `UniqueTogetherValidator` classes. + +REST framework now provides two new validators that allow you to ensure field uniqueness, while still using a completely explicit `Serializer` class instead of using `ModelSerializer`. + +The `UniqueValidator` should be applied to a serializer field, and takes a single `queryset` argument. + + from rest_framework import serializers + from rest_framework.validators import UniqueValidator + + class OrganizationSerializer(serializers.Serializer): + url = serializers.HyperlinkedIdentityField(view_name='organisation_detail') + created = serializers.DateTimeField(read_only=True) + name = serializers.CharField( + max_length=100, + validators=UniqueValidator(queryset=Organisation.objects.all()) + ) + +The `UniqueTogetherValidator` should be applied to a serializer, and takes a `queryset` argument and a `fields` argument which should be a list or tuple of field names. + + class RaceResultSerializer(serializers.Serializer): + category = serializers.ChoiceField(['5k', '10k']) + position = serializers.IntegerField() + name = serializers.CharField(max_length=100) + + default_validators = [UniqueTogetherValidator( + queryset=RaceResult.objects.all(), + fields=('category', 'position') + )] + ## Generic views #### Simplification of view logic. @@ -633,6 +662,16 @@ The `COMPACT_JSON` setting has been added, and can be used to revert this behavi 'COMPACT_JSON': False } +#### File fields as URLs + +The `FileField` and `ImageField` classes are now represented as URLs by default. You should ensure you set Django's standard `MEDIA_URL` setting appropriately. + +You can revert this behavior, and display filenames as the representation, using the `UPLOADED_FILES_USE_URL` settings key: + + REST_FRAMEWORK = { + 'UPLOADED_FILES_USE_URL': False + } + #### Throttle headers using `Retry-After`. The custom `X-Throttle-Wait-Second` header has now been dropped in favor of the standard `Retry-After` header. You can revert this behavior if needed by writing a custom exception handler for your application. From d1b2c8ac7faec65483cbddf4f1718ca4f5805246 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 29 Sep 2014 14:12:26 +0100 Subject: [PATCH 109/249] Absolute URLs for file fields --- rest_framework/fields.py | 12 +++++++----- rest_framework/serializers.py | 2 -- tests/test_fields.py | 17 +++++++++++++++++ 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index fee6080aa..f7ea3b0c2 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -150,10 +150,6 @@ class Field(object): messages.update(error_messages or {}) self.error_messages = messages - for validator in validators: - if getattr(validator, 'requires_context', False): - validator.serializer_field = self - def bind(self, field_name, parent): """ Initializes the field name and parent for the field instance. @@ -264,6 +260,8 @@ class Field(object): """ errors = [] for validator in self.validators: + if getattr(validator, 'requires_context', False): + validator.serializer_field = self try: validator(value) except ValidationError as exc: @@ -907,7 +905,11 @@ class FileField(Field): def to_representation(self, value): if self.use_url: - return settings.MEDIA_URL + value.url + url = settings.MEDIA_URL + value.url + request = self.context.get('request', None) + if request is not None: + return request.build_absolute_uri(url) + return url return value.name diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 09ad376a2..0faa56718 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -428,7 +428,6 @@ class ModelSerializer(Serializer): queryset=model_class._default_manager, fields=unique_together ) - validator.serializer_field = self validators.append(validator) for parent_class in model_class._meta.parents.keys(): @@ -438,7 +437,6 @@ class ModelSerializer(Serializer): queryset=parent_class._default_manager, fields=unique_together ) - validator.serializer_field = self validators.append(validator) return validators diff --git a/tests/test_fields.py b/tests/test_fields.py index aa8c3a68c..bbd9f93d8 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -953,6 +953,23 @@ class TestListField(FieldValues): field = fields.ListField(child=fields.IntegerField()) +# Tests for FieldField. +# --------------------- + +class MockRequest: + def build_absolute_uri(self, value): + return 'http://example.com' + value + + +class TestFileFieldContext: + def test_fully_qualified_when_request_in_context(self): + field = fields.FileField(max_length=10) + field._context = {'request': MockRequest()} + obj = MockFile(name='example.txt', url='/example.txt') + value = field.to_representation(obj) + assert value == 'http://example.com/example.txt' + + # Tests for SerializerMethodField. # -------------------------------- From 83a5ea8db27b9452a5539f1e0574f493392a91ad Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 29 Sep 2014 21:17:13 +0100 Subject: [PATCH 110/249] Update release notes --- docs/topics/3.0-announcement.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 584c49794..12ab5a0dc 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -664,14 +664,26 @@ The `COMPACT_JSON` setting has been added, and can be used to revert this behavi #### File fields as URLs -The `FileField` and `ImageField` classes are now represented as URLs by default. You should ensure you set Django's standard `MEDIA_URL` setting appropriately. +The `FileField` and `ImageField` classes are now represented as URLs by default. You should ensure you set Django's [standard `MEDIA_URL` setting](https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-MEDIA_URL) appropriately, and ensure your application [serves the uploaded files](https://docs.djangoproject.com/en/dev/howto/static-files/#serving-uploaded-files-in-development). -You can revert this behavior, and display filenames as the representation, using the `UPLOADED_FILES_USE_URL` settings key: +You can revert this behavior, and display filenames in the representation by using the `UPLOADED_FILES_USE_URL` settings key: REST_FRAMEWORK = { 'UPLOADED_FILES_USE_URL': False } +You can also modify serializer fields individually, using the `use_url` argument: + + uploaded_file = serializers.FileField(user_url=False) + +Also note that you should pass the `request` object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form `https://example.com/url_path/filename.txt`. For example: + + context = {'request': request} + serializer = ExampleSerializer(instance, context=context) + return Response(serializer.data) + +If the request is omitted from the context, the returned URLs will be of the form `/url_path/filename.txt`. + #### Throttle headers using `Retry-After`. The custom `X-Throttle-Wait-Second` header has now been dropped in favor of the standard `Retry-After` header. You can revert this behavior if needed by writing a custom exception handler for your application. From da4900a353bd1136aa96cb5444b34f7beefa8e85 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Tue, 30 Sep 2014 11:10:13 +0100 Subject: [PATCH 111/249] Update 3.0-announcement.md --- docs/topics/3.0-announcement.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 12ab5a0dc..1c7e016eb 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -9,10 +9,8 @@ See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-fr The most notable outstanding issues still to resolved on the `version-3.0` branch are as follows: * Forms support for serializers and in the browsable API. -* Enforcing uniqueness on `unique=True` and `unique_together` fields. * Optimisations for serialializing primary keys. * Refine style of validation errors in some cases, such as validation errors in `ListField`. -* `.validate()` method on fields. * `.transform_<field>()` method on serializers. **Your feedback on the upgrade process and 3.0 changes is hugely important!** From 770d63fb046917f9fe1f08449f07bf13f1adfa4f Mon Sep 17 00:00:00 2001 From: Omer Katz <omer.drow@gmail.com> Date: Wed, 1 Oct 2014 13:12:33 +0300 Subject: [PATCH 112/249] Fixed documentation typo. --- docs/topics/3.0-announcement.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 1c7e016eb..d2505a1b3 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -75,7 +75,7 @@ Previously the serializers used a two-step object creation, as follows: This style is in line with how the `ModelForm` class works in Django, but is problematic for a number of reasons: -* Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been save. This type of data needed to be hidden in some undocumentated state on the object instance, or kept as state on the serializer instance so that it could be used when `.save()` is called. +* Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumentated state on the object instance, or kept as state on the serializer instance so that it could be used when `.save()` is called. * Instantiating model instances directly means that you cannot use model manager classes for instance creation, eg `ExampleModel.objects.create(...)`. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints. * The two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save? From 381771731f48c75e7d5951e353049cceec386512 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 1 Oct 2014 13:09:14 +0100 Subject: [PATCH 113/249] Use six.text_type instead of str everywhere --- rest_framework/compat.py | 9 +++++---- rest_framework/fields.py | 22 +++++++++++----------- rest_framework/filters.py | 3 ++- rest_framework/generics.py | 5 +++-- rest_framework/parsers.py | 3 ++- rest_framework/relations.py | 3 ++- rest_framework/reverse.py | 3 ++- rest_framework/utils/encoders.py | 6 +++--- 8 files changed, 30 insertions(+), 24 deletions(-) diff --git a/rest_framework/compat.py b/rest_framework/compat.py index 89af9b485..3993cee6d 100644 --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -5,11 +5,12 @@ versions of django/python, and compatibility wrappers around optional packages. # flake8: noqa from __future__ import unicode_literals -import django -import inspect + from django.core.exceptions import ImproperlyConfigured from django.conf import settings from django.utils import six +import django +import inspect # Handle django.utils.encoding rename in 1.5 onwards. @@ -177,12 +178,12 @@ class RequestFactory(DjangoRequestFactory): r = { 'PATH_INFO': self._get_path(parsed), 'QUERY_STRING': force_text(parsed[4]), - 'REQUEST_METHOD': str(method), + 'REQUEST_METHOD': six.text_type(method), } if data: r.update({ 'CONTENT_LENGTH': len(data), - 'CONTENT_TYPE': str(content_type), + 'CONTENT_TYPE': six.text_type(content_type), 'wsgi.input': FakePayload(data), }) elif django.VERSION <= (1, 4): diff --git a/rest_framework/fields.py b/rest_framework/fields.py index f7ea3b0c2..f3ff22334 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -2,7 +2,7 @@ from django import forms from django.conf import settings from django.core import validators from django.core.exceptions import ValidationError -from django.utils import timezone +from django.utils import six, timezone from django.utils.datastructures import SortedDict from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.encoding import is_protected_type @@ -431,10 +431,10 @@ class CharField(Field): return super(CharField, self).run_validation(data) def to_internal_value(self, data): - return str(data) + return six.text_type(data) def to_representation(self, value): - return str(value) + return six.text_type(value) class EmailField(CharField): @@ -448,10 +448,10 @@ class EmailField(CharField): self.validators.append(validator) def to_internal_value(self, data): - return str(data).strip() + return six.text_type(data).strip() def to_representation(self, value): - return str(value).strip() + return six.text_type(value).strip() class RegexField(CharField): @@ -510,7 +510,7 @@ class IntegerField(Field): def to_internal_value(self, data): try: - data = int(str(data)) + data = int(six.text_type(data)) except (ValueError, TypeError): self.fail('invalid') return data @@ -616,7 +616,7 @@ class DecimalField(Field): def to_representation(self, value): if not isinstance(value, decimal.Decimal): - value = decimal.Decimal(str(value).strip()) + value = decimal.Decimal(six.text_type(value).strip()) context = decimal.getcontext().copy() context.prec = self.max_digits @@ -832,19 +832,19 @@ class ChoiceField(Field): # Allows us to deal with eg. integer choices while supporting either # integer or string input, but still get the correct datatype out. self.choice_strings_to_values = dict([ - (str(key), key) for key in self.choices.keys() + (six.text_type(key), key) for key in self.choices.keys() ]) super(ChoiceField, self).__init__(**kwargs) def to_internal_value(self, data): try: - return self.choice_strings_to_values[str(data)] + return self.choice_strings_to_values[six.text_type(data)] except KeyError: self.fail('invalid_choice', input=data) def to_representation(self, value): - return self.choice_strings_to_values[str(value)] + return self.choice_strings_to_values[six.text_type(value)] class MultipleChoiceField(ChoiceField): @@ -864,7 +864,7 @@ class MultipleChoiceField(ChoiceField): def to_representation(self, value): return set([ - self.choice_strings_to_values[str(item)] for item in value + self.choice_strings_to_values[six.text_type(item)] for item in value ]) diff --git a/rest_framework/filters.py b/rest_framework/filters.py index 085dfe659..4c485668a 100644 --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -3,6 +3,7 @@ Provides generic filtering backends that can be used to filter the results returned by list views. """ from __future__ import unicode_literals + from django.core.exceptions import ImproperlyConfigured from django.db import models from django.utils import six @@ -97,7 +98,7 @@ class SearchFilter(BaseFilterBackend): if not search_fields: return queryset - orm_lookups = [self.construct_search(str(search_field)) + orm_lookups = [self.construct_search(six.text_type(search_field)) for search_field in search_fields] for search_term in self.get_search_terms(request): diff --git a/rest_framework/generics.py b/rest_framework/generics.py index cf903dab3..3d6cf1684 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -3,10 +3,11 @@ Generic views that provide commonly needed behaviour. """ from __future__ import unicode_literals -from django.db.models.query import QuerySet from django.core.paginator import Paginator, InvalidPage +from django.db.models.query import QuerySet from django.http import Http404 from django.shortcuts import get_object_or_404 as _get_object_or_404 +from django.utils import six from django.utils.translation import ugettext as _ from rest_framework import views, mixins from rest_framework.settings import api_settings @@ -127,7 +128,7 @@ class GenericAPIView(views.APIView): error_format = _('Invalid page (%(page_number)s): %(message)s') raise Http404(error_format % { 'page_number': page_number, - 'message': str(exc) + 'message': six.text_type(exc) }) return page diff --git a/rest_framework/parsers.py b/rest_framework/parsers.py index fa02ecf1e..ccb82f03b 100644 --- a/rest_framework/parsers.py +++ b/rest_framework/parsers.py @@ -5,6 +5,7 @@ They give us a generic way of being able to handle various media types on the request, such as form content or json encoded data. """ from __future__ import unicode_literals + from django.conf import settings from django.core.files.uploadhandler import StopFutureHandlers from django.http import QueryDict @@ -132,7 +133,7 @@ class MultiPartParser(BaseParser): data, files = parser.parse() return DataAndFiles(data, files) except MultiPartParserError as exc: - raise ParseError('Multipart form parse error - %s' % str(exc)) + raise ParseError('Multipart form parse error - %s' % six.text_type(exc)) class XMLParser(BaseParser): diff --git a/rest_framework/relations.py b/rest_framework/relations.py index b37a6fedd..b5effc6cb 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -4,6 +4,7 @@ from rest_framework.reverse import reverse from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch, Resolver404 from django.db.models.query import QuerySet +from django.utils import six from django.utils.translation import ugettext_lazy as _ @@ -49,7 +50,7 @@ class StringRelatedField(Field): super(StringRelatedField, self).__init__(**kwargs) def to_representation(self, value): - return str(value) + return six.text_type(value) class PrimaryKeyRelatedField(RelatedField): diff --git a/rest_framework/reverse.py b/rest_framework/reverse.py index a51b07f54..a74e8aa2d 100644 --- a/rest_framework/reverse.py +++ b/rest_framework/reverse.py @@ -3,6 +3,7 @@ Provide reverse functions that return fully qualified URLs """ from __future__ import unicode_literals from django.core.urlresolvers import reverse as django_reverse +from django.utils import six from django.utils.functional import lazy @@ -20,4 +21,4 @@ def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra return url -reverse_lazy = lazy(reverse, str) +reverse_lazy = lazy(reverse, six.text_type) diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py index 174b08b8b..7c4179a1f 100644 --- a/rest_framework/utils/encoders.py +++ b/rest_framework/utils/encoders.py @@ -2,8 +2,8 @@ Helper classes for parsers. """ from __future__ import unicode_literals -from django.utils import timezone from django.db.models.query import QuerySet +from django.utils import six, timezone from django.utils.datastructures import SortedDict from django.utils.functional import Promise from rest_framework.compat import force_text @@ -40,7 +40,7 @@ class JSONEncoder(json.JSONEncoder): representation = representation[:12] return representation elif isinstance(obj, datetime.timedelta): - return str(obj.total_seconds()) + return six.text_type(obj.total_seconds()) elif isinstance(obj, decimal.Decimal): # Serializers will coerce decimals to strings by default. return float(obj) @@ -72,7 +72,7 @@ else: than the usual behaviour of sorting the keys. """ def represent_decimal(self, data): - return self.represent_scalar('tag:yaml.org,2002:str', str(data)) + return self.represent_scalar('tag:yaml.org,2002:str', six.text_type(data)) def represent_mapping(self, tag, mapping, flow_style=None): value = [] From c630a12e26f29145784523dd1b01ab0b3576f42c Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 1 Oct 2014 13:24:47 +0100 Subject: [PATCH 114/249] Deal with lazy strings in serializer reprs --- rest_framework/utils/representation.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/rest_framework/utils/representation.py b/rest_framework/utils/representation.py index e64fdd223..180b51f8d 100644 --- a/rest_framework/utils/representation.py +++ b/rest_framework/utils/representation.py @@ -3,6 +3,8 @@ Helper functions for creating user-friendly representations of serializer classes and serializer fields. """ from django.db import models +from django.utils.functional import Promise +from rest_framework.compat import force_text import re @@ -19,6 +21,9 @@ def smart_repr(value): if isinstance(value, models.Manager): return manager_repr(value) + if isinstance(value, Promise) and value._delegate_text: + value = force_text(value) + value = repr(value) # Representations like u'help text' From c171fa21ac62538331755524057d2435f33ec8a5 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 1 Oct 2014 19:44:46 +0100 Subject: [PATCH 115/249] First pass at HTML form rendering --- rest_framework/renderers.py | 47 +++++++++++++++++-- rest_framework/serializers.py | 2 + .../rest_framework/fields/attrs.html | 1 + .../fields/horizontal/checkbox.html | 10 ++++ .../fields/horizontal/fieldset.html | 10 ++++ .../fields/horizontal/input.html | 7 +++ .../fields/horizontal/label.html | 1 + .../fields/horizontal/select.html | 10 ++++ .../fields/horizontal/select_checkbox.html | 22 +++++++++ .../fields/horizontal/select_multiple.html | 10 ++++ .../fields/horizontal/select_radio.html | 22 +++++++++ .../fields/horizontal/textarea.html | 7 +++ .../fields/inline/checkbox.html | 6 +++ .../fields/inline/fieldset.html | 3 ++ .../rest_framework/fields/inline/input.html | 4 ++ .../rest_framework/fields/inline/label.html | 1 + .../rest_framework/fields/inline/select.html | 8 ++++ .../fields/inline/select_checkbox.html | 11 +++++ .../fields/inline/select_multiple.html | 8 ++++ .../fields/inline/select_radio.html | 11 +++++ .../fields/inline/textarea.html | 4 ++ .../fields/vertical/checkbox.html | 6 +++ .../fields/vertical/fieldset.html | 6 +++ .../rest_framework/fields/vertical/input.html | 5 ++ .../rest_framework/fields/vertical/label.html | 1 + .../fields/vertical/select.html | 8 ++++ .../fields/vertical/select_checkbox.html | 22 +++++++++ .../fields/vertical/select_multiple.html | 8 ++++ .../fields/vertical/select_radio.html | 22 +++++++++ .../fields/vertical/textarea.html | 5 ++ .../templates/rest_framework/form.html | 40 +++++++++++----- rest_framework/templatetags/rest_framework.py | 8 ++++ rest_framework/utils/field_mapping.py | 3 ++ tests/test_model_serializer.py | 2 +- 34 files changed, 325 insertions(+), 16 deletions(-) create mode 100644 rest_framework/templates/rest_framework/fields/attrs.html create mode 100644 rest_framework/templates/rest_framework/fields/horizontal/checkbox.html create mode 100644 rest_framework/templates/rest_framework/fields/horizontal/fieldset.html create mode 100644 rest_framework/templates/rest_framework/fields/horizontal/input.html create mode 100644 rest_framework/templates/rest_framework/fields/horizontal/label.html create mode 100644 rest_framework/templates/rest_framework/fields/horizontal/select.html create mode 100644 rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html create mode 100644 rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html create mode 100644 rest_framework/templates/rest_framework/fields/horizontal/select_radio.html create mode 100644 rest_framework/templates/rest_framework/fields/horizontal/textarea.html create mode 100644 rest_framework/templates/rest_framework/fields/inline/checkbox.html create mode 100644 rest_framework/templates/rest_framework/fields/inline/fieldset.html create mode 100644 rest_framework/templates/rest_framework/fields/inline/input.html create mode 100644 rest_framework/templates/rest_framework/fields/inline/label.html create mode 100644 rest_framework/templates/rest_framework/fields/inline/select.html create mode 100644 rest_framework/templates/rest_framework/fields/inline/select_checkbox.html create mode 100644 rest_framework/templates/rest_framework/fields/inline/select_multiple.html create mode 100644 rest_framework/templates/rest_framework/fields/inline/select_radio.html create mode 100644 rest_framework/templates/rest_framework/fields/inline/textarea.html create mode 100644 rest_framework/templates/rest_framework/fields/vertical/checkbox.html create mode 100644 rest_framework/templates/rest_framework/fields/vertical/fieldset.html create mode 100644 rest_framework/templates/rest_framework/fields/vertical/input.html create mode 100644 rest_framework/templates/rest_framework/fields/vertical/label.html create mode 100644 rest_framework/templates/rest_framework/fields/vertical/select.html create mode 100644 rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html create mode 100644 rest_framework/templates/rest_framework/fields/vertical/select_multiple.html create mode 100644 rest_framework/templates/rest_framework/fields/vertical/select_radio.html create mode 100644 rest_framework/templates/rest_framework/fields/vertical/textarea.html diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 225f9fe8f..6483a47c0 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -13,17 +13,18 @@ import django from django import forms from django.core.exceptions import ImproperlyConfigured from django.http.multipartparser import parse_header -from django.template import RequestContext, loader, Template +from django.template import Context, RequestContext, loader, Template from django.test.client import encode_multipart from django.utils import six from django.utils.xmlutils import SimplerXMLGenerator +from rest_framework import exceptions, serializers, status, VERSION from rest_framework.compat import StringIO, smart_text, yaml from rest_framework.exceptions import ParseError from rest_framework.settings import api_settings from rest_framework.request import is_form_media_type, override_method from rest_framework.utils import encoders from rest_framework.utils.breadcrumbs import get_breadcrumbs -from rest_framework import exceptions, status, VERSION +from rest_framework.utils.field_mapping import ClassLookupDict def zero_as_none(value): @@ -341,6 +342,42 @@ class HTMLFormRenderer(BaseRenderer): template = 'rest_framework/form.html' charset = 'utf-8' + field_templates = ClassLookupDict({ + serializers.Field: { + 'default': 'input.html' + }, + serializers.BooleanField: { + 'default': 'checkbox.html' + }, + serializers.CharField: { + 'default': 'input.html', + 'textarea': 'textarea.html' + }, + serializers.ChoiceField: { + 'default': 'select.html', + 'radio': 'select_radio.html' + }, + serializers.MultipleChoiceField: { + 'default': 'select_multiple.html', + 'checkbox': 'select_checkbox.html' + } + }) + + def render_field(self, field, value, errors, layout=None): + layout = layout or 'vertical' + style_type = field.style.get('type', 'default') + if style_type == 'textarea' and layout == 'inline': + style_type = 'default' + base = self.field_templates[field][style_type] + template_name = 'rest_framework/fields/' + layout + '/' + base + template = loader.get_template(template_name) + context = Context({ + 'field': field, + 'value': value, + 'errors': errors + }) + return template.render(context) + def render(self, data, accepted_media_type=None, renderer_context=None): """ Render serializer data and return an HTML form, as a string. @@ -349,7 +386,11 @@ class HTMLFormRenderer(BaseRenderer): request = renderer_context['request'] template = loader.get_template(self.template) - context = RequestContext(request, {'form': data}) + context = RequestContext(request, { + 'form': data, + 'layout': getattr(getattr(data, 'Meta', None), 'layout', 'vertical'), + 'renderer': self + }) return template.render(context) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 0faa56718..5da812477 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -302,6 +302,8 @@ class Serializer(BaseSerializer): def __iter__(self): errors = self.errors if hasattr(self, '_errors') else {} for field in self.fields.values(): + if field.read_only: + continue value = self.data.get(field.field_name) if self.data else None error = errors.get(field.field_name) yield FieldResult(field, value, error) diff --git a/rest_framework/templates/rest_framework/fields/attrs.html b/rest_framework/templates/rest_framework/fields/attrs.html new file mode 100644 index 000000000..b5a4dbcf1 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/attrs.html @@ -0,0 +1 @@ +name="{{ field.field_name }}" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.style.rows %}rows="{{ field.style.rows }}"{% endif %} diff --git a/rest_framework/templates/rest_framework/fields/horizontal/checkbox.html b/rest_framework/templates/rest_framework/fields/horizontal/checkbox.html new file mode 100644 index 000000000..dce4a5cf9 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/horizontal/checkbox.html @@ -0,0 +1,10 @@ +<div class="form-group"> + <div class="col-sm-offset-2 col-sm-10"> + <div class="checkbox"> + <label> + <input type="checkbox" name="{{ field.field_name }}" value="true" {% if value %}checked{% endif %}> + {% if field.label %}{{ field.label }}{% endif %} + </label> + </div> + </div> +</div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/fieldset.html b/rest_framework/templates/rest_framework/fields/horizontal/fieldset.html new file mode 100644 index 000000000..86417633f --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/horizontal/fieldset.html @@ -0,0 +1,10 @@ +<fieldset> + {% if field.label %} + <div class="form-group" style="border-bottom: 1px solid #e5e5e5"> + <legend class="control-label col-sm-2 {% if field.style.hide_label %}sr-only{% endif %}" style="border-bottom: 0">{{ field.label }}</legend> + </div> + {% endif %} + {% for field_item in value.field_items.values() %} + {{ renderer.render_field(field_item, layout=layout) }} + {% endfor %} +</fieldset> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/input.html b/rest_framework/templates/rest_framework/fields/horizontal/input.html new file mode 100644 index 000000000..310154bb4 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/horizontal/input.html @@ -0,0 +1,7 @@ +<div class="form-group"> + {% include "rest_framework/fields/horizontal/label.html" %} + <div class="col-sm-10"> + <input type="{{ input_type }}" class="form-control" {% include "rest_framework/fields/attrs.html" %} {% if value %}value="{{ value }}"{% endif %}> + {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} + </div> +</div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/label.html b/rest_framework/templates/rest_framework/fields/horizontal/label.html new file mode 100644 index 000000000..bf21f78cc --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/horizontal/label.html @@ -0,0 +1 @@ +{% if field.label %}<label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label>{% endif %} diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select.html b/rest_framework/templates/rest_framework/fields/horizontal/select.html new file mode 100644 index 000000000..3f8cab0a3 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/horizontal/select.html @@ -0,0 +1,10 @@ +<div class="form-group"> + {% include "rest_framework/fields/horizontal/label.html" %} + <div class="col-sm-10"> + <select class="form-control" name="{{ field.field_name }}"> + {% for key, text in field.choices.items %} + <option value="{{ key }}" {% if key == value %}selected{% endif %}>{{ text }}</option> + {% endfor %} + </select> + </div> +</div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html b/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html new file mode 100644 index 000000000..659eede84 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html @@ -0,0 +1,22 @@ +<div class="form-group"> + {% include "rest_framework/fields/horizontal/label.html" %} + <div class="col-sm-10"> + {% if field.style.inline %} + {% for key, text in field.choices.items %} + <label class="checkbox-inline"> + <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in value %}checked{% endif %}> + {{ text }} + </label> + {% endfor %} + {% else %} + {% for key, text in field.choices.items %} + <div class="checkbox"> + <label> + <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in value %}checked{% endif %}> + {{ text }} + </label> + </div> + {% endfor %} + {% endif %} + </div> +</div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html b/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html new file mode 100644 index 000000000..da25eb2bd --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html @@ -0,0 +1,10 @@ +<div class="form-group"> + {% include "rest_framework/fields/horizontal/label.html" %} + <div class="col-sm-10"> + <select multiple class="form-control" name="{{ field.field_name }}"> + {% for key, text in field.choices.items %} + <option value="{{ key }}" {% if key in value %}selected{% endif %}>{{ text }}</option> + {% endfor %} + </select> + </div> +</div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html b/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html new file mode 100644 index 000000000..188f05e27 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html @@ -0,0 +1,22 @@ +<div class="form-group"> + {% include "rest_framework/fields/horizontal/label.html" %} + <div class="col-sm-10"> + {% if field.style.inline %} + {% for key, text in field.choices.items %} + <label class="radio-inline"> + <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == value %}checked{% endif %}> + {{ text }} + </label> + {% endfor %} + {% else %} + {% for key, text in field.choices.items %} + <div class="radio"> + <label> + <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == value %}checked{% endif %}> + {{ text }} + </label> + </div> + {% endfor %} + {% endif %} + </div> +</div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/textarea.html b/rest_framework/templates/rest_framework/fields/horizontal/textarea.html new file mode 100644 index 000000000..e99266f37 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/horizontal/textarea.html @@ -0,0 +1,7 @@ +<div class="form-group"> + {% include "rest_framework/fields/horizontal/label.html" %} + <div class="col-sm-10"> + <textarea class="form-control" {% include "rest_framework/fields/attrs.html" %}>{% if value %}{{ value }}{% endif %}</textarea> + {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} + </div> +</div> diff --git a/rest_framework/templates/rest_framework/fields/inline/checkbox.html b/rest_framework/templates/rest_framework/fields/inline/checkbox.html new file mode 100644 index 000000000..01d30aaef --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/inline/checkbox.html @@ -0,0 +1,6 @@ +<div class="checkbox"> + <label> + <input type="checkbox" name="{{ field.field_name }}" value="true" {% if value %}checked{% endif %}> + {% if field.label %}{{ field.label }}{% endif %} + </label> +</div> diff --git a/rest_framework/templates/rest_framework/fields/inline/fieldset.html b/rest_framework/templates/rest_framework/fields/inline/fieldset.html new file mode 100644 index 000000000..d22982fdd --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/inline/fieldset.html @@ -0,0 +1,3 @@ +{% for field_item in value.field_items.values() %} + {{ renderer.render_field(field_item, layout=layout) }} +{% endfor %} diff --git a/rest_framework/templates/rest_framework/fields/inline/input.html b/rest_framework/templates/rest_framework/fields/inline/input.html new file mode 100644 index 000000000..aefd16723 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/inline/input.html @@ -0,0 +1,4 @@ +<div class="form-group"> + {% include "rest_framework/fields/inline/label.html" %} + <input type="{{ input_type }}" class="form-control" {% include "rest_framework/fields/attrs.html" %} {% if value %}value="{{ value }}"{% endif %}> +</div> diff --git a/rest_framework/templates/rest_framework/fields/inline/label.html b/rest_framework/templates/rest_framework/fields/inline/label.html new file mode 100644 index 000000000..7d546a571 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/inline/label.html @@ -0,0 +1 @@ +{% if field.label %}<label class="sr-only">{{ field.label }}</label>{% endif %} diff --git a/rest_framework/templates/rest_framework/fields/inline/select.html b/rest_framework/templates/rest_framework/fields/inline/select.html new file mode 100644 index 000000000..cb9a70137 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/inline/select.html @@ -0,0 +1,8 @@ +<div class="form-group"> + {% include "rest_framework/fields/inline/label.html" %} + <select class="form-control" name="{{ field.field_name }}"> + {% for key, text in field.choices.items %} + <option value="{{ key }}" {% if key == value %}selected{% endif %}>{{ text }}</option> + {% endfor %} + </select> +</div> diff --git a/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html b/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html new file mode 100644 index 000000000..424df93e6 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html @@ -0,0 +1,11 @@ +<div class="form-group"> + {% include "rest_framework/fields/inline/label.html" %} + {% for key, text in field.choices.items %} + <div class="checkbox"> + <label> + <input type="checkbox" name="{{ rest_framework/field.field_name }}" value="{{ key }}" {% if key in value %}checked{% endif %}> + {{ text }} + </label> + </div> + {% endfor %} +</div> diff --git a/rest_framework/templates/rest_framework/fields/inline/select_multiple.html b/rest_framework/templates/rest_framework/fields/inline/select_multiple.html new file mode 100644 index 000000000..6fdfd672f --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/inline/select_multiple.html @@ -0,0 +1,8 @@ +<div class="form-group"> + {% include "rest_framework/fields/inline/label.html" %} + <select multiple class="form-control" name="{{ field.field_name }}"> + {% for key, text in field.choices.items %} + <option value="{{ key }}" {% if key in value %}selected{% endif %}>{{ text }}</option> + {% endfor %} + </select> +</div> diff --git a/rest_framework/templates/rest_framework/fields/inline/select_radio.html b/rest_framework/templates/rest_framework/fields/inline/select_radio.html new file mode 100644 index 000000000..ddabc9e96 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/inline/select_radio.html @@ -0,0 +1,11 @@ +<div class="form-group"> + {% include "rest_framework/fields/inline/label.html" %} + {% for key, text in field.choices.items %} + <div class="radio"> + <label> + <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == value %}checked{% endif %}> + {{ text }} + </label> + </div> + {% endfor %} +</div> diff --git a/rest_framework/templates/rest_framework/fields/inline/textarea.html b/rest_framework/templates/rest_framework/fields/inline/textarea.html new file mode 100644 index 000000000..313668098 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/inline/textarea.html @@ -0,0 +1,4 @@ +<div class="form-group"> + {% include "rest_framework/fields/inline/label.html" %} + <textarea class="form-control" {% include "rest_framework/fields/attrs.html" %}>{% if value %}{{ value }}{% endif %}</textarea> +</div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/checkbox.html b/rest_framework/templates/rest_framework/fields/vertical/checkbox.html new file mode 100644 index 000000000..01d30aaef --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/vertical/checkbox.html @@ -0,0 +1,6 @@ +<div class="checkbox"> + <label> + <input type="checkbox" name="{{ field.field_name }}" value="true" {% if value %}checked{% endif %}> + {% if field.label %}{{ field.label }}{% endif %} + </label> +</div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/fieldset.html b/rest_framework/templates/rest_framework/fields/vertical/fieldset.html new file mode 100644 index 000000000..cad32df99 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/vertical/fieldset.html @@ -0,0 +1,6 @@ +<fieldset> + {% if field.label %}<legend {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %} + {% for field_item in value.field_items.values() %} + {{ renderer.render_field(field_item, layout=layout) }} + {% endfor %} +</fieldset> diff --git a/rest_framework/templates/rest_framework/fields/vertical/input.html b/rest_framework/templates/rest_framework/fields/vertical/input.html new file mode 100644 index 000000000..c25407d16 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/vertical/input.html @@ -0,0 +1,5 @@ +<div class="form-group"> + {% include "rest_framework/fields/vertical/label.html" %} + <input type="{{ input_type }}" class="form-control" {% include "rest_framework/fields/attrs.html" %} {% if value %}value="{{ value }}"{% endif %}> + {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} +</div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/label.html b/rest_framework/templates/rest_framework/fields/vertical/label.html new file mode 100644 index 000000000..651939b26 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/vertical/label.html @@ -0,0 +1 @@ +{% if field.label %}<label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label>{% endif %} diff --git a/rest_framework/templates/rest_framework/fields/vertical/select.html b/rest_framework/templates/rest_framework/fields/vertical/select.html new file mode 100644 index 000000000..44679d8a4 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/vertical/select.html @@ -0,0 +1,8 @@ +<div class="form-group"> + {% include "rest_framework/fields/vertical/label.html" %} + <select class="form-control" name="{{ field.field_name }}"> + {% for key, text in field.choices.items %} + <option value="{{ key }}" {% if key == value %}selected{% endif %}>{{ text }}</option> + {% endfor %} + </select> +</div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html b/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html new file mode 100644 index 000000000..e60574c07 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html @@ -0,0 +1,22 @@ +<div class="form-group"> + {% include "rest_framework/fields/vertical/label.html" %} + {% if field.style.inline %} + <div> + {% for key, text in field.choices.items %} + <label class="checkbox-inline"> + <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in value %}checked{% endif %}> + {{ text }} + </label> + {% endfor %} + </div> + {% else %} + {% for key, text in field.choices.items %} + <div class="checkbox"> + <label> + <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in value %}checked{% endif %}> + {{ text }} + </label> + </div> + {% endfor %} + {% endif %} +</div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html b/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html new file mode 100644 index 000000000..f0fa418b5 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html @@ -0,0 +1,8 @@ +<div class="form-group"> + {% include "rest_framework/fields/vertical/label.html" %} + <select multiple class="form-control" name="{{ field.field_name }}"> + {% for key, text in field.choices.items() %} + <option value="{{ key }}" {% if key in value %}selected{% endif %}>{{ text }}</option> + {% endfor %} + </select> +</div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_radio.html b/rest_framework/templates/rest_framework/fields/vertical/select_radio.html new file mode 100644 index 000000000..4ffe38ea9 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/vertical/select_radio.html @@ -0,0 +1,22 @@ +<div class="form-group"> + {% include "rest_framework/fields/vertical/label.html" %} + {% if field.style.inline %} + <div> + {% for key, text in field.choices.items %} + <label class="radio-inline"> + <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key|string==value|string %}checked{% endif %}> + {{ text }} + </label> + {% endfor %} + </div> + {% else %} + {% for key, text in field.choices.items %} + <div class="radio"> + <label> + <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key|string==value|string %}checked{% endif %}> + {{ text }} + </label> + </div> + {% endfor %} + {% endif %} +</div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/textarea.html b/rest_framework/templates/rest_framework/fields/vertical/textarea.html new file mode 100644 index 000000000..33cb27c75 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/vertical/textarea.html @@ -0,0 +1,5 @@ +<div class="form-group"> + {% include "rest_framework/fields/vertical/label.html" %} + <textarea class="form-control" {% include "rest_framework/fields/attrs.html" %}>{% if value %}{{ value }}{% endif %}</textarea> + {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} +</div> diff --git a/rest_framework/templates/rest_framework/form.html b/rest_framework/templates/rest_framework/form.html index b1e148df7..64b1b0bc5 100644 --- a/rest_framework/templates/rest_framework/form.html +++ b/rest_framework/templates/rest_framework/form.html @@ -1,15 +1,31 @@ +<html> +<head> + <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> +</head> +<body> +<div class="container"> + +<h1>User update</h1> +<div class="well"> + {% load rest_framework %} -{% csrf_token %} -{{ form.non_field_errors }} -{% for field in form.fields.values %} - {% if not field.read_only %} - <div class="control-group {% if field.errors %}error{% endif %}"> - {{ field.label_tag|add_class:"control-label" }} - <div class="controls"> - {{ field.widget_html }} - {% if field.help_text %}<span class="help-block">{{ field.help_text }}</span>{% endif %} - {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} +<form {% if layout == "inline" %}class="form-inline"{% elif layout == "horizontal" %}class="form-horizontal"{% endif %} role="form" action="" method="POST"> + {% csrf_token %} + {% for field, value, errors in form %} + {% render_field field value errors layout=layout renderer=renderer %} + {% endfor %} + <!-- form.non_field_errors --> + {% if layout == "horizontal" %} + <div class="form-group"> + <div class="col-sm-offset-2 col-sm-10"> + <button type="submit" class="btn btn-default">Submit</button> + </div> </div> - </div> + {% else %} + <button type="submit" class="btn btn-default">Submit</button> {% endif %} -{% endfor %} +</form> + +</div> +</div></body> +</html> diff --git a/rest_framework/templatetags/rest_framework.py b/rest_framework/templatetags/rest_framework.py index 864d64dd0..88ff9d4ed 100644 --- a/rest_framework/templatetags/rest_framework.py +++ b/rest_framework/templatetags/rest_framework.py @@ -31,6 +31,14 @@ class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])') # And the template tags themselves... +# @register.simple_tag +# def render_field(field, value, errors, renderer): +# return renderer.render_field(field, value, errors) +@register.simple_tag +def render_field(field, value, errors, layout=None, renderer=None): + return renderer.render_field(field, value, errors, layout) + + @register.simple_tag def optional_login(request): """ diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index cf9d910aa..b4d33e395 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -79,6 +79,9 @@ def get_field_kwargs(field_name, model_field): kwargs['choices'] = model_field.flatchoices return kwargs + if isinstance(model_field, models.TextField): + kwargs['style'] = {'type': 'textarea'} + if model_field.null and not isinstance(model_field, models.NullBooleanField): kwargs['allow_null'] = True diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index f74750247..2edf0be5b 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -95,7 +95,7 @@ class TestRegularFieldMappings(TestCase): positive_small_integer_field = IntegerField() slug_field = SlugField(max_length=100) small_integer_field = IntegerField() - text_field = CharField() + text_field = CharField(style={'type': 'textarea'}) time_field = TimeField() url_field = URLField(max_length=100) custom_field = ModelField(model_field=<tests.test_model_serializer.CustomField: custom_field>) From ffc6aa3abcb0f823b43b63db1666913565e6f934 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 1 Oct 2014 21:35:27 +0100 Subject: [PATCH 116/249] More forms support --- rest_framework/relations.py | 20 +++++++++++++++ rest_framework/renderers.py | 25 +++++++++++++++++-- .../fields/vertical/select_multiple.html | 2 +- .../templates/rest_framework/form.html | 2 +- 4 files changed, 45 insertions(+), 4 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index b5effc6cb..8c1356727 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -38,6 +38,16 @@ class RelatedField(Field): queryset = queryset.all() return queryset + @property + def choices(self): + return dict([ + ( + str(self.to_representation(item)), + str(item) + ) + for item in self.queryset.all() + ]) + class StringRelatedField(Field): """ @@ -255,3 +265,13 @@ class ManyRelation(Field): self.child_relation.to_representation(value) for value in obj.all() ] + + @property + def choices(self): + return dict([ + ( + str(self.child_relation.to_representation(item)), + str(item) + ) + for item in self.child_relation.queryset.all() + ]) diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 6483a47c0..297c60d8f 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -360,22 +360,43 @@ class HTMLFormRenderer(BaseRenderer): serializers.MultipleChoiceField: { 'default': 'select_multiple.html', 'checkbox': 'select_checkbox.html' + }, + serializers.ManyRelation: { + 'default': 'select_multiple.html', + 'checkbox': 'select_checkbox.html' } }) + input_type = ClassLookupDict({ + serializers.Field: 'text', + serializers.EmailField: 'email', + serializers.URLField: 'url', + serializers.IntegerField: 'number', + serializers.DateTimeField: 'datetime-local', + serializers.DateField: 'date', + serializers.TimeField: 'time', + }) + def render_field(self, field, value, errors, layout=None): layout = layout or 'vertical' style_type = field.style.get('type', 'default') if style_type == 'textarea' and layout == 'inline': style_type = 'default' + + input_type = self.input_type[field] + if input_type == 'datetime-local': + value = value.rstrip('Z') + base = self.field_templates[field][style_type] template_name = 'rest_framework/fields/' + layout + '/' + base template = loader.get_template(template_name) context = Context({ 'field': field, 'value': value, - 'errors': errors + 'errors': errors, + 'input_type': input_type }) + return template.render(context) def render(self, data, accepted_media_type=None, renderer_context=None): @@ -388,7 +409,7 @@ class HTMLFormRenderer(BaseRenderer): template = loader.get_template(self.template) context = RequestContext(request, { 'form': data, - 'layout': getattr(getattr(data, 'Meta', None), 'layout', 'vertical'), + 'layout': getattr(getattr(data, 'Meta', None), 'layout', 'horizontal'), 'renderer': self }) return template.render(context) diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html b/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html index f0fa418b5..00b25b4b1 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html +++ b/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html @@ -1,7 +1,7 @@ <div class="form-group"> {% include "rest_framework/fields/vertical/label.html" %} <select multiple class="form-control" name="{{ field.field_name }}"> - {% for key, text in field.choices.items() %} + {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key in value %}selected{% endif %}>{{ text }}</option> {% endfor %} </select> diff --git a/rest_framework/templates/rest_framework/form.html b/rest_framework/templates/rest_framework/form.html index 64b1b0bc5..658aa2934 100644 --- a/rest_framework/templates/rest_framework/form.html +++ b/rest_framework/templates/rest_framework/form.html @@ -9,7 +9,7 @@ <div class="well"> {% load rest_framework %} -<form {% if layout == "inline" %}class="form-inline"{% elif layout == "horizontal" %}class="form-horizontal"{% endif %} role="form" action="" method="POST"> +<form {% if layout == "inline" %}class="form-inline"{% elif layout == "horizontal" %}class="form-horizontal"{% endif %} role="form" action="." method="POST"> {% csrf_token %} {% for field, value, errors in form %} {% render_field field value errors layout=layout renderer=renderer %} From 79e91dff92443ab1f301638ac280bd3231a2ca15 Mon Sep 17 00:00:00 2001 From: Omer Katz <omer.drow@gmail.com> Date: Thu, 2 Oct 2014 16:44:20 +0300 Subject: [PATCH 117/249] The encoder now returns tuples instead of lists. Tuples take a little less memory which is significant when serializing a lot of objects. --- rest_framework/utils/encoders.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py index 7c4179a1f..486186c94 100644 --- a/rest_framework/utils/encoders.py +++ b/rest_framework/utils/encoders.py @@ -45,7 +45,7 @@ class JSONEncoder(json.JSONEncoder): # Serializers will coerce decimals to strings by default. return float(obj) elif isinstance(obj, QuerySet): - return list(obj) + return tuple(obj) elif hasattr(obj, 'tolist'): # Numpy arrays and array scalars. return obj.tolist() @@ -55,7 +55,7 @@ class JSONEncoder(json.JSONEncoder): except: pass elif hasattr(obj, '__iter__'): - return [item for item in obj] + return tuple(item for item in obj) return super(JSONEncoder, self).default(obj) From df7b6fcf58417fd95e49655eb140b387899b1ceb Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 2 Oct 2014 16:24:24 +0100 Subject: [PATCH 118/249] First pass on incorperating the form rendering into the browsable API --- rest_framework/fields.py | 8 +- rest_framework/relations.py | 4 +- rest_framework/renderers.py | 62 ++++---- rest_framework/serializers.py | 145 ++++++++++++------ .../rest_framework/css/bootstrap-tweaks.css | 18 ++- .../templates/rest_framework/base.html | 56 +++---- .../fields/horizontal/checkbox.html | 2 +- .../fields/horizontal/fieldset.html | 2 +- .../fields/horizontal/input.html | 2 +- .../fields/horizontal/select.html | 2 +- .../fields/horizontal/select_checkbox.html | 4 +- .../fields/horizontal/select_multiple.html | 2 +- .../fields/horizontal/select_radio.html | 4 +- .../fields/horizontal/textarea.html | 2 +- .../fields/inline/checkbox.html | 2 +- .../fields/inline/fieldset.html | 2 +- .../rest_framework/fields/inline/input.html | 2 +- .../rest_framework/fields/inline/select.html | 2 +- .../fields/inline/select_checkbox.html | 2 +- .../fields/inline/select_multiple.html | 2 +- .../fields/inline/select_radio.html | 2 +- .../fields/inline/textarea.html | 2 +- .../fields/vertical/fieldset.html | 2 +- .../rest_framework/fields/vertical/input.html | 2 +- .../fields/vertical/select.html | 2 +- .../fields/vertical/select_checkbox.html | 4 +- .../fields/vertical/select_multiple.html | 2 +- .../fields/vertical/select_radio.html | 4 +- .../fields/vertical/textarea.html | 2 +- .../templates/rest_framework/form.html | 14 +- rest_framework/templatetags/rest_framework.py | 7 +- rest_framework/utils/field_mapping.py | 9 +- 32 files changed, 225 insertions(+), 152 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index f3ff22334..c794963e1 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -689,10 +689,10 @@ class DateTimeField(Field): return value if self.format.lower() == ISO_8601: - ret = value.isoformat() - if ret.endswith('+00:00'): - ret = ret[:-6] + 'Z' - return ret + value = value.isoformat() + if value.endswith('+00:00'): + value = value[:-6] + 'Z' + return value return value.strftime(self.format) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 8c1356727..988b9ede4 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -127,7 +127,7 @@ class HyperlinkedRelatedField(RelatedField): attributes are not configured to correctly match the URL conf. """ # Unsaved objects will not yet have a valid URL. - if obj.pk is None: + if obj.pk: return None lookup_value = getattr(obj, self.lookup_field) @@ -248,11 +248,13 @@ class ManyRelation(Field): You shouldn't need to be using this class directly yourself. """ + initial = [] def __init__(self, child_relation=None, *args, **kwargs): self.child_relation = child_relation assert child_relation is not None, '`child_relation` is a required argument.' super(ManyRelation, self).__init__(*args, **kwargs) + self.child_relation.bind(field_name='', parent=self) def to_internal_value(self, data): return [ diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 297c60d8f..931dd434f 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -377,23 +377,21 @@ class HTMLFormRenderer(BaseRenderer): serializers.TimeField: 'time', }) - def render_field(self, field, value, errors, layout=None): + def render_field(self, field, layout=None): layout = layout or 'vertical' style_type = field.style.get('type', 'default') if style_type == 'textarea' and layout == 'inline': style_type = 'default' input_type = self.input_type[field] - if input_type == 'datetime-local': - value = value.rstrip('Z') + if input_type == 'datetime-local' and isinstance(field.value, six.text_type): + field.value = field.value.rstrip('Z') base = self.field_templates[field][style_type] template_name = 'rest_framework/fields/' + layout + '/' + base template = loader.get_template(template_name) context = Context({ 'field': field, - 'value': value, - 'errors': errors, 'input_type': input_type }) @@ -408,7 +406,7 @@ class HTMLFormRenderer(BaseRenderer): template = loader.get_template(self.template) context = RequestContext(request, { - 'form': data, + 'form': data.serializer, 'layout': getattr(getattr(data, 'Meta', None), 'layout', 'horizontal'), 'renderer': self }) @@ -479,27 +477,29 @@ class BrowsableAPIRenderer(BaseRenderer): return False # Doesn't have permissions return True - def get_rendered_html_form(self, view, method, request): + def get_rendered_html_form(self, data, view, method, request): """ Return a string representing a rendered HTML form, possibly bound to either the input or output data. In the absence of the View having an associated form then return None. """ + serializer = getattr(data, 'serializer', None) + if serializer and not getattr(serializer, 'many', False): + instance = getattr(serializer, 'instance', None) + else: + instance = None + if request.method == method: try: data = request.data - # files = request.FILES except ParseError: data = None - # files = None else: data = None - # files = None with override_method(view, request, method) as request: - obj = getattr(view, 'object', None) - if not self.show_form_for_method(view, method, request, obj): + if not self.show_form_for_method(view, method, request, instance): return if method in ('DELETE', 'OPTIONS'): @@ -511,19 +511,24 @@ class BrowsableAPIRenderer(BaseRenderer): ): return - serializer = view.get_serializer(instance=obj, data=data) - serializer.is_valid() - data = serializer.data - + serializer = view.get_serializer(instance=instance, data=data) + if data is not None: + serializer.is_valid() form_renderer = self.form_renderer_class() - return form_renderer.render(data, self.accepted_media_type, self.renderer_context) + return form_renderer.render(serializer.data, self.accepted_media_type, self.renderer_context) - def get_raw_data_form(self, view, method, request): + def get_raw_data_form(self, data, view, method, request): """ Returns a form that allows for arbitrary content types to be tunneled via standard HTML forms. (Which are typically application/x-www-form-urlencoded) """ + serializer = getattr(data, 'serializer', None) + if serializer and not getattr(serializer, 'many', False): + instance = getattr(serializer, 'instance', None) + else: + instance = None + with override_method(view, request, method) as request: # If we're not using content overloading there's no point in # supplying a generic form, as the view won't treat the form's @@ -533,8 +538,7 @@ class BrowsableAPIRenderer(BaseRenderer): return None # Check permissions - obj = getattr(view, 'object', None) - if not self.show_form_for_method(view, method, request, obj): + if not self.show_form_for_method(view, method, request, instance): return # If possible, serialize the initial content for the generic form @@ -545,8 +549,8 @@ class BrowsableAPIRenderer(BaseRenderer): # corresponding renderer that can be used to render the data. # Get a read-only version of the serializer - serializer = view.get_serializer(instance=obj) - if obj is None: + serializer = view.get_serializer(instance=instance) + if instance is None: for name, field in serializer.fields.items(): if getattr(field, 'read_only', None): del serializer.fields[name] @@ -606,9 +610,9 @@ class BrowsableAPIRenderer(BaseRenderer): renderer = self.get_default_renderer(view) - raw_data_post_form = self.get_raw_data_form(view, 'POST', request) - raw_data_put_form = self.get_raw_data_form(view, 'PUT', request) - raw_data_patch_form = self.get_raw_data_form(view, 'PATCH', request) + raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request) + raw_data_put_form = self.get_raw_data_form(data, view, 'PUT', request) + raw_data_patch_form = self.get_raw_data_form(data, view, 'PATCH', request) raw_data_put_or_patch_form = raw_data_put_form or raw_data_patch_form response_headers = dict(response.items()) @@ -632,10 +636,10 @@ class BrowsableAPIRenderer(BaseRenderer): 'available_formats': [renderer_cls.format for renderer_cls in view.renderer_classes], 'response_headers': response_headers, - # 'put_form': self.get_rendered_html_form(view, 'PUT', request), - # 'post_form': self.get_rendered_html_form(view, 'POST', request), - # 'delete_form': self.get_rendered_html_form(view, 'DELETE', request), - # 'options_form': self.get_rendered_html_form(view, 'OPTIONS', request), + 'put_form': self.get_rendered_html_form(data, view, 'PUT', request), + 'post_form': self.get_rendered_html_form(data, view, 'POST', request), + 'delete_form': self.get_rendered_html_form(data, view, 'DELETE', request), + 'options_form': self.get_rendered_html_form(data, view, 'OPTIONS', request), 'raw_data_put_form': raw_data_put_form, 'raw_data_post_form': raw_data_post_form, diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 5da812477..0f24ed402 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -14,7 +14,6 @@ from django.core.exceptions import ImproperlyConfigured, ValidationError from django.db import models from django.utils import six from django.utils.datastructures import SortedDict -from collections import namedtuple from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.settings import api_settings from rest_framework.utils import html, model_meta, representation @@ -38,8 +37,8 @@ from rest_framework.relations import * # NOQA from rest_framework.fields import * # NOQA -FieldResult = namedtuple('FieldResult', ['field', 'value', 'error']) - +# BaseSerializer +# -------------- class BaseSerializer(Field): """ @@ -113,11 +112,6 @@ class BaseSerializer(Field): if not hasattr(self, '_data'): if self.instance is not None: self._data = self.to_representation(self.instance) - elif self._initial_data is not None: - self._data = dict([ - (field_name, field.get_value(self._initial_data)) - for field_name, field in self.fields.items() - ]) else: self._data = self.get_initial() return self._data @@ -137,6 +131,79 @@ class BaseSerializer(Field): return self._validated_data +# Serializer & ListSerializer classes +# ----------------------------------- + +class ReturnDict(SortedDict): + """ + Return object from `serialier.data` for the `Serializer` class. + Includes a backlink to the serializer instance for renderers + to use if they need richer field information. + """ + def __init__(self, *args, **kwargs): + self.serializer = kwargs.pop('serializer') + super(ReturnDict, self).__init__(*args, **kwargs) + + +class ReturnList(list): + """ + Return object from `serialier.data` for the `SerializerList` class. + Includes a backlink to the serializer instance for renderers + to use if they need richer field information. + """ + def __init__(self, *args, **kwargs): + self.serializer = kwargs.pop('serializer') + super(ReturnList, self).__init__(*args, **kwargs) + + +class BoundField(object): + """ + A field object that also includes `.value` and `.error` properties. + Returned when iterating over a serializer instance, + providing an API similar to Django forms and form fields. + """ + def __init__(self, field, value, errors): + self._field = field + self.value = value + self.errors = errors + + def __getattr__(self, attr_name): + return getattr(self._field, attr_name) + + @property + def _proxy_class(self): + return self._field.__class__ + + +class BindingDict(object): + """ + This dict-like object is used to store fields on a serializer. + + This ensures that whenever fields are added to the serializer we call + `field.bind()` so that the `field_name` and `parent` attributes + can be set correctly. + """ + def __init__(self, serializer): + self.serializer = serializer + self.fields = SortedDict() + + def __setitem__(self, key, field): + self.fields[key] = field + field.bind(field_name=key, parent=self.serializer) + + def __getitem__(self, key): + return self.fields[key] + + def __delitem__(self, key): + del self.fields[key] + + def items(self): + return self.fields.items() + + def values(self): + return self.fields.values() + + class SerializerMetaclass(type): """ This metaclass sets a dictionary named `base_fields` on the class. @@ -167,35 +234,6 @@ class SerializerMetaclass(type): return super(SerializerMetaclass, cls).__new__(cls, name, bases, attrs) -class BindingDict(object): - """ - This dict-like object is used to store fields on a serializer. - - This ensures that whenever fields are added to the serializer we call - `field.bind()` so that the `field_name` and `parent` attributes - can be set correctly. - """ - def __init__(self, serializer): - self.serializer = serializer - self.fields = SortedDict() - - def __setitem__(self, key, field): - self.fields[key] = field - field.bind(field_name=key, parent=self.serializer) - - def __getitem__(self, key): - return self.fields[key] - - def __delitem__(self, key): - del self.fields[key] - - def items(self): - return self.fields.items() - - def values(self): - return self.fields.values() - - @six.add_metaclass(SerializerMetaclass) class Serializer(BaseSerializer): def __init__(self, *args, **kwargs): @@ -212,10 +250,18 @@ class Serializer(BaseSerializer): return copy.deepcopy(self._declared_fields) def get_initial(self): - return dict([ + if self._initial_data is not None: + return ReturnDict([ + (field_name, field.get_value(self._initial_data)) + for field_name, field in self.fields.items() + ], serializer=self) + #return self.to_representation(self._initial_data) + + return ReturnDict([ (field.field_name, field.get_initial()) for field in self.fields.values() - ]) + if not field.write_only + ], serializer=self) def get_value(self, dictionary): # We override the default field access in order to support @@ -288,7 +334,7 @@ class Serializer(BaseSerializer): """ Object instance -> Dict of primitive datatypes. """ - ret = SortedDict() + ret = ReturnDict(serializer=self) fields = [field for field in self.fields.values() if not field.write_only] for field in fields: @@ -302,11 +348,9 @@ class Serializer(BaseSerializer): def __iter__(self): errors = self.errors if hasattr(self, '_errors') else {} for field in self.fields.values(): - if field.read_only: - continue value = self.data.get(field.field_name) if self.data else None error = errors.get(field.field_name) - yield FieldResult(field, value, error) + yield BoundField(field, value, error) def __repr__(self): return representation.serializer_repr(self, indent=1) @@ -317,7 +361,7 @@ class Serializer(BaseSerializer): class ListSerializer(BaseSerializer): child = None - initial = [] + many = True def __init__(self, *args, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) @@ -326,6 +370,11 @@ class ListSerializer(BaseSerializer): super(ListSerializer, self).__init__(*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) + return ReturnList(serializer=self) + def get_value(self, dictionary): # We override the default field access in order to support # lists in HTML forms. @@ -345,7 +394,10 @@ class ListSerializer(BaseSerializer): """ List of object instances -> List of dicts of primitive datatypes. """ - return [self.child.to_representation(item) for item in data] + return ReturnList( + [self.child.to_representation(item) for item in data], + serializer=self + ) def create(self, attrs_list): return [self.child.create(attrs) for attrs in attrs_list] @@ -354,6 +406,9 @@ class ListSerializer(BaseSerializer): return representation.list_repr(self, indent=1) +# ModelSerializer & HyperlinkedModelSerializer +# -------------------------------------------- + class ModelSerializer(Serializer): _field_mapping = ClassLookupDict({ models.AutoField: IntegerField, diff --git a/rest_framework/static/rest_framework/css/bootstrap-tweaks.css b/rest_framework/static/rest_framework/css/bootstrap-tweaks.css index 6fa1e6cb5..84389b1d1 100644 --- a/rest_framework/static/rest_framework/css/bootstrap-tweaks.css +++ b/rest_framework/static/rest_framework/css/bootstrap-tweaks.css @@ -10,6 +10,12 @@ a single block in the template. background: transparent; border-top-color: transparent; padding-top: 0; + text-align: right; +} + +#generic-content-form textarea { + font-family:Consolas,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New, monospace; + font-size: 80%; } .navbar-inverse .brand a { @@ -29,7 +35,7 @@ a single block in the template. z-index: 3; } -.navbar .navbar-inner { +.navbar { background: #2C2C2C; color: white; border: none; @@ -37,7 +43,7 @@ a single block in the template. border-radius: 0px; } -.navbar .navbar-inner .nav li, .navbar .navbar-inner .nav li a, .navbar .navbar-inner .brand:hover { +.navbar .nav li, .navbar .nav li a, .navbar .brand:hover { color: white; } @@ -45,11 +51,11 @@ a single block in the template. background: #2C2C2C; } -.navbar .navbar-inner .dropdown-menu li a, .navbar .navbar-inner .dropdown-menu li { +.navbar .dropdown-menu li a, .navbar .dropdown-menu li { color: #A30000; } -.navbar .navbar-inner .dropdown-menu li a:hover { +.navbar .dropdown-menu li a:hover { background: #EEEEEE; color: #C20000; } @@ -61,10 +67,10 @@ html { background: none; } -body, .navbar .navbar-inner .container-fluid { +/*body, .navbar .container-fluid { max-width: 1150px; margin: 0 auto; -} +}*/ body { background: url("../img/grid.png") repeat-x; diff --git a/rest_framework/templates/rest_framework/base.html b/rest_framework/templates/rest_framework/base.html index a84ccf269..2e03dd987 100644 --- a/rest_framework/templates/rest_framework/base.html +++ b/rest_framework/templates/rest_framework/base.html @@ -15,7 +15,8 @@ {% block style %} {% block bootstrap_theme %} - <link rel="stylesheet" type="text/css" href="{% static "rest_framework/css/bootstrap.min.css" %}"/> + <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> + <!--<link rel="stylesheet" type="text/css" href="{% static "rest_framework/css/bootstrap.min.css" %}"/>--> <link rel="stylesheet" type="text/css" href="{% static "rest_framework/css/bootstrap-tweaks.css" %}"/> {% endblock %} <link rel="stylesheet" type="text/css" href="{% static "rest_framework/css/prettify.css" %}"/> @@ -26,44 +27,42 @@ </head> {% block body %} - <body class="{% block bodyclass %}{% endblock %} container"> + <body class="{% block bodyclass %}{% endblock %}"> <div class="wrapper"> {% block navbar %} - <div class="navbar {% block bootstrap_navbar_variant %}navbar-inverse{% endblock %}"> - <div class="navbar-inner"> - <div class="container-fluid"> - <span> - {% block branding %} - <a class='brand' rel="nofollow" href='http://www.django-rest-framework.org'> - Django REST framework <span class="version">{{ version }}</span> - </a> - {% endblock %} - </span> - <ul class="nav pull-right"> - {% block userlinks %} - {% if user.is_authenticated %} - {% optional_logout request user %} - {% else %} - {% optional_login request %} - {% endif %} - {% endblock %} - </ul> - </div> + <div class="navbar navbar-static-top {% block bootstrap_navbar_variant %}navbar-inverse{% endblock %}"> + <div class="container"> + <span> + {% block branding %} + <a class='navbar-brand' rel="nofollow" href='http://www.django-rest-framework.org'> + Django REST framework <span class="version">{{ version }}</span> + </a> + {% endblock %} + </span> + <ul class="nav navbar-nav pull-right"> + {% block userlinks %} + {% if user.is_authenticated %} + {% optional_logout request user %} + {% else %} + {% optional_login request %} + {% endif %} + {% endblock %} + </ul> </div> </div> {% endblock %} + <div class="container"> {% block breadcrumbs %} <ul class="breadcrumb"> {% for breadcrumb_name, breadcrumb_url in breadcrumblist %} - <li> - <a href="{{ breadcrumb_url }}" {% if forloop.last %}class="active"{% endif %}> - {{ breadcrumb_name }} - </a> - {% if not forloop.last %}<span class="divider">›</span>{% endif %} - </li> + {% if forloop.last %} + <li class="active">{{ breadcrumb_name }}</li> + {% else %} + <li><a href="{{ breadcrumb_url }}">{{ breadcrumb_name }}</a></li> + {% endif %} {% endfor %} </ul> {% endblock %} @@ -238,6 +237,7 @@ {% endif %} </div> <!-- END Content --> + </div><!-- /.container --> <footer> {% block footer %} diff --git a/rest_framework/templates/rest_framework/fields/horizontal/checkbox.html b/rest_framework/templates/rest_framework/fields/horizontal/checkbox.html index dce4a5cf9..dd3c3cef1 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/checkbox.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/checkbox.html @@ -2,7 +2,7 @@ <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> - <input type="checkbox" name="{{ field.field_name }}" value="true" {% if value %}checked{% endif %}> + <input type="checkbox" name="{{ field.field_name }}" value="true" {% if field.value %}checked{% endif %}> {% if field.label %}{{ field.label }}{% endif %} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/fieldset.html b/rest_framework/templates/rest_framework/fields/horizontal/fieldset.html index 86417633f..843a56b29 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/fieldset.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/fieldset.html @@ -4,7 +4,7 @@ <legend class="control-label col-sm-2 {% if field.style.hide_label %}sr-only{% endif %}" style="border-bottom: 0">{{ field.label }}</legend> </div> {% endif %} - {% for field_item in value.field_items.values() %} + {% for field_item in field.value.field_items.values() %} {{ renderer.render_field(field_item, layout=layout) }} {% endfor %} </fieldset> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/input.html b/rest_framework/templates/rest_framework/fields/horizontal/input.html index 310154bb4..6f1a504b5 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/input.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/input.html @@ -1,7 +1,7 @@ <div class="form-group"> {% include "rest_framework/fields/horizontal/label.html" %} <div class="col-sm-10"> - <input type="{{ input_type }}" class="form-control" {% include "rest_framework/fields/attrs.html" %} {% if value %}value="{{ value }}"{% endif %}> + <input type="{{ input_type }}" class="form-control" {% include "rest_framework/fields/attrs.html" %} {% if field.value %}value="{{ field.value }}"{% endif %}> {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} </div> </div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select.html b/rest_framework/templates/rest_framework/fields/horizontal/select.html index 3f8cab0a3..7367d7269 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/select.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/select.html @@ -3,7 +3,7 @@ <div class="col-sm-10"> <select class="form-control" name="{{ field.field_name }}"> {% for key, text in field.choices.items %} - <option value="{{ key }}" {% if key == value %}selected{% endif %}>{{ text }}</option> + <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} </select> </div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html b/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html index 659eede84..381cda2cb 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html @@ -4,7 +4,7 @@ {% if field.style.inline %} {% for key, text in field.choices.items %} <label class="checkbox-inline"> - <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in value %}checked{% endif %}> + <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> {{ text }} </label> {% endfor %} @@ -12,7 +12,7 @@ {% for key, text in field.choices.items %} <div class="checkbox"> <label> - <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in value %}checked{% endif %}> + <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> {{ text }} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html b/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html index da25eb2bd..29ba86610 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html @@ -3,7 +3,7 @@ <div class="col-sm-10"> <select multiple class="form-control" name="{{ field.field_name }}"> {% for key, text in field.choices.items %} - <option value="{{ key }}" {% if key in value %}selected{% endif %}>{{ text }}</option> + <option value="{{ key }}" {% if key in field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} </select> </div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html b/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html index 188f05e27..20aab8b22 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html @@ -4,7 +4,7 @@ {% if field.style.inline %} {% for key, text in field.choices.items %} <label class="radio-inline"> - <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == value %}checked{% endif %}> + <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> {{ text }} </label> {% endfor %} @@ -12,7 +12,7 @@ {% for key, text in field.choices.items %} <div class="radio"> <label> - <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == value %}checked{% endif %}> + <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> {{ text }} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/textarea.html b/rest_framework/templates/rest_framework/fields/horizontal/textarea.html index e99266f37..3d0161950 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/textarea.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/textarea.html @@ -1,7 +1,7 @@ <div class="form-group"> {% include "rest_framework/fields/horizontal/label.html" %} <div class="col-sm-10"> - <textarea class="form-control" {% include "rest_framework/fields/attrs.html" %}>{% if value %}{{ value }}{% endif %}</textarea> + <textarea class="form-control" {% include "rest_framework/fields/attrs.html" %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} </div> </div> diff --git a/rest_framework/templates/rest_framework/fields/inline/checkbox.html b/rest_framework/templates/rest_framework/fields/inline/checkbox.html index 01d30aaef..289bbb4d8 100644 --- a/rest_framework/templates/rest_framework/fields/inline/checkbox.html +++ b/rest_framework/templates/rest_framework/fields/inline/checkbox.html @@ -1,6 +1,6 @@ <div class="checkbox"> <label> - <input type="checkbox" name="{{ field.field_name }}" value="true" {% if value %}checked{% endif %}> + <input type="checkbox" name="{{ field.field_name }}" value="true" {% if field.value %}checked{% endif %}> {% if field.label %}{{ field.label }}{% endif %} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/inline/fieldset.html b/rest_framework/templates/rest_framework/fields/inline/fieldset.html index d22982fdd..380d46272 100644 --- a/rest_framework/templates/rest_framework/fields/inline/fieldset.html +++ b/rest_framework/templates/rest_framework/fields/inline/fieldset.html @@ -1,3 +1,3 @@ -{% for field_item in value.field_items.values() %} +{% for field_item in field.value.field_items.values() %} {{ renderer.render_field(field_item, layout=layout) }} {% endfor %} diff --git a/rest_framework/templates/rest_framework/fields/inline/input.html b/rest_framework/templates/rest_framework/fields/inline/input.html index aefd16723..e4a92ccd1 100644 --- a/rest_framework/templates/rest_framework/fields/inline/input.html +++ b/rest_framework/templates/rest_framework/fields/inline/input.html @@ -1,4 +1,4 @@ <div class="form-group"> {% include "rest_framework/fields/inline/label.html" %} - <input type="{{ input_type }}" class="form-control" {% include "rest_framework/fields/attrs.html" %} {% if value %}value="{{ value }}"{% endif %}> + <input type="{{ input_type }}" class="form-control" {% include "rest_framework/fields/attrs.html" %} {% if field.value %}value="{{ field.value }}"{% endif %}> </div> diff --git a/rest_framework/templates/rest_framework/fields/inline/select.html b/rest_framework/templates/rest_framework/fields/inline/select.html index cb9a70137..9f361c4a0 100644 --- a/rest_framework/templates/rest_framework/fields/inline/select.html +++ b/rest_framework/templates/rest_framework/fields/inline/select.html @@ -2,7 +2,7 @@ {% include "rest_framework/fields/inline/label.html" %} <select class="form-control" name="{{ field.field_name }}"> {% for key, text in field.choices.items %} - <option value="{{ key }}" {% if key == value %}selected{% endif %}>{{ text }}</option> + <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} </select> </div> diff --git a/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html b/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html index 424df93e6..0f33fb692 100644 --- a/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html +++ b/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html @@ -3,7 +3,7 @@ {% for key, text in field.choices.items %} <div class="checkbox"> <label> - <input type="checkbox" name="{{ rest_framework/field.field_name }}" value="{{ key }}" {% if key in value %}checked{% endif %}> + <input type="checkbox" name="{{ rest_framework/field.field_name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> {{ text }} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/inline/select_multiple.html b/rest_framework/templates/rest_framework/fields/inline/select_multiple.html index 6fdfd672f..7c9e51684 100644 --- a/rest_framework/templates/rest_framework/fields/inline/select_multiple.html +++ b/rest_framework/templates/rest_framework/fields/inline/select_multiple.html @@ -2,7 +2,7 @@ {% include "rest_framework/fields/inline/label.html" %} <select multiple class="form-control" name="{{ field.field_name }}"> {% for key, text in field.choices.items %} - <option value="{{ key }}" {% if key in value %}selected{% endif %}>{{ text }}</option> + <option value="{{ key }}" {% if key in field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} </select> </div> diff --git a/rest_framework/templates/rest_framework/fields/inline/select_radio.html b/rest_framework/templates/rest_framework/fields/inline/select_radio.html index ddabc9e96..177c0eeba 100644 --- a/rest_framework/templates/rest_framework/fields/inline/select_radio.html +++ b/rest_framework/templates/rest_framework/fields/inline/select_radio.html @@ -3,7 +3,7 @@ {% for key, text in field.choices.items %} <div class="radio"> <label> - <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == value %}checked{% endif %}> + <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> {{ text }} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/inline/textarea.html b/rest_framework/templates/rest_framework/fields/inline/textarea.html index 313668098..8259487b3 100644 --- a/rest_framework/templates/rest_framework/fields/inline/textarea.html +++ b/rest_framework/templates/rest_framework/fields/inline/textarea.html @@ -1,4 +1,4 @@ <div class="form-group"> {% include "rest_framework/fields/inline/label.html" %} - <textarea class="form-control" {% include "rest_framework/fields/attrs.html" %}>{% if value %}{{ value }}{% endif %}</textarea> + <textarea class="form-control" {% include "rest_framework/fields/attrs.html" %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> </div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/fieldset.html b/rest_framework/templates/rest_framework/fields/vertical/fieldset.html index cad32df99..8708916bd 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/fieldset.html +++ b/rest_framework/templates/rest_framework/fields/vertical/fieldset.html @@ -1,6 +1,6 @@ <fieldset> {% if field.label %}<legend {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %} - {% for field_item in value.field_items.values() %} + {% for field_item in field.value.field_items.values() %} {{ renderer.render_field(field_item, layout=layout) }} {% endfor %} </fieldset> diff --git a/rest_framework/templates/rest_framework/fields/vertical/input.html b/rest_framework/templates/rest_framework/fields/vertical/input.html index c25407d16..3ee2716af 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/input.html +++ b/rest_framework/templates/rest_framework/fields/vertical/input.html @@ -1,5 +1,5 @@ <div class="form-group"> {% include "rest_framework/fields/vertical/label.html" %} - <input type="{{ input_type }}" class="form-control" {% include "rest_framework/fields/attrs.html" %} {% if value %}value="{{ value }}"{% endif %}> + <input type="{{ input_type }}" class="form-control" {% include "rest_framework/fields/attrs.html" %} {% if field.value %}value="{{ field.value }}"{% endif %}> {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} </div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/select.html b/rest_framework/templates/rest_framework/fields/vertical/select.html index 44679d8a4..dcc9a3cd9 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/select.html +++ b/rest_framework/templates/rest_framework/fields/vertical/select.html @@ -2,7 +2,7 @@ {% include "rest_framework/fields/vertical/label.html" %} <select class="form-control" name="{{ field.field_name }}"> {% for key, text in field.choices.items %} - <option value="{{ key }}" {% if key == value %}selected{% endif %}>{{ text }}</option> + <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} </select> </div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html b/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html index e60574c07..1fbe6a940 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html +++ b/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html @@ -4,7 +4,7 @@ <div> {% for key, text in field.choices.items %} <label class="checkbox-inline"> - <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in value %}checked{% endif %}> + <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> {{ text }} </label> {% endfor %} @@ -13,7 +13,7 @@ {% for key, text in field.choices.items %} <div class="checkbox"> <label> - <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in value %}checked{% endif %}> + <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> {{ text }} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html b/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html index 00b25b4b1..2cc40d99e 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html +++ b/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html @@ -2,7 +2,7 @@ {% include "rest_framework/fields/vertical/label.html" %} <select multiple class="form-control" name="{{ field.field_name }}"> {% for key, text in field.choices.items %} - <option value="{{ key }}" {% if key in value %}selected{% endif %}>{{ text }}</option> + <option value="{{ key }}" {% if key in field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} </select> </div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_radio.html b/rest_framework/templates/rest_framework/fields/vertical/select_radio.html index 4ffe38ea9..470bcb0b0 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/select_radio.html +++ b/rest_framework/templates/rest_framework/fields/vertical/select_radio.html @@ -4,7 +4,7 @@ <div> {% for key, text in field.choices.items %} <label class="radio-inline"> - <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key|string==value|string %}checked{% endif %}> + <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> {{ text }} </label> {% endfor %} @@ -13,7 +13,7 @@ {% for key, text in field.choices.items %} <div class="radio"> <label> - <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key|string==value|string %}checked{% endif %}> + <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> {{ text }} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/textarea.html b/rest_framework/templates/rest_framework/fields/vertical/textarea.html index 33cb27c75..406cfa77d 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/textarea.html +++ b/rest_framework/templates/rest_framework/fields/vertical/textarea.html @@ -1,5 +1,5 @@ <div class="form-group"> {% include "rest_framework/fields/vertical/label.html" %} - <textarea class="form-control" {% include "rest_framework/fields/attrs.html" %}>{% if value %}{{ value }}{% endif %}</textarea> + <textarea class="form-control" {% include "rest_framework/fields/attrs.html" %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} </div> diff --git a/rest_framework/templates/rest_framework/form.html b/rest_framework/templates/rest_framework/form.html index 658aa2934..162c56336 100644 --- a/rest_framework/templates/rest_framework/form.html +++ b/rest_framework/templates/rest_framework/form.html @@ -1,4 +1,4 @@ -<html> +<!-- <html> <head> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> </head> @@ -6,13 +6,15 @@ <div class="container"> <h1>User update</h1> -<div class="well"> +<div class="well"> --> {% load rest_framework %} <form {% if layout == "inline" %}class="form-inline"{% elif layout == "horizontal" %}class="form-horizontal"{% endif %} role="form" action="." method="POST"> {% csrf_token %} - {% for field, value, errors in form %} - {% render_field field value errors layout=layout renderer=renderer %} + {% for field in form %} + {% if not field.read_only %} + {% render_field field layout=layout renderer=renderer %} + {% endif %} {% endfor %} <!-- form.non_field_errors --> {% if layout == "horizontal" %} @@ -25,7 +27,7 @@ <button type="submit" class="btn btn-default">Submit</button> {% endif %} </form> - +<!-- </div> </div></body> -</html> +</html> --> diff --git a/rest_framework/templatetags/rest_framework.py b/rest_framework/templatetags/rest_framework.py index 88ff9d4ed..49a4c3389 100644 --- a/rest_framework/templatetags/rest_framework.py +++ b/rest_framework/templatetags/rest_framework.py @@ -31,12 +31,9 @@ class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])') # And the template tags themselves... -# @register.simple_tag -# def render_field(field, value, errors, renderer): -# return renderer.render_field(field, value, errors) @register.simple_tag -def render_field(field, value, errors, layout=None, renderer=None): - return renderer.render_field(field, value, errors, layout) +def render_field(field, layout=None, renderer=None): + return renderer.render_field(field, layout) @register.simple_tag diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index b4d33e395..30fae3709 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -21,7 +21,14 @@ class ClassLookupDict(object): self.mapping = mapping def __getitem__(self, key): - for cls in inspect.getmro(key.__class__): + if hasattr(key, '_proxy_class'): + # Deal with proxy classes. Ie. BoundField behaves as if it + # is a Field instance when using ClassLookupDict. + base_class = key._proxy_class + else: + base_class = key.__class__ + + for cls in inspect.getmro(base_class): if cls in self.mapping: return self.mapping[cls] raise KeyError('Class %s not found in lookup.', cls.__name__) From fec7c4b45812d22423e73ec3ab801857a55d7340 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 2 Oct 2014 18:13:15 +0100 Subject: [PATCH 119/249] Browsable API tweaks --- rest_framework/fields.py | 5 ++--- rest_framework/relations.py | 1 + rest_framework/serializers.py | 1 + .../static/rest_framework/css/bootstrap-tweaks.css | 2 +- rest_framework/static/rest_framework/css/default.css | 3 +-- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index c794963e1..3f22660cc 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -106,7 +106,7 @@ class Field(object): 'null': _('This field may not be null.') } default_validators = [] - default_empty_html = None + default_empty_html = empty initial = None def __init__(self, read_only=False, write_only=False, @@ -375,7 +375,6 @@ class NullBooleanField(Field): default_error_messages = { 'invalid': _('`{input}` is not a valid boolean.') } - default_empty_html = None initial = None TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True)) FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False)) @@ -411,7 +410,6 @@ class CharField(Field): default_error_messages = { 'blank': _('This field may not be blank.') } - default_empty_html = '' initial = '' def __init__(self, **kwargs): @@ -852,6 +850,7 @@ class MultipleChoiceField(ChoiceField): 'invalid_choice': _('`{input}` is not a valid choice.'), 'not_a_list': _('Expected a list of items but got type `{input_type}`') } + default_empty_html = [] def to_internal_value(self, data): if isinstance(data, type('')) or not hasattr(data, '__iter__'): diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 988b9ede4..4f971917a 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -249,6 +249,7 @@ class ManyRelation(Field): You shouldn't need to be using this class directly yourself. """ initial = [] + default_empty_html = [] def __init__(self, child_relation=None, *args, **kwargs): self.child_relation = child_relation diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 0f24ed402..21cb7ea27 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -254,6 +254,7 @@ class Serializer(BaseSerializer): return ReturnDict([ (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 ], serializer=self) #return self.to_representation(self._initial_data) diff --git a/rest_framework/static/rest_framework/css/bootstrap-tweaks.css b/rest_framework/static/rest_framework/css/bootstrap-tweaks.css index 84389b1d1..6a37cae23 100644 --- a/rest_framework/static/rest_framework/css/bootstrap-tweaks.css +++ b/rest_framework/static/rest_framework/css/bootstrap-tweaks.css @@ -173,7 +173,7 @@ footer a:hover { .page-header { border-bottom: none; padding-bottom: 0px; - margin-bottom: 20px; + margin: 0; } /* custom general page styles */ diff --git a/rest_framework/static/rest_framework/css/default.css b/rest_framework/static/rest_framework/css/default.css index 461cdfe5c..82c6033b6 100644 --- a/rest_framework/static/rest_framework/css/default.css +++ b/rest_framework/static/rest_framework/css/default.css @@ -33,7 +33,7 @@ h2, h3 { } ul.breadcrumb { - margin: 80px 0 0 0; + margin: 70px 0 0 0; } form select, form input, form textarea { @@ -67,5 +67,4 @@ pre { .page-header { border-bottom: none; padding-bottom: 0px; - margin-bottom: 20px; } From dfab9af294972720f59890967cd9ae1a6c0796b6 Mon Sep 17 00:00:00 2001 From: Craig de Stigter <craig.destigter@koordinates.com> Date: Fri, 3 Oct 2014 08:41:18 +1300 Subject: [PATCH 120/249] Minor: fix spelling and grammar, mostly in 3.0 announcement --- CONTRIBUTING.md | 2 +- docs/api-guide/fields.md | 2 +- docs/api-guide/renderers.md | 2 +- docs/topics/2.4-announcement.md | 2 +- docs/topics/3.0-announcement.md | 42 +++++++++++----------- docs/topics/contributing.md | 2 +- docs/topics/release-notes.md | 2 +- docs/topics/writable-nested-serializers.md | 2 +- rest_framework/compat.py | 2 +- rest_framework/fields.py | 12 +++---- rest_framework/relations.py | 2 +- rest_framework/validators.py | 2 +- rest_framework/views.py | 2 +- tests/test_model_serializer.py | 4 +-- tests/test_relations.py | 12 +++---- 15 files changed, 46 insertions(+), 46 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a6dd05a0e..1b1995348 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -75,7 +75,7 @@ You can also use the excellent [`tox`][tox] testing tool to run the tests agains It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission. -It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another seperate issue without interfering with an ongoing pull requests. +It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests. It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests. diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index f07783186..292a51d89 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -286,7 +286,7 @@ For example, to validate numbers up to 999 with a resolution of 2 decimal places serializers.DecimalField(max_digits=5, decimal_places=2) -And to validate numbers up to anything lesss than one billion with a resolution of 10 decimal places: +And to validate numbers up to anything less than one billion with a resolution of 10 decimal places: serializers.DecimalField(max_digits=19, decimal_places=10) diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 2e1c892fd..db7436c23 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -74,7 +74,7 @@ If your API includes views that can serve both regular webpages and API response Renders the request data into `JSON`, using utf-8 encoding. -Note that the default style is to include unicode characters, and render the response using a compact style with no uneccessary whitespace: +Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace: {"unicode black star":"★","value":999} diff --git a/docs/topics/2.4-announcement.md b/docs/topics/2.4-announcement.md index 09294b910..d8aa5b108 100644 --- a/docs/topics/2.4-announcement.md +++ b/docs/topics/2.4-announcement.md @@ -23,7 +23,7 @@ The documentation has previously stated that usage of the more explicit style is Doing so will mean that there are cases of API code where you'll now need to include a serializer class where you previously were just using the `.model` shortcut. However we firmly believe that it is the right trade-off to make. -Removing the shortcut takes away an unneccessary layer of abstraction, and makes your codebase more explicit without any significant extra complexity. It also results in better consistency, as there's now only one way to set the serializer class and queryset attributes for the view, instead of two. +Removing the shortcut takes away an unnecessary layer of abstraction, and makes your codebase more explicit without any significant extra complexity. It also results in better consistency, as there's now only one way to set the serializer class and queryset attributes for the view, instead of two. The `DEFAULT_MODEL_SERIALIZER_CLASS` API setting is now also deprecated. diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index d2505a1b3..5242be573 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -6,10 +6,10 @@ The 3.0 release is now ready for some tentative testing and upgrades for super k See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-framework/pull/1800) for more details on remaining work. -The most notable outstanding issues still to resolved on the `version-3.0` branch are as follows: +The most notable outstanding issues still to be resolved on the `version-3.0` branch are as follows: * Forms support for serializers and in the browsable API. -* Optimisations for serialializing primary keys. +* Optimisations for serializing primary keys. * Refine style of validation errors in some cases, such as validation errors in `ListField`. * `.transform_<field>()` method on serializers. @@ -50,13 +50,13 @@ Below is an in-depth guide to the API changes and migration notes for 3.0. The usage of `request.DATA` and `request.FILES` is now discouraged in favor of a single `request.data` attribute that contains *all* the parsed data. -Having seperate attributes is reasonable for web applications that only ever parse URL encoded or MultiPart requests, but makes less sense for the general-purpose request parsing that REST framework supports. +Having separate attributes is reasonable for web applications that only ever parse URL encoded or MultiPart requests, but makes less sense for the general-purpose request parsing that REST framework supports. You may now pass all the request data to a serializer class in a single argument: ExampleSerializer(data=request.data) -Instead of passing the files argument seperately: +Instead of passing the files argument separately: # Don't do this... ExampleSerializer(data=request.DATA, files=request.FILES) @@ -75,7 +75,7 @@ Previously the serializers used a two-step object creation, as follows: This style is in line with how the `ModelForm` class works in Django, but is problematic for a number of reasons: -* Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumentated state on the object instance, or kept as state on the serializer instance so that it could be used when `.save()` is called. +* Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumented state on the object instance, or kept as state on the serializer instance so that it could be used when `.save()` is called. * Instantiating model instances directly means that you cannot use model manager classes for instance creation, eg `ExampleModel.objects.create(...)`. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints. * The two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save? @@ -88,7 +88,7 @@ The resulting API changes are further detailed below. #### The `.create()` and `.update()` methods. -The `.restore_object()` method is now replaced with two seperate methods, `.create()` and `.update()`. +The `.restore_object()` method is now replaced with two separate methods, `.create()` and `.update()`. When using the `.create()` and `.update()` methods you should both create *and save* the object instance. This is in contrast to the previous `.restore_object()` behavior that would instantiate the object but not save it. @@ -107,7 +107,7 @@ The following example from the tutorial previously used `restore_object()` to ha # Create new instance return Snippet(**attrs) -This would now be split out into two seperate methods. +This would now be split out into two separate methods. def update(self, instance, validated_attrs) instance.title = validated_attrs.get('title', instance.title) @@ -146,7 +146,7 @@ The corresponding code would now look like this: #### Limitations of ModelSerializer validation. -This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner seperation, and ensures that there's no automatic validation behavior on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes. +This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes. This change comes with the following limitations: @@ -157,7 +157,7 @@ This change comes with the following limitations: REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic: -* There can be complex dependancies involved in order of saving multiple related model instances. +* There can be complex dependencies involved in order of saving multiple related model instances. * It's unclear what behavior the user should expect when related models are passed `None` data. * It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records. @@ -289,7 +289,7 @@ The `ListSerializer` class has now been added, and allows you to create base ser class MultipleUserSerializer(ListSerializer): child = UserSerializer() -You can also still use the `many=True` argument to serializer classes. It's worth noting that `many=True` argument transparently creates a `ListSerializer` instance, allowing the validation logic for list and non-list data to be cleanly seperated in the REST framework codebase. +You can also still use the `many=True` argument to serializer classes. It's worth noting that `many=True` argument transparently creates a `ListSerializer` instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase. See also the new `ListField` class, which validates input in the same way, but does not include the serializer interfaces of `.is_valid()`, `.data`, `.save()` and so on. @@ -299,7 +299,7 @@ REST framework now includes a simple `BaseSerializer` class that can be used to This class implements the same basic API as the `Serializer` class: -* `.data` - Returns the outgoing primative representation. +* `.data` - Returns the outgoing primitive representation. * `.is_valid()` - Deserializes and validates incoming data. * `.validated_data` - Returns the validated incoming data. * `.errors` - Returns an errors during validation. @@ -320,7 +320,7 @@ To implement a read-only serializer using the `BaseSerializer` class, we just ne player_name = models.CharField(max_length=10) score = models.IntegerField() -It's simple to create a read-only serializer for converting `HighScore` instances into primative data types. +It's simple to create a read-only serializer for converting `HighScore` instances into primitive data types. class HighScoreSerializer(serializers.BaseSerializer): def to_representation(self, obj): @@ -394,12 +394,12 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends. -The following class is an example of a generic serializer that can handle coercing aribitrary objects into primative representations. +The following class is an example of a generic serializer that can handle coercing aribitrary objects into primitive representations. class ObjectSerializer(serializers.BaseSerializer): """ A read-only serializer that coerces arbitrary complex objects - into primative representations. + into primitive representations. """ def to_representation(self, obj): for attribute_name in dir(obj): @@ -411,7 +411,7 @@ The following class is an example of a generic serializer that can handle coerci # Ignore methods and other callables. pass elif isinstance(attribute, (str, int, bool, float, type(None))): - # Primative types can be passed through unmodified. + # primitive types can be passed through unmodified. output[attribute_name] = attribute elif isinstance(attribute, list): # Recursivly deal with items in lists. @@ -437,7 +437,7 @@ There are some minor tweaks to the field base classes. Previously we had these two base classes: * `Field` as the base class for read-only fields. A default implementation was included for serializing data. -* `WriteableField` as the base class for read-write fields. +* `WritableField` as the base class for read-write fields. We now use the following: @@ -448,9 +448,9 @@ We now use the following: REST framework now has more explict and clear control over validating empty values for fields. -Previously the meaning of the `required=False` keyword argument was underspecified. In practice it's use meant that a field could either be not included in the input, or it could be included, but be `None`. +Previously the meaning of the `required=False` keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be `None`. -We now have a better seperation, with seperate `required` and `allow_none` arguments. +We now have a better separation, with separate `required` and `allow_none` arguments. The following set of arguments are used to control validation of empty values: @@ -552,7 +552,7 @@ In order to ensure a consistent code style an assertion error will be raised if #### Enforcing consistent `source` usage. -I've see several codebases that unneccessarily include the `source` argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that `source` is usually not required. +I've see several codebases that unnecessarily include the `source` argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that `source` is usually not required. The following usage will *now raise an error*: @@ -614,7 +614,7 @@ I would personally recommend that developers treat view instances as immutable o #### PUT as create. -Allowing `PUT` as create operations is problematic, as it neccessarily exposes information about the existence or non-existance of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is neccessarily a better default behavior than simply returning `404` responses. +Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existance of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses. Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but we've now opted for the 404 behavior as the default, due to it being simpler and more obvious. @@ -628,7 +628,7 @@ This change means that you can now easily cusomize the style of error responses ## The metadata API -Behavior for dealing with `OPTIONS` requests was previously built directly into the class based views. This has now been properly seperated out into a Metadata API that allows the same pluggable style as other API policies in REST framework. +Behavior for dealing with `OPTIONS` requests was previously built directly into the class based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework. This makes it far easier to use a different style for `OPTIONS` responses throughout your API, and makes it possible to create third-party metadata policies. diff --git a/docs/topics/contributing.md b/docs/topics/contributing.md index 3400bc8f9..50b8ded16 100644 --- a/docs/topics/contributing.md +++ b/docs/topics/contributing.md @@ -109,7 +109,7 @@ You can also use the excellent [tox][tox] testing tool to run the tests against It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission. -It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another seperate issue without interfering with an ongoing pull requests. +It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests. It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests. diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md index 16589f3b9..4fa3d6271 100644 --- a/docs/topics/release-notes.md +++ b/docs/topics/release-notes.md @@ -149,7 +149,7 @@ You can determine your currently installed version using `pip freeze`: * Added `write_only_fields` option to `ModelSerializer` classes. * JSON renderer now deals with objects that implement a dict-like interface. * Fix compatiblity with newer versions of `django-oauth-plus`. -* Bugfix: Refine behavior that calls model manager `all()` across nested serializer relationships, preventing erronous behavior with some non-ORM objects, and preventing unneccessary queryset re-evaluations. +* Bugfix: Refine behavior that calls model manager `all()` across nested serializer relationships, preventing erronous behavior with some non-ORM objects, and preventing unnecessary queryset re-evaluations. * Bugfix: Allow defaults on BooleanFields to be properly honored when values are not supplied. * Bugfix: Prevent double-escaping of non-latin1 URL query params when appending `format=json` params. diff --git a/docs/topics/writable-nested-serializers.md b/docs/topics/writable-nested-serializers.md index 66ea78150..abc6a82f7 100644 --- a/docs/topics/writable-nested-serializers.md +++ b/docs/topics/writable-nested-serializers.md @@ -6,7 +6,7 @@ Although flat data structures serve to properly delineate between the individual entities in your service, there are cases where it may be more appropriate or convenient to use nested data structures. -Nested data structures are easy enough to work with if they're read-only - simply nest your serializer classes and you're good to go. However, there are a few more subtleties to using writable nested serializers, due to the dependancies between the various model instances, and the need to save or delete multiple instances in a single action. +Nested data structures are easy enough to work with if they're read-only - simply nest your serializer classes and you're good to go. However, there are a few more subtleties to using writable nested serializers, due to the dependencies between the various model instances, and the need to save or delete multiple instances in a single action. ## One-to-many data structures diff --git a/rest_framework/compat.py b/rest_framework/compat.py index 3993cee6d..e4e69580f 100644 --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -131,7 +131,7 @@ else: self.message = kwargs.pop('message', self.message) super(MaxValueValidator, self).__init__(*args, **kwargs) -# URLValidator only accept `message` in 1.6+ +# URLValidator only accepts `message` in 1.6+ if django.VERSION >= (1, 6): from django.core.validators import URLValidator else: diff --git a/rest_framework/fields.py b/rest_framework/fields.py index f3ff22334..bba8ccae2 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -186,14 +186,14 @@ class Field(object): def get_initial(self): """ - Return a value to use when the field is being returned as a primative + Return a value to use when the field is being returned as a primitive value, without any object instance. """ return self.initial def get_value(self, dictionary): """ - Given the *incoming* primative data, return the value for this field + Given the *incoming* primitive data, return the value for this field that should be validated and transformed to a native value. """ if html.is_html_input(dictionary): @@ -205,7 +205,7 @@ class Field(object): def get_field_representation(self, instance): """ - Given the outgoing object instance, return the primative value + Given the outgoing object instance, return the primitive value that should be used for this field. """ attribute = get_attribute(instance, self.source_attrs) @@ -274,13 +274,13 @@ class Field(object): def to_internal_value(self, data): """ - Transform the *incoming* primative data into a native value. + Transform the *incoming* primitive data into a native value. """ raise NotImplementedError('to_internal_value() must be implemented.') def to_representation(self, value): """ - Transform the *outgoing* native value into primative data. + Transform the *outgoing* native value into primitive data. """ raise NotImplementedError('to_representation() must be implemented.') @@ -928,7 +928,7 @@ class ImageField(FileField): def to_internal_value(self, data): # Image validation is a bit grungy, so we'll just outright # defer to Django's implementation so we don't need to - # consider it, or treat PIL as a test dependancy. + # consider it, or treat PIL as a test dependency. file_object = super(ImageField, self).to_internal_value(data) django_field = self._DjangoImageField() django_field.error_messages = self.error_messages diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 8c1356727..8141de134 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -100,7 +100,7 @@ class HyperlinkedRelatedField(RelatedField): self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field) self.format = kwargs.pop('format', None) - # We include these simply for dependancy injection in tests. + # We include these simply for dependency injection in tests. # We can't add them as class attributes or they would expect an # implict `self` argument to be passed. self.reverse = reverse diff --git a/rest_framework/validators.py b/rest_framework/validators.py index 20de4b427..5bb69ad88 100644 --- a/rest_framework/validators.py +++ b/rest_framework/validators.py @@ -2,7 +2,7 @@ We perform uniqueness checks explicitly on the serializer class, rather the using Django's `.full_clean()`. -This gives us better seperation of concerns, allows us to use single-step +This gives us better separation of concerns, allows us to use single-step object creation, and makes it possible to switch between using the implicit `ModelSerializer` class and an equivelent explicit `Serializer` class. """ diff --git a/rest_framework/views.py b/rest_framework/views.py index 835e223a7..979229eb4 100644 --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -100,7 +100,7 @@ class APIView(View): content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS metadata_class = api_settings.DEFAULT_METADATA_CLASS - # Allow dependancy injection of other settings to make testing easier. + # Allow dependency injection of other settings to make testing easier. settings = api_settings @classmethod diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index 2edf0be5b..bb74cd2e2 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -34,7 +34,7 @@ class RegularFieldsModel(models.Model): big_integer_field = models.BigIntegerField() boolean_field = models.BooleanField(default=False) char_field = models.CharField(max_length=100) - comma_seperated_integer_field = models.CommaSeparatedIntegerField(max_length=100) + comma_separated_integer_field = models.CommaSeparatedIntegerField(max_length=100) date_field = models.DateField() datetime_field = models.DateTimeField() decimal_field = models.DecimalField(max_digits=3, decimal_places=1) @@ -83,7 +83,7 @@ class TestRegularFieldMappings(TestCase): big_integer_field = IntegerField() boolean_field = BooleanField(required=False) char_field = CharField(max_length=100) - comma_seperated_integer_field = CharField(max_length=100, validators=[<django.core.validators.RegexValidator object>]) + comma_separated_integer_field = CharField(max_length=100, validators=[<django.core.validators.RegexValidator object>]) date_field = DateField() datetime_field = DateTimeField() decimal_field = DecimalField(decimal_places=1, max_digits=3) diff --git a/tests/test_relations.py b/tests/test_relations.py index 2d11672b8..66784195e 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -161,18 +161,18 @@ class TestSlugRelatedField(APISimpleTestCase): # https://github.com/tomchristie/django-rest-framework/issues/446 # """ # field = serializers.PrimaryKeyRelatedField(queryset=NullModel.objects.all()) -# self.assertRaises(serializers.ValidationError, field.to_primative, '') -# self.assertRaises(serializers.ValidationError, field.to_primative, []) +# self.assertRaises(serializers.ValidationError, field.to_primitive, '') +# self.assertRaises(serializers.ValidationError, field.to_primitive, []) # def test_hyperlinked_related_field_with_empty_string(self): # field = serializers.HyperlinkedRelatedField(queryset=NullModel.objects.all(), view_name='') -# self.assertRaises(serializers.ValidationError, field.to_primative, '') -# self.assertRaises(serializers.ValidationError, field.to_primative, []) +# self.assertRaises(serializers.ValidationError, field.to_primitive, '') +# self.assertRaises(serializers.ValidationError, field.to_primitive, []) # def test_slug_related_field_with_empty_string(self): # field = serializers.SlugRelatedField(queryset=NullModel.objects.all(), slug_field='pk') -# self.assertRaises(serializers.ValidationError, field.to_primative, '') -# self.assertRaises(serializers.ValidationError, field.to_primative, []) +# self.assertRaises(serializers.ValidationError, field.to_primitive, '') +# self.assertRaises(serializers.ValidationError, field.to_primitive, []) # class TestManyRelatedMixin(TestCase): From 857a8486b1534f89bd482de86d39ff717b6618eb Mon Sep 17 00:00:00 2001 From: Craig de Stigter <craig.destigter@koordinates.com> Date: Fri, 3 Oct 2014 09:00:33 +1300 Subject: [PATCH 121/249] More spelling tweaks --- docs/topics/3.0-announcement.md | 6 +++--- rest_framework/filters.py | 2 +- rest_framework/mixins.py | 2 +- rest_framework/relations.py | 2 +- tests/test_response.py | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 5242be573..fcae79e12 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -411,7 +411,7 @@ The following class is an example of a generic serializer that can handle coerci # Ignore methods and other callables. pass elif isinstance(attribute, (str, int, bool, float, type(None))): - # primitive types can be passed through unmodified. + # Primitive types can be passed through unmodified. output[attribute_name] = attribute elif isinstance(attribute, list): # Recursivly deal with items in lists. @@ -446,7 +446,7 @@ We now use the following: #### The `required`, `allow_none`, `allow_blank` and `default` arguments. -REST framework now has more explict and clear control over validating empty values for fields. +REST framework now has more explicit and clear control over validating empty values for fields. Previously the meaning of the `required=False` keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be `None`. @@ -522,7 +522,7 @@ However this code *would not be valid* in `2.4.3`: # ... The queryset argument is now always required for writable relational fields. -This removes some magic and makes it easier and more obvious to move between implict `ModelSerializer` classes and explicit `Serializer` classes. +This removes some magic and makes it easier and more obvious to move between implicit `ModelSerializer` classes and explicit `Serializer` classes. class AccountSerializer(serializers.ModelSerializer): organisations = serializers.SlugRelatedField( diff --git a/rest_framework/filters.py b/rest_framework/filters.py index 4c485668a..d188a2d1e 100644 --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -148,7 +148,7 @@ class OrderingFilter(BaseFilterBackend): if not getattr(field, 'write_only', False) ] elif valid_fields == '__all__': - # View explictly allows filtering on any model field + # 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() diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index 04b7a7636..de334b4b9 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -83,7 +83,7 @@ class DestroyModelMixin(object): # The AllowPUTAsCreateMixin was previously the default behaviour -# for PUT requests. This has now been removed and must be *explictly* +# for PUT requests. This has now been removed and must be *explicitly* # included if it is the behavior that you want. # For more info see: ... diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 8141de134..dc9781e7c 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -102,7 +102,7 @@ class HyperlinkedRelatedField(RelatedField): # We include these simply for dependency injection in tests. # We can't add them as class attributes or they would expect an - # implict `self` argument to be passed. + # implicit `self` argument to be passed. self.reverse = reverse self.resolve = resolve diff --git a/tests/test_response.py b/tests/test_response.py index 84c39c1a6..f233ae332 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -262,9 +262,9 @@ class Issue807Tests(TestCase): expected = "{0}; charset={1}".format(RendererC.media_type, RendererC.charset) self.assertEqual(expected, resp['Content-Type']) - def test_content_type_set_explictly_on_response(self): + def test_content_type_set_explicitly_on_response(self): """ - The content type may be set explictly on the response. + The content type may be set explicitly on the response. """ headers = {"HTTP_ACCEPT": RendererC.media_type} resp = self.client.get('/setbyview', **headers) From 765b0b33bf1fa9b7c6b45d3877d10a05d4e9f6ea Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 3 Oct 2014 13:12:23 +0100 Subject: [PATCH 122/249] Revert accidental stupidity --- rest_framework/relations.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 4f971917a..f9b5ff0d8 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -127,7 +127,7 @@ class HyperlinkedRelatedField(RelatedField): attributes are not configured to correctly match the URL conf. """ # Unsaved objects will not yet have a valid URL. - if obj.pk: + if obj.pk is None: return None lookup_value = getattr(obj, self.lookup_field) From e6c5ebdda6d0f169f21498909e2d390c460138a9 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 3 Oct 2014 13:14:17 +0100 Subject: [PATCH 123/249] Fix indentation --- rest_framework/serializers.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 21cb7ea27..c3a0815e2 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -252,10 +252,10 @@ class Serializer(BaseSerializer): def get_initial(self): if self._initial_data is not None: return ReturnDict([ - (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 - ], serializer=self) + (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 + ], serializer=self) #return self.to_representation(self._initial_data) return ReturnDict([ From 3a3e2bf57d5443dc0b058d5beb3111f87c418947 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 3 Oct 2014 13:42:06 +0100 Subject: [PATCH 124/249] Serializer.save() takes keyword arguments, not 'extras' argument --- docs/topics/3.0-announcement.md | 21 ++++++++++----------- rest_framework/mixins.py | 4 ++-- rest_framework/serializers.py | 7 +++---- 3 files changed, 15 insertions(+), 17 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index fcae79e12..4a7815032 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -109,16 +109,16 @@ The following example from the tutorial previously used `restore_object()` to ha This would now be split out into two separate methods. - def update(self, instance, validated_attrs) - instance.title = validated_attrs.get('title', instance.title) - instance.code = validated_attrs.get('code', instance.code) - instance.linenos = validated_attrs.get('linenos', instance.linenos) - instance.language = validated_attrs.get('language', instance.language) - instance.style = validated_attrs.get('style', instance.style) + def update(self, instance, validated_data) + instance.title = validated_data.get('title', instance.title) + instance.code = validated_data.get('code', instance.code) + instance.linenos = validated_data.get('linenos', instance.linenos) + instance.language = validated_data.get('language', instance.language) + instance.style = validated_data.get('style', instance.style) instance.save() - def create(self, validated_attrs): - return Snippet.objects.create(**validated_attrs) + def create(self, validated_data): + return Snippet.objects.create(**validated_data) Note that the `.create` method should return the newly created object instance. @@ -134,15 +134,14 @@ For example the following code *is no longer valid*: serializer.object.user = request.user # Include the user when saving. serializer.save() -Instead of using `.object` to inspect a partially constructed instance, you would now use `.validated_data` to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the `.save()` method using the `extras` keyword argument. +Instead of using `.object` to inspect a partially constructed instance, you would now use `.validated_data` to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the `.save()` method as keyword arguments. The corresponding code would now look like this: if serializer.is_valid(): name = serializer.validated_data['name'] # Inspect validated field data. logging.info('Creating ticket "%s"' % name) - extras = {'user': request.user} # Include the user when saving. - serializer.save(extras=extras) + serializer.save(user=request.user) # Include the user when saving. #### Limitations of ModelSerializer validation. diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index de334b4b9..bc4ce22f1 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -101,8 +101,8 @@ class AllowPUTAsCreateMixin(object): if instance is None: lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field lookup_value = self.kwargs[lookup_url_kwarg] - extras = {self.lookup_field: lookup_value} - serializer.save(extras=extras) + extra_kwargs = {self.lookup_field: lookup_value} + serializer.save(**extra_kwargs) return Response(serializer.data, status=status.HTTP_201_CREATED) serializer.save() diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index c3a0815e2..ed024f87b 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -74,12 +74,12 @@ class BaseSerializer(Field): def create(self, validated_data): raise NotImplementedError('`create()` must be implemented.') - def save(self, extras=None): + def save(self, **kwargs): validated_data = self.validated_data - if extras is not None: + if kwargs: validated_data = dict( list(validated_data.items()) + - list(extras.items()) + list(kwargs.items()) ) if self.instance is not None: @@ -256,7 +256,6 @@ class Serializer(BaseSerializer): for field_name, field in self.fields.items() if field.get_value(self._initial_data) is not empty ], serializer=self) - #return self.to_representation(self._initial_data) return ReturnDict([ (field.field_name, field.get_initial()) From 2dfe75c23a041493bc83514d8e9e9268b79072d9 Mon Sep 17 00:00:00 2001 From: Jones Chi <duguschi@gmail.com> Date: Fri, 3 Oct 2014 14:42:49 +0800 Subject: [PATCH 125/249] Fix follow does not work on APIClient Handle follow just like Django's Client. --- rest_framework/test.py | 46 +++++++++++++++++++++++++++++++++++++++++ tests/test_testing.py | 47 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) diff --git a/rest_framework/test.py b/rest_framework/test.py index 9b40353a3..74d2c868f 100644 --- a/rest_framework/test.py +++ b/rest_framework/test.py @@ -156,6 +156,52 @@ class APIClient(APIRequestFactory, DjangoClient): kwargs.update(self._credentials) return super(APIClient, self).request(**kwargs) + def get(self, path, data=None, follow=False, **extra): + response = super(APIClient, self).get(path, data=data, **extra) + if follow: + response = self._handle_redirects(response, **extra) + return response + + def post(self, path, data=None, format=None, content_type=None, + follow=False, **extra): + response = super(APIClient, self).post( + path, data=data, format=format, content_type=content_type, **extra) + if follow: + response = self._handle_redirects(response, **extra) + return response + + def put(self, path, data=None, format=None, content_type=None, + follow=False, **extra): + response = super(APIClient, self).put( + path, data=data, format=format, content_type=content_type, **extra) + if follow: + response = self._handle_redirects(response, **extra) + return response + + def patch(self, path, data=None, format=None, content_type=None, + follow=False, **extra): + response = super(APIClient, self).patch( + path, data=data, format=format, content_type=content_type, **extra) + if follow: + response = self._handle_redirects(response, **extra) + return response + + def delete(self, path, data=None, format=None, content_type=None, + follow=False, **extra): + response = super(APIClient, self).delete( + path, data=data, format=format, content_type=content_type, **extra) + if follow: + response = self._handle_redirects(response, **extra) + return response + + def options(self, path, data=None, format=None, content_type=None, + follow=False, **extra): + response = super(APIClient, self).options( + path, data=data, format=format, content_type=content_type, **extra) + if follow: + response = self._handle_redirects(response, **extra) + return response + def logout(self): self._credentials = {} return super(APIClient, self).logout() diff --git a/tests/test_testing.py b/tests/test_testing.py index 9c472026a..9fd5966eb 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -5,6 +5,7 @@ from django.conf.urls import patterns, url from io import BytesIO from django.contrib.auth.models import User +from django.shortcuts import redirect from django.test import TestCase from rest_framework.decorators import api_view from rest_framework.response import Response @@ -28,10 +29,16 @@ def session_view(request): }) +@api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']) +def redirect_view(request): + return redirect('/view/') + + urlpatterns = patterns( '', url(r'^view/$', view), url(r'^session-view/$', session_view), + url(r'^redirect-view/$', redirect_view), ) @@ -111,6 +118,46 @@ class TestAPITestClient(TestCase): response = self.client.get('/view/') self.assertEqual(response.data['auth'], b'') + def test_follow_redirect(self): + """ + Follow redirect by setting follow argument. + """ + response = self.client.get('/redirect-view/') + self.assertEqual(response.status_code, 302) + response = self.client.get('/redirect-view/', follow=True) + self.assertIsNotNone(response.redirect_chain) + self.assertEqual(response.status_code, 200) + + response = self.client.post('/redirect-view/') + self.assertEqual(response.status_code, 302) + response = self.client.post('/redirect-view/', follow=True) + self.assertIsNotNone(response.redirect_chain) + self.assertEqual(response.status_code, 200) + + response = self.client.put('/redirect-view/') + self.assertEqual(response.status_code, 302) + response = self.client.put('/redirect-view/', follow=True) + self.assertIsNotNone(response.redirect_chain) + self.assertEqual(response.status_code, 200) + + response = self.client.patch('/redirect-view/') + self.assertEqual(response.status_code, 302) + response = self.client.patch('/redirect-view/', follow=True) + self.assertIsNotNone(response.redirect_chain) + self.assertEqual(response.status_code, 200) + + response = self.client.delete('/redirect-view/') + self.assertEqual(response.status_code, 302) + response = self.client.delete('/redirect-view/', follow=True) + self.assertIsNotNone(response.redirect_chain) + self.assertEqual(response.status_code, 200) + + response = self.client.options('/redirect-view/') + self.assertEqual(response.status_code, 302) + response = self.client.options('/redirect-view/', follow=True) + self.assertIsNotNone(response.redirect_chain) + self.assertEqual(response.status_code, 200) + class TestAPIRequestFactory(TestCase): def test_csrf_exempt_by_default(self): From 6bfed6f8525a49fc50df7143ac2d492528b8f2ac Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Tue, 7 Oct 2014 17:04:53 +0100 Subject: [PATCH 126/249] Enforce uniqueness validation for relational fields --- rest_framework/fields.py | 2 ++ rest_framework/utils/field_mapping.py | 3 +++ tests/test_model_serializer.py | 4 ++-- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 0963d4bf2..9d577c53c 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -224,6 +224,8 @@ class Field(object): """ if self.default is empty: raise SkipField() + if is_simple_callable(self.default): + return self.default() return self.default def run_validation(self, data=empty): diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index 30fae3709..fd6da699f 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -219,6 +219,9 @@ def get_relation_kwargs(field_name, relation_info): kwargs['required'] = False if model_field.null: kwargs['allow_null'] = True + if getattr(model_field, 'unique', False): + validator = UniqueValidator(queryset=model_field.model._default_manager) + kwargs['validators'] = [validator] return kwargs diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index bb74cd2e2..18170bc06 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -248,7 +248,7 @@ class TestRelationalFieldMappings(TestCase): TestSerializer(): id = IntegerField(label='ID', read_only=True) foreign_key = PrimaryKeyRelatedField(queryset=ForeignKeyTargetModel.objects.all()) - one_to_one = PrimaryKeyRelatedField(queryset=OneToOneTargetModel.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()) through = PrimaryKeyRelatedField(many=True, read_only=True) """) @@ -287,7 +287,7 @@ class TestRelationalFieldMappings(TestCase): TestSerializer(): 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(), view_name='onetoonetargetmodel-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') through = HyperlinkedRelatedField(many=True, read_only=True, view_name='throughtargetmodel-detail') """) From 3fa4a1898aee0dabee951f81f790bb2da042ec81 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Tue, 7 Oct 2014 17:21:12 +0100 Subject: [PATCH 127/249] Reintroduce save hooks --- rest_framework/mixins.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index bc4ce22f1..03ebb0341 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -20,10 +20,13 @@ class CreateModelMixin(object): def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) - serializer.save() + self.create_valid(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) + def create_valid(self, serializer): + serializer.save() + def get_success_headers(self, data): try: return {'Location': data[api_settings.URL_FIELD_NAME]} @@ -64,9 +67,12 @@ class UpdateModelMixin(object): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) - serializer.save() + self.update_valid(serializer) return Response(serializer.data) + def update_valid(self, serializer): + serializer.save() + def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) From 093febb91299e332c810de6a6b6aba57c2b16a91 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 8 Oct 2014 11:04:08 +0100 Subject: [PATCH 128/249] Tests for relational fields --- rest_framework/fields.py | 9 +- tests/test_relations_hyperlink.py | 775 +++++++++++++++--------------- tests/test_relations_pk.py | 764 +++++++++++++++-------------- tests/test_relations_slug.py | 455 +++++++++--------- 4 files changed, 1008 insertions(+), 995 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 9d577c53c..5fb0ec8d7 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1,7 +1,7 @@ from django import forms from django.conf import settings from django.core import validators -from django.core.exceptions import ValidationError +from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.utils import six, timezone from django.utils.datastructures import SortedDict from django.utils.dateparse import parse_date, parse_datetime, parse_time @@ -54,6 +54,8 @@ def get_attribute(instance, attrs): for attr in attrs: try: instance = getattr(instance, attr) + except ObjectDoesNotExist: + return None except AttributeError as exc: try: return instance[attr] @@ -108,6 +110,7 @@ class Field(object): default_validators = [] default_empty_html = empty initial = None + coerce_blank_to_null = True def __init__(self, read_only=False, write_only=False, required=None, default=empty, initial=empty, source=None, @@ -245,6 +248,9 @@ class Field(object): self.fail('required') return self.get_default() + if data == '' and self.coerce_blank_to_null: + data = None + if data is None: if not self.allow_null: self.fail('null') @@ -413,6 +419,7 @@ class CharField(Field): 'blank': _('This field may not be blank.') } initial = '' + coerce_blank_to_null = False def __init__(self, **kwargs): self.allow_blank = kwargs.pop('allow_blank', False) diff --git a/tests/test_relations_hyperlink.py b/tests/test_relations_hyperlink.py index 315d1abf8..0337f3599 100644 --- a/tests/test_relations_hyperlink.py +++ b/tests/test_relations_hyperlink.py @@ -1,459 +1,460 @@ -# from __future__ import unicode_literals -# from django.conf.urls import patterns, url -# from django.test import TestCase -# from rest_framework import serializers -# from rest_framework.test import APIRequestFactory -# from tests.models import ( -# BlogPost, -# ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, -# NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource -# ) +from __future__ import unicode_literals +from django.conf.urls import patterns, url +from django.test import TestCase +from rest_framework import serializers +from rest_framework.test import APIRequestFactory +from tests.models import ( + ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, + NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource +) -# factory = APIRequestFactory() -# request = factory.get('/') # Just to ensure we have a request in the serializer context +factory = APIRequestFactory() +request = factory.get('/') # Just to ensure we have a request in the serializer context -# def dummy_view(request, pk): -# pass +dummy_view = lambda request, pk: None -# urlpatterns = patterns( -# '', -# url(r'^dummyurl/(?P<pk>[0-9]+)/$', dummy_view, name='dummy-url'), -# url(r'^manytomanysource/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanysource-detail'), -# url(r'^manytomanytarget/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanytarget-detail'), -# url(r'^foreignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeysource-detail'), -# url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'), -# url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'), -# url(r'^onetoonetarget/(?P<pk>[0-9]+)/$', dummy_view, name='onetoonetarget-detail'), -# url(r'^nullableonetoonesource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableonetoonesource-detail'), -# ) +urlpatterns = patterns( + '', + url(r'^dummyurl/(?P<pk>[0-9]+)/$', dummy_view, name='dummy-url'), + url(r'^manytomanysource/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanysource-detail'), + url(r'^manytomanytarget/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanytarget-detail'), + url(r'^foreignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeysource-detail'), + url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'), + url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'), + url(r'^onetoonetarget/(?P<pk>[0-9]+)/$', dummy_view, name='onetoonetarget-detail'), + url(r'^nullableonetoonesource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableonetoonesource-detail'), +) -# # ManyToMany -# class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer): -# class Meta: -# model = ManyToManyTarget -# fields = ('url', 'name', 'sources') +# ManyToMany +class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = ManyToManyTarget + fields = ('url', 'name', 'sources') -# class ManyToManySourceSerializer(serializers.HyperlinkedModelSerializer): -# class Meta: -# model = ManyToManySource -# fields = ('url', 'name', 'targets') +class ManyToManySourceSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = ManyToManySource + fields = ('url', 'name', 'targets') -# # ForeignKey -# class ForeignKeyTargetSerializer(serializers.HyperlinkedModelSerializer): -# class Meta: -# model = ForeignKeyTarget -# fields = ('url', 'name', 'sources') +# ForeignKey +class ForeignKeyTargetSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = ForeignKeyTarget + fields = ('url', 'name', 'sources') -# class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): -# class Meta: -# model = ForeignKeySource -# fields = ('url', 'name', 'target') +class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = ForeignKeySource + fields = ('url', 'name', 'target') -# # Nullable ForeignKey -# class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): -# class Meta: -# model = NullableForeignKeySource -# fields = ('url', 'name', 'target') +# Nullable ForeignKey +class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = NullableForeignKeySource + fields = ('url', 'name', 'target') -# # Nullable OneToOne -# class NullableOneToOneTargetSerializer(serializers.HyperlinkedModelSerializer): -# class Meta: -# model = OneToOneTarget -# fields = ('url', 'name', 'nullable_source') +# Nullable OneToOne +class NullableOneToOneTargetSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = OneToOneTarget + fields = ('url', 'name', 'nullable_source') -# # TODO: Add test that .data cannot be accessed prior to .is_valid +# TODO: Add test that .data cannot be accessed prior to .is_valid -# class HyperlinkedManyToManyTests(TestCase): -# urls = 'tests.test_relations_hyperlink' +class HyperlinkedManyToManyTests(TestCase): + urls = 'tests.test_relations_hyperlink' -# def setUp(self): -# for idx in range(1, 4): -# target = ManyToManyTarget(name='target-%d' % idx) -# target.save() -# source = ManyToManySource(name='source-%d' % idx) -# source.save() -# for target in ManyToManyTarget.objects.all(): -# source.targets.add(target) + def setUp(self): + for idx in range(1, 4): + target = ManyToManyTarget(name='target-%d' % idx) + target.save() + source = ManyToManySource(name='source-%d' % idx) + source.save() + for target in ManyToManyTarget.objects.all(): + source.targets.add(target) -# def test_many_to_many_retrieve(self): -# queryset = ManyToManySource.objects.all() -# serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']}, -# {'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) + def test_many_to_many_retrieve(self): + queryset = ManyToManySource.objects.all() + serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']}, + {'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) -# def test_reverse_many_to_many_retrieve(self): -# queryset = ManyToManyTarget.objects.all() -# serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']}, -# {'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) + def test_reverse_many_to_many_retrieve(self): + queryset = ManyToManyTarget.objects.all() + serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']}, + {'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) -# 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/']} -# instance = ManyToManySource.objects.get(pk=1) -# serializer = ManyToManySourceSerializer(instance, data=data, context={'request': request}) -# self.assertTrue(serializer.is_valid()) -# serializer.save() -# self.assertEqual(serializer.data, data) + 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/']} + instance = ManyToManySource.objects.get(pk=1) + serializer = ManyToManySourceSerializer(instance, data=data, context={'request': request}) + self.assertTrue(serializer.is_valid()) + serializer.save() + self.assertEqual(serializer.data, data) -# # Ensure source 1 is updated, and everything else is as expected -# queryset = ManyToManySource.objects.all() -# serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}, -# {'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) + # Ensure source 1 is updated, and everything else is as expected + queryset = ManyToManySource.objects.all() + serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}, + {'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) -# def test_reverse_many_to_many_update(self): -# data = {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']} -# instance = ManyToManyTarget.objects.get(pk=1) -# serializer = ManyToManyTargetSerializer(instance, data=data, context={'request': request}) -# self.assertTrue(serializer.is_valid()) -# serializer.save() -# self.assertEqual(serializer.data, data) + def test_reverse_many_to_many_update(self): + data = {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']} + instance = ManyToManyTarget.objects.get(pk=1) + serializer = ManyToManyTargetSerializer(instance, data=data, context={'request': request}) + self.assertTrue(serializer.is_valid()) + serializer.save() + self.assertEqual(serializer.data, data) -# # Ensure target 1 is updated, and everything else is as expected -# queryset = ManyToManyTarget.objects.all() -# serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']}, -# {'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/']} + # Ensure target 1 is updated, and everything else is as expected + queryset = ManyToManyTarget.objects.all() + serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']}, + {'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) + ] + self.assertEqual(serializer.data, expected) -# def test_many_to_many_create(self): -# data = {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']} -# serializer = ManyToManySourceSerializer(data=data, context={'request': request}) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, data) -# self.assertEqual(obj.name, 'source-4') + def test_many_to_many_create(self): + data = {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']} + serializer = ManyToManySourceSerializer(data=data, context={'request': request}) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, data) + self.assertEqual(obj.name, 'source-4') -# # Ensure source 4 is added, and everything else is as expected -# queryset = ManyToManySource.objects.all() -# serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']}, -# {'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/']}, -# {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 4 is added, and everything else is as expected + queryset = ManyToManySource.objects.all() + serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']}, + {'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/']}, + {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']} + ] + self.assertEqual(serializer.data, expected) -# def test_reverse_many_to_many_create(self): -# data = {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']} -# serializer = ManyToManyTargetSerializer(data=data, context={'request': request}) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, data) -# self.assertEqual(obj.name, 'target-4') + def test_reverse_many_to_many_create(self): + data = {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']} + serializer = ManyToManyTargetSerializer(data=data, context={'request': request}) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, data) + self.assertEqual(obj.name, 'target-4') -# # Ensure target 4 is added, and everything else is as expected -# queryset = ManyToManyTarget.objects.all() -# serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']}, -# {'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/']}, -# {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure target 4 is added, and everything else is as expected + queryset = ManyToManyTarget.objects.all() + serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']}, + {'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/']}, + {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']} + ] + self.assertEqual(serializer.data, expected) -# class HyperlinkedForeignKeyTests(TestCase): -# urls = 'tests.test_relations_hyperlink' +class HyperlinkedForeignKeyTests(TestCase): + urls = 'tests.test_relations_hyperlink' -# def setUp(self): -# target = ForeignKeyTarget(name='target-1') -# target.save() -# new_target = ForeignKeyTarget(name='target-2') -# new_target.save() -# for idx in range(1, 4): -# source = ForeignKeySource(name='source-%d' % idx, target=target) -# source.save() + def setUp(self): + target = ForeignKeyTarget(name='target-1') + target.save() + new_target = ForeignKeyTarget(name='target-2') + new_target.save() + for idx in range(1, 4): + source = ForeignKeySource(name='source-%d' % idx, target=target) + source.save() -# def test_foreign_key_retrieve(self): -# queryset = ForeignKeySource.objects.all() -# serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, -# {'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) + def test_foreign_key_retrieve(self): + queryset = ForeignKeySource.objects.all() + serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, + {'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) -# def test_reverse_foreign_key_retrieve(self): -# queryset = ForeignKeyTarget.objects.all() -# serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'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) + def test_reverse_foreign_key_retrieve(self): + queryset = ForeignKeyTarget.objects.all() + serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'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) -# def test_foreign_key_update(self): -# data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'} -# instance = ForeignKeySource.objects.get(pk=1) -# serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request}) -# self.assertTrue(serializer.is_valid()) -# self.assertEqual(serializer.data, data) -# serializer.save() + def test_foreign_key_update(self): + data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'} + instance = ForeignKeySource.objects.get(pk=1) + serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request}) + self.assertTrue(serializer.is_valid()) + serializer.save() + self.assertEqual(serializer.data, data) -# # Ensure source 1 is updated, and everything else is as expected -# queryset = ForeignKeySource.objects.all() -# serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'}, -# {'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) + # Ensure source 1 is updated, and everything else is as expected + queryset = ForeignKeySource.objects.all() + serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'}, + {'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) -# def test_foreign_key_update_incorrect_type(self): -# data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 2} -# instance = ForeignKeySource.objects.get(pk=1) -# serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request}) -# self.assertFalse(serializer.is_valid()) -# self.assertEqual(serializer.errors, {'target': ['Incorrect type. Expected url string, received int.']}) + def test_foreign_key_update_incorrect_type(self): + data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 2} + instance = ForeignKeySource.objects.get(pk=1) + serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request}) + self.assertFalse(serializer.is_valid()) + self.assertEqual(serializer.errors, {'target': ['Incorrect type. Expected URL string, received int.']}) -# def test_reverse_foreign_key_update(self): -# data = {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']} -# instance = ForeignKeyTarget.objects.get(pk=2) -# serializer = ForeignKeyTargetSerializer(instance, data=data, context={'request': request}) -# self.assertTrue(serializer.is_valid()) -# # We shouldn't have saved anything to the db yet since save -# # hasn't been called. -# queryset = ForeignKeyTarget.objects.all() -# new_serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'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(new_serializer.data, expected) + def test_reverse_foreign_key_update(self): + data = {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']} + instance = ForeignKeyTarget.objects.get(pk=2) + serializer = ForeignKeyTargetSerializer(instance, data=data, context={'request': request}) + self.assertTrue(serializer.is_valid()) + # We shouldn't have saved anything to the db yet since save + # hasn't been called. + queryset = ForeignKeyTarget.objects.all() + new_serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'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(new_serializer.data, expected) -# serializer.save() -# self.assertEqual(serializer.data, data) + serializer.save() + self.assertEqual(serializer.data, data) -# # Ensure target 2 is update, and everything else is as expected -# queryset = ForeignKeyTarget.objects.all() -# serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']}, -# {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}, -# ] -# self.assertEqual(serializer.data, expected) + # Ensure target 2 is update, and everything else is as expected + queryset = ForeignKeyTarget.objects.all() + serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']}, + {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}, + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_create(self): -# data = {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'} -# serializer = ForeignKeySourceSerializer(data=data, context={'request': request}) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, data) -# self.assertEqual(obj.name, 'source-4') + def test_foreign_key_create(self): + data = {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'} + serializer = ForeignKeySourceSerializer(data=data, context={'request': request}) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, data) + self.assertEqual(obj.name, 'source-4') -# # Ensure source 1 is updated, and everything else is as expected -# queryset = ForeignKeySource.objects.all() -# serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, -# {'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/'}, -# {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'}, -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 1 is updated, and everything else is as expected + queryset = ForeignKeySource.objects.all() + serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, + {'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/'}, + {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'}, + ] + self.assertEqual(serializer.data, expected) -# def test_reverse_foreign_key_create(self): -# data = {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']} -# serializer = ForeignKeyTargetSerializer(data=data, context={'request': request}) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, data) -# self.assertEqual(obj.name, 'target-3') + def test_reverse_foreign_key_create(self): + data = {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']} + serializer = ForeignKeyTargetSerializer(data=data, context={'request': request}) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, data) + self.assertEqual(obj.name, 'target-3') -# # Ensure target 4 is added, and everything else is as expected -# queryset = ForeignKeyTarget.objects.all() -# serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']}, -# {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []}, -# {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}, -# ] -# self.assertEqual(serializer.data, expected) + # Ensure target 4 is added, and everything else is as expected + queryset = ForeignKeyTarget.objects.all() + serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']}, + {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []}, + {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}, + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_update_with_invalid_null(self): -# data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': None} -# instance = ForeignKeySource.objects.get(pk=1) -# serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request}) -# self.assertFalse(serializer.is_valid()) -# self.assertEqual(serializer.errors, {'target': ['This field is required.']}) + def test_foreign_key_update_with_invalid_null(self): + data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': None} + instance = ForeignKeySource.objects.get(pk=1) + serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request}) + self.assertFalse(serializer.is_valid()) + self.assertEqual(serializer.errors, {'target': ['This field may not be null.']}) -# class HyperlinkedNullableForeignKeyTests(TestCase): -# urls = 'tests.test_relations_hyperlink' +class HyperlinkedNullableForeignKeyTests(TestCase): + urls = 'tests.test_relations_hyperlink' -# def setUp(self): -# target = ForeignKeyTarget(name='target-1') -# target.save() -# for idx in range(1, 4): -# if idx == 3: -# target = None -# source = NullableForeignKeySource(name='source-%d' % idx, target=target) -# source.save() + def setUp(self): + target = ForeignKeyTarget(name='target-1') + target.save() + for idx in range(1, 4): + if idx == 3: + target = None + source = NullableForeignKeySource(name='source-%d' % idx, target=target) + source.save() -# def test_foreign_key_retrieve_with_null(self): -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, -# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, -# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, -# ] -# self.assertEqual(serializer.data, expected) + def test_foreign_key_retrieve_with_null(self): + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, + {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, + {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_create_with_valid_null(self): -# data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} -# serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request}) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, data) -# self.assertEqual(obj.name, 'source-4') + def test_foreign_key_create_with_valid_null(self): + data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} + serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request}) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, data) + self.assertEqual(obj.name, 'source-4') -# # Ensure source 4 is created, and everything else is as expected -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, -# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, -# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, -# {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 4 is created, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, + {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, + {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, + {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_create_with_valid_emptystring(self): -# """ -# The emptystring should be interpreted as null in the context -# of relationships. -# """ -# data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': ''} -# expected_data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} -# serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request}) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, expected_data) -# self.assertEqual(obj.name, 'source-4') + def test_foreign_key_create_with_valid_emptystring(self): + """ + The emptystring should be interpreted as null in the context + of relationships. + """ + data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': ''} + expected_data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} + serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request}) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, expected_data) + self.assertEqual(obj.name, 'source-4') -# # Ensure source 4 is created, and everything else is as expected -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, -# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, -# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, -# {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 4 is created, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'}, + {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, + {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, + {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_update_with_valid_null(self): -# data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None} -# instance = NullableForeignKeySource.objects.get(pk=1) -# serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request}) -# self.assertTrue(serializer.is_valid()) -# self.assertEqual(serializer.data, data) -# serializer.save() + def test_foreign_key_update_with_valid_null(self): + data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None} + instance = NullableForeignKeySource.objects.get(pk=1) + serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request}) + self.assertTrue(serializer.is_valid()) + serializer.save() + self.assertEqual(serializer.data, data) -# # Ensure source 1 is updated, and everything else is as expected -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}, -# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, -# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 1 is updated, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}, + {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, + {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_update_with_valid_emptystring(self): -# """ -# The emptystring should be interpreted as null in the context -# of relationships. -# """ -# data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': ''} -# expected_data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None} -# instance = NullableForeignKeySource.objects.get(pk=1) -# serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request}) -# self.assertTrue(serializer.is_valid()) -# self.assertEqual(serializer.data, expected_data) -# serializer.save() + def test_foreign_key_update_with_valid_emptystring(self): + """ + The emptystring should be interpreted as null in the context + of relationships. + """ + data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': ''} + expected_data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None} + instance = NullableForeignKeySource.objects.get(pk=1) + serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request}) + self.assertTrue(serializer.is_valid()) + serializer.save() + self.assertEqual(serializer.data, expected_data) -# # Ensure source 1 is updated, and everything else is as expected -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}, -# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, -# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 1 is updated, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}, + {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'}, + {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, + ] + self.assertEqual(serializer.data, expected) # # reverse foreign keys MUST be read_only # # In the general case they do not provide .remove() or .clear() # # and cannot be arbitrarily set. -# # def test_reverse_foreign_key_update(self): -# # data = {'id': 1, 'name': 'target-1', 'sources': [1]} -# # instance = ForeignKeyTarget.objects.get(pk=1) -# # serializer = ForeignKeyTargetSerializer(instance, data=data) -# # self.assertTrue(serializer.is_valid()) -# # self.assertEqual(serializer.data, data) -# # serializer.save() + # def test_reverse_foreign_key_update(self): + # data = {'id': 1, 'name': 'target-1', 'sources': [1]} + # instance = ForeignKeyTarget.objects.get(pk=1) + # serializer = ForeignKeyTargetSerializer(instance, data=data) + # print serializer.is_valid() + # print serializer.errors + # print serializer + # self.assertTrue(serializer.is_valid()) + # serializer.save() + # self.assertEqual(serializer.data, data) -# # # Ensure target 1 is updated, and everything else is as expected -# # queryset = ForeignKeyTarget.objects.all() -# # serializer = ForeignKeyTargetSerializer(queryset, many=True) -# # expected = [ -# # {'id': 1, 'name': 'target-1', 'sources': [1]}, -# # {'id': 2, 'name': 'target-2', 'sources': []}, -# # ] -# # self.assertEqual(serializer.data, expected) + # # Ensure target 1 is updated, and everything else is as expected + # queryset = ForeignKeyTarget.objects.all() + # serializer = ForeignKeyTargetSerializer(queryset, many=True) + # expected = [ + # {'id': 1, 'name': 'target-1', 'sources': [1]}, + # {'id': 2, 'name': 'target-2', 'sources': []}, + # ] + # self.assertEqual(serializer.data, expected) -# class HyperlinkedNullableOneToOneTests(TestCase): -# urls = 'tests.test_relations_hyperlink' +class HyperlinkedNullableOneToOneTests(TestCase): + urls = 'tests.test_relations_hyperlink' -# def setUp(self): -# target = OneToOneTarget(name='target-1') -# target.save() -# new_target = OneToOneTarget(name='target-2') -# new_target.save() -# source = NullableOneToOneSource(name='source-1', target=target) -# source.save() + def setUp(self): + target = OneToOneTarget(name='target-1') + target.save() + new_target = OneToOneTarget(name='target-2') + new_target.save() + source = NullableOneToOneSource(name='source-1', target=target) + source.save() -# def test_reverse_foreign_key_retrieve_with_null(self): -# queryset = OneToOneTarget.objects.all() -# serializer = NullableOneToOneTargetSerializer(queryset, many=True, context={'request': request}) -# expected = [ -# {'url': 'http://testserver/onetoonetarget/1/', 'name': 'target-1', 'nullable_source': 'http://testserver/nullableonetoonesource/1/'}, -# {'url': 'http://testserver/onetoonetarget/2/', 'name': 'target-2', 'nullable_source': None}, -# ] -# self.assertEqual(serializer.data, expected) + def test_reverse_foreign_key_retrieve_with_null(self): + queryset = OneToOneTarget.objects.all() + serializer = NullableOneToOneTargetSerializer(queryset, many=True, context={'request': request}) + expected = [ + {'url': 'http://testserver/onetoonetarget/1/', 'name': 'target-1', 'nullable_source': 'http://testserver/nullableonetoonesource/1/'}, + {'url': 'http://testserver/onetoonetarget/2/', 'name': 'target-2', 'nullable_source': None}, + ] + self.assertEqual(serializer.data, expected) # # Regression tests for #694 (`source` attribute on related fields) diff --git a/tests/test_relations_pk.py b/tests/test_relations_pk.py index 031a79b32..da3c57863 100644 --- a/tests/test_relations_pk.py +++ b/tests/test_relations_pk.py @@ -1,446 +1,443 @@ -# from __future__ import unicode_literals -# from django.db import models -# from django.test import TestCase -# from django.utils import six -# from rest_framework import serializers -# from tests.models import ( -# BlogPost, ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, -# NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource, -# ) +from __future__ import unicode_literals +from django.test import TestCase +from django.utils import six +from rest_framework import serializers +from tests.models import ( + ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, + NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource, +) -# # ManyToMany -# class ManyToManyTargetSerializer(serializers.ModelSerializer): -# class Meta: -# model = ManyToManyTarget -# fields = ('id', 'name', 'sources') +# ManyToMany +class ManyToManyTargetSerializer(serializers.ModelSerializer): + class Meta: + model = ManyToManyTarget + fields = ('id', 'name', 'sources') -# class ManyToManySourceSerializer(serializers.ModelSerializer): -# class Meta: -# model = ManyToManySource -# fields = ('id', 'name', 'targets') +class ManyToManySourceSerializer(serializers.ModelSerializer): + class Meta: + model = ManyToManySource + fields = ('id', 'name', 'targets') -# # ForeignKey -# class ForeignKeyTargetSerializer(serializers.ModelSerializer): -# class Meta: -# model = ForeignKeyTarget -# fields = ('id', 'name', 'sources') +# ForeignKey +class ForeignKeyTargetSerializer(serializers.ModelSerializer): + class Meta: + model = ForeignKeyTarget + fields = ('id', 'name', 'sources') -# class ForeignKeySourceSerializer(serializers.ModelSerializer): -# class Meta: -# model = ForeignKeySource -# fields = ('id', 'name', 'target') +class ForeignKeySourceSerializer(serializers.ModelSerializer): + class Meta: + model = ForeignKeySource + fields = ('id', 'name', 'target') -# # Nullable ForeignKey -# class NullableForeignKeySourceSerializer(serializers.ModelSerializer): -# class Meta: -# model = NullableForeignKeySource -# fields = ('id', 'name', 'target') +# Nullable ForeignKey +class NullableForeignKeySourceSerializer(serializers.ModelSerializer): + class Meta: + model = NullableForeignKeySource + fields = ('id', 'name', 'target') -# # Nullable OneToOne -# class NullableOneToOneTargetSerializer(serializers.ModelSerializer): -# class Meta: -# model = OneToOneTarget -# fields = ('id', 'name', 'nullable_source') +# Nullable OneToOne +class NullableOneToOneTargetSerializer(serializers.ModelSerializer): + class Meta: + model = OneToOneTarget + fields = ('id', 'name', 'nullable_source') -# # TODO: Add test that .data cannot be accessed prior to .is_valid +# TODO: Add test that .data cannot be accessed prior to .is_valid -# class PKManyToManyTests(TestCase): -# def setUp(self): -# for idx in range(1, 4): -# target = ManyToManyTarget(name='target-%d' % idx) -# target.save() -# source = ManyToManySource(name='source-%d' % idx) -# source.save() -# for target in ManyToManyTarget.objects.all(): -# source.targets.add(target) +class PKManyToManyTests(TestCase): + def setUp(self): + for idx in range(1, 4): + target = ManyToManyTarget(name='target-%d' % idx) + target.save() + source = ManyToManySource(name='source-%d' % idx) + source.save() + for target in ManyToManyTarget.objects.all(): + source.targets.add(target) -# def test_many_to_many_retrieve(self): -# queryset = ManyToManySource.objects.all() -# serializer = ManyToManySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'targets': [1]}, -# {'id': 2, 'name': 'source-2', 'targets': [1, 2]}, -# {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]} -# ] -# self.assertEqual(serializer.data, expected) + def test_many_to_many_retrieve(self): + queryset = ManyToManySource.objects.all() + serializer = ManyToManySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'targets': [1]}, + {'id': 2, 'name': 'source-2', 'targets': [1, 2]}, + {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]} + ] + self.assertEqual(serializer.data, expected) -# def test_reverse_many_to_many_retrieve(self): -# queryset = ManyToManyTarget.objects.all() -# serializer = ManyToManyTargetSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, -# {'id': 2, 'name': 'target-2', 'sources': [2, 3]}, -# {'id': 3, 'name': 'target-3', 'sources': [3]} -# ] -# self.assertEqual(serializer.data, expected) + def test_reverse_many_to_many_retrieve(self): + queryset = ManyToManyTarget.objects.all() + serializer = ManyToManyTargetSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, + {'id': 2, 'name': 'target-2', 'sources': [2, 3]}, + {'id': 3, 'name': 'target-3', 'sources': [3]} + ] + self.assertEqual(serializer.data, expected) -# def test_many_to_many_update(self): -# data = {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]} -# instance = ManyToManySource.objects.get(pk=1) -# serializer = ManyToManySourceSerializer(instance, data=data) -# self.assertTrue(serializer.is_valid()) -# serializer.save() -# self.assertEqual(serializer.data, data) + def test_many_to_many_update(self): + data = {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]} + instance = ManyToManySource.objects.get(pk=1) + serializer = ManyToManySourceSerializer(instance, data=data) + self.assertTrue(serializer.is_valid()) + serializer.save() + self.assertEqual(serializer.data, data) -# # Ensure source 1 is updated, and everything else is as expected -# queryset = ManyToManySource.objects.all() -# serializer = ManyToManySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]}, -# {'id': 2, 'name': 'source-2', 'targets': [1, 2]}, -# {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 1 is updated, and everything else is as expected + queryset = ManyToManySource.objects.all() + serializer = ManyToManySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]}, + {'id': 2, 'name': 'source-2', 'targets': [1, 2]}, + {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]} + ] + self.assertEqual(serializer.data, expected) -# def test_reverse_many_to_many_update(self): -# data = {'id': 1, 'name': 'target-1', 'sources': [1]} -# instance = ManyToManyTarget.objects.get(pk=1) -# serializer = ManyToManyTargetSerializer(instance, data=data) -# self.assertTrue(serializer.is_valid()) -# serializer.save() -# self.assertEqual(serializer.data, data) + def test_reverse_many_to_many_update(self): + data = {'id': 1, 'name': 'target-1', 'sources': [1]} + instance = ManyToManyTarget.objects.get(pk=1) + serializer = ManyToManyTargetSerializer(instance, data=data) + self.assertTrue(serializer.is_valid()) + serializer.save() + self.assertEqual(serializer.data, data) -# # Ensure target 1 is updated, and everything else is as expected -# queryset = ManyToManyTarget.objects.all() -# serializer = ManyToManyTargetSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'target-1', 'sources': [1]}, -# {'id': 2, 'name': 'target-2', 'sources': [2, 3]}, -# {'id': 3, 'name': 'target-3', 'sources': [3]} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure target 1 is updated, and everything else is as expected + queryset = ManyToManyTarget.objects.all() + serializer = ManyToManyTargetSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'target-1', 'sources': [1]}, + {'id': 2, 'name': 'target-2', 'sources': [2, 3]}, + {'id': 3, 'name': 'target-3', 'sources': [3]} + ] + self.assertEqual(serializer.data, expected) -# def test_many_to_many_create(self): -# data = {'id': 4, 'name': 'source-4', 'targets': [1, 3]} -# serializer = ManyToManySourceSerializer(data=data) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, data) -# self.assertEqual(obj.name, 'source-4') + def test_many_to_many_create(self): + data = {'id': 4, 'name': 'source-4', 'targets': [1, 3]} + serializer = ManyToManySourceSerializer(data=data) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, data) + self.assertEqual(obj.name, 'source-4') -# # Ensure source 4 is added, and everything else is as expected -# queryset = ManyToManySource.objects.all() -# serializer = ManyToManySourceSerializer(queryset, many=True) -# self.assertFalse(serializer.fields['targets'].read_only) -# expected = [ -# {'id': 1, 'name': 'source-1', 'targets': [1]}, -# {'id': 2, 'name': 'source-2', 'targets': [1, 2]}, -# {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]}, -# {'id': 4, 'name': 'source-4', 'targets': [1, 3]}, -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 4 is added, and everything else is as expected + queryset = ManyToManySource.objects.all() + serializer = ManyToManySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'targets': [1]}, + {'id': 2, 'name': 'source-2', 'targets': [1, 2]}, + {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]}, + {'id': 4, 'name': 'source-4', 'targets': [1, 3]}, + ] + self.assertEqual(serializer.data, expected) -# def test_reverse_many_to_many_create(self): -# data = {'id': 4, 'name': 'target-4', 'sources': [1, 3]} -# serializer = ManyToManyTargetSerializer(data=data) -# self.assertFalse(serializer.fields['sources'].read_only) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, data) -# self.assertEqual(obj.name, 'target-4') + def test_reverse_many_to_many_create(self): + data = {'id': 4, 'name': 'target-4', 'sources': [1, 3]} + serializer = ManyToManyTargetSerializer(data=data) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, data) + self.assertEqual(obj.name, 'target-4') -# # Ensure target 4 is added, and everything else is as expected -# queryset = ManyToManyTarget.objects.all() -# serializer = ManyToManyTargetSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, -# {'id': 2, 'name': 'target-2', 'sources': [2, 3]}, -# {'id': 3, 'name': 'target-3', 'sources': [3]}, -# {'id': 4, 'name': 'target-4', 'sources': [1, 3]} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure target 4 is added, and everything else is as expected + queryset = ManyToManyTarget.objects.all() + serializer = ManyToManyTargetSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, + {'id': 2, 'name': 'target-2', 'sources': [2, 3]}, + {'id': 3, 'name': 'target-3', 'sources': [3]}, + {'id': 4, 'name': 'target-4', 'sources': [1, 3]} + ] + self.assertEqual(serializer.data, expected) -# class PKForeignKeyTests(TestCase): -# def setUp(self): -# target = ForeignKeyTarget(name='target-1') -# target.save() -# new_target = ForeignKeyTarget(name='target-2') -# new_target.save() -# for idx in range(1, 4): -# source = ForeignKeySource(name='source-%d' % idx, target=target) -# source.save() +class PKForeignKeyTests(TestCase): + def setUp(self): + target = ForeignKeyTarget(name='target-1') + target.save() + new_target = ForeignKeyTarget(name='target-2') + new_target.save() + for idx in range(1, 4): + source = ForeignKeySource(name='source-%d' % idx, target=target) + source.save() -# def test_foreign_key_retrieve(self): -# queryset = ForeignKeySource.objects.all() -# serializer = ForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': 1}, -# {'id': 2, 'name': 'source-2', 'target': 1}, -# {'id': 3, 'name': 'source-3', 'target': 1} -# ] -# self.assertEqual(serializer.data, expected) + def test_foreign_key_retrieve(self): + queryset = ForeignKeySource.objects.all() + serializer = ForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': 1}, + {'id': 2, 'name': 'source-2', 'target': 1}, + {'id': 3, 'name': 'source-3', 'target': 1} + ] + self.assertEqual(serializer.data, expected) -# def test_reverse_foreign_key_retrieve(self): -# queryset = ForeignKeyTarget.objects.all() -# serializer = ForeignKeyTargetSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, -# {'id': 2, 'name': 'target-2', 'sources': []}, -# ] -# self.assertEqual(serializer.data, expected) + def test_reverse_foreign_key_retrieve(self): + queryset = ForeignKeyTarget.objects.all() + serializer = ForeignKeyTargetSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, + {'id': 2, 'name': 'target-2', 'sources': []}, + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_update(self): -# data = {'id': 1, 'name': 'source-1', 'target': 2} -# instance = ForeignKeySource.objects.get(pk=1) -# serializer = ForeignKeySourceSerializer(instance, data=data) -# self.assertTrue(serializer.is_valid()) -# self.assertEqual(serializer.data, data) -# serializer.save() + def test_foreign_key_update(self): + data = {'id': 1, 'name': 'source-1', 'target': 2} + instance = ForeignKeySource.objects.get(pk=1) + serializer = ForeignKeySourceSerializer(instance, data=data) + self.assertTrue(serializer.is_valid()) + serializer.save() + self.assertEqual(serializer.data, data) -# # Ensure source 1 is updated, and everything else is as expected -# queryset = ForeignKeySource.objects.all() -# serializer = ForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': 2}, -# {'id': 2, 'name': 'source-2', 'target': 1}, -# {'id': 3, 'name': 'source-3', 'target': 1} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 1 is updated, and everything else is as expected + queryset = ForeignKeySource.objects.all() + serializer = ForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': 2}, + {'id': 2, 'name': 'source-2', 'target': 1}, + {'id': 3, 'name': 'source-3', 'target': 1} + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_update_incorrect_type(self): -# data = {'id': 1, 'name': 'source-1', 'target': 'foo'} -# instance = ForeignKeySource.objects.get(pk=1) -# serializer = ForeignKeySourceSerializer(instance, data=data) -# self.assertFalse(serializer.is_valid()) -# self.assertEqual(serializer.errors, {'target': ['Incorrect type. Expected pk value, received %s.' % six.text_type.__name__]}) + def test_foreign_key_update_incorrect_type(self): + data = {'id': 1, 'name': 'source-1', 'target': 'foo'} + instance = ForeignKeySource.objects.get(pk=1) + serializer = ForeignKeySourceSerializer(instance, data=data) + self.assertFalse(serializer.is_valid()) + self.assertEqual(serializer.errors, {'target': ['Incorrect type. Expected pk value, received %s.' % six.text_type.__name__]}) -# def test_reverse_foreign_key_update(self): -# data = {'id': 2, 'name': 'target-2', 'sources': [1, 3]} -# instance = ForeignKeyTarget.objects.get(pk=2) -# serializer = ForeignKeyTargetSerializer(instance, data=data) -# self.assertTrue(serializer.is_valid()) -# # We shouldn't have saved anything to the db yet since save -# # hasn't been called. -# queryset = ForeignKeyTarget.objects.all() -# new_serializer = ForeignKeyTargetSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, -# {'id': 2, 'name': 'target-2', 'sources': []}, -# ] -# self.assertEqual(new_serializer.data, expected) + def test_reverse_foreign_key_update(self): + data = {'id': 2, 'name': 'target-2', 'sources': [1, 3]} + instance = ForeignKeyTarget.objects.get(pk=2) + serializer = ForeignKeyTargetSerializer(instance, data=data) + self.assertTrue(serializer.is_valid()) + # We shouldn't have saved anything to the db yet since save + # hasn't been called. + queryset = ForeignKeyTarget.objects.all() + new_serializer = ForeignKeyTargetSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, + {'id': 2, 'name': 'target-2', 'sources': []}, + ] + self.assertEqual(new_serializer.data, expected) -# serializer.save() -# self.assertEqual(serializer.data, data) + serializer.save() + self.assertEqual(serializer.data, data) -# # Ensure target 2 is update, and everything else is as expected -# queryset = ForeignKeyTarget.objects.all() -# serializer = ForeignKeyTargetSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'target-1', 'sources': [2]}, -# {'id': 2, 'name': 'target-2', 'sources': [1, 3]}, -# ] -# self.assertEqual(serializer.data, expected) + # Ensure target 2 is update, and everything else is as expected + queryset = ForeignKeyTarget.objects.all() + serializer = ForeignKeyTargetSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'target-1', 'sources': [2]}, + {'id': 2, 'name': 'target-2', 'sources': [1, 3]}, + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_create(self): -# data = {'id': 4, 'name': 'source-4', 'target': 2} -# serializer = ForeignKeySourceSerializer(data=data) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, data) -# self.assertEqual(obj.name, 'source-4') + def test_foreign_key_create(self): + data = {'id': 4, 'name': 'source-4', 'target': 2} + serializer = ForeignKeySourceSerializer(data=data) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, data) + self.assertEqual(obj.name, 'source-4') -# # Ensure source 4 is added, and everything else is as expected -# queryset = ForeignKeySource.objects.all() -# serializer = ForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': 1}, -# {'id': 2, 'name': 'source-2', 'target': 1}, -# {'id': 3, 'name': 'source-3', 'target': 1}, -# {'id': 4, 'name': 'source-4', 'target': 2}, -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 4 is added, and everything else is as expected + queryset = ForeignKeySource.objects.all() + serializer = ForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': 1}, + {'id': 2, 'name': 'source-2', 'target': 1}, + {'id': 3, 'name': 'source-3', 'target': 1}, + {'id': 4, 'name': 'source-4', 'target': 2}, + ] + self.assertEqual(serializer.data, expected) -# def test_reverse_foreign_key_create(self): -# data = {'id': 3, 'name': 'target-3', 'sources': [1, 3]} -# serializer = ForeignKeyTargetSerializer(data=data) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, data) -# self.assertEqual(obj.name, 'target-3') + def test_reverse_foreign_key_create(self): + data = {'id': 3, 'name': 'target-3', 'sources': [1, 3]} + serializer = ForeignKeyTargetSerializer(data=data) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, data) + self.assertEqual(obj.name, 'target-3') -# # Ensure target 3 is added, and everything else is as expected -# queryset = ForeignKeyTarget.objects.all() -# serializer = ForeignKeyTargetSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'target-1', 'sources': [2]}, -# {'id': 2, 'name': 'target-2', 'sources': []}, -# {'id': 3, 'name': 'target-3', 'sources': [1, 3]}, -# ] -# self.assertEqual(serializer.data, expected) + # Ensure target 3 is added, and everything else is as expected + queryset = ForeignKeyTarget.objects.all() + serializer = ForeignKeyTargetSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'target-1', 'sources': [2]}, + {'id': 2, 'name': 'target-2', 'sources': []}, + {'id': 3, 'name': 'target-3', 'sources': [1, 3]}, + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_update_with_invalid_null(self): -# data = {'id': 1, 'name': 'source-1', 'target': None} -# instance = ForeignKeySource.objects.get(pk=1) -# serializer = ForeignKeySourceSerializer(instance, data=data) -# self.assertFalse(serializer.is_valid()) -# self.assertEqual(serializer.errors, {'target': ['This field is required.']}) + def test_foreign_key_update_with_invalid_null(self): + data = {'id': 1, 'name': 'source-1', 'target': None} + instance = ForeignKeySource.objects.get(pk=1) + serializer = ForeignKeySourceSerializer(instance, data=data) + self.assertFalse(serializer.is_valid()) + self.assertEqual(serializer.errors, {'target': ['This field may not be null.']}) -# def test_foreign_key_with_empty(self): -# """ -# Regression test for #1072 + def test_foreign_key_with_empty(self): + """ + Regression test for #1072 -# https://github.com/tomchristie/django-rest-framework/issues/1072 -# """ -# serializer = NullableForeignKeySourceSerializer() -# self.assertEqual(serializer.data['target'], None) + https://github.com/tomchristie/django-rest-framework/issues/1072 + """ + serializer = NullableForeignKeySourceSerializer() + self.assertEqual(serializer.data['target'], None) -# class PKNullableForeignKeyTests(TestCase): -# def setUp(self): -# target = ForeignKeyTarget(name='target-1') -# target.save() -# for idx in range(1, 4): -# if idx == 3: -# target = None -# source = NullableForeignKeySource(name='source-%d' % idx, target=target) -# source.save() +class PKNullableForeignKeyTests(TestCase): + def setUp(self): + target = ForeignKeyTarget(name='target-1') + target.save() + for idx in range(1, 4): + if idx == 3: + target = None + source = NullableForeignKeySource(name='source-%d' % idx, target=target) + source.save() -# def test_foreign_key_retrieve_with_null(self): -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': 1}, -# {'id': 2, 'name': 'source-2', 'target': 1}, -# {'id': 3, 'name': 'source-3', 'target': None}, -# ] -# self.assertEqual(serializer.data, expected) + def test_foreign_key_retrieve_with_null(self): + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': 1}, + {'id': 2, 'name': 'source-2', 'target': 1}, + {'id': 3, 'name': 'source-3', 'target': None}, + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_create_with_valid_null(self): -# data = {'id': 4, 'name': 'source-4', 'target': None} -# serializer = NullableForeignKeySourceSerializer(data=data) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, data) -# self.assertEqual(obj.name, 'source-4') + def test_foreign_key_create_with_valid_null(self): + data = {'id': 4, 'name': 'source-4', 'target': None} + serializer = NullableForeignKeySourceSerializer(data=data) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, data) + self.assertEqual(obj.name, 'source-4') -# # Ensure source 4 is created, and everything else is as expected -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': 1}, -# {'id': 2, 'name': 'source-2', 'target': 1}, -# {'id': 3, 'name': 'source-3', 'target': None}, -# {'id': 4, 'name': 'source-4', 'target': None} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 4 is created, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': 1}, + {'id': 2, 'name': 'source-2', 'target': 1}, + {'id': 3, 'name': 'source-3', 'target': None}, + {'id': 4, 'name': 'source-4', 'target': None} + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_create_with_valid_emptystring(self): -# """ -# The emptystring should be interpreted as null in the context -# of relationships. -# """ -# data = {'id': 4, 'name': 'source-4', 'target': ''} -# expected_data = {'id': 4, 'name': 'source-4', 'target': None} -# serializer = NullableForeignKeySourceSerializer(data=data) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, expected_data) -# self.assertEqual(obj.name, 'source-4') + def test_foreign_key_create_with_valid_emptystring(self): + """ + The emptystring should be interpreted as null in the context + of relationships. + """ + data = {'id': 4, 'name': 'source-4', 'target': ''} + expected_data = {'id': 4, 'name': 'source-4', 'target': None} + serializer = NullableForeignKeySourceSerializer(data=data) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, expected_data) + self.assertEqual(obj.name, 'source-4') -# # Ensure source 4 is created, and everything else is as expected -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': 1}, -# {'id': 2, 'name': 'source-2', 'target': 1}, -# {'id': 3, 'name': 'source-3', 'target': None}, -# {'id': 4, 'name': 'source-4', 'target': None} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 4 is created, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': 1}, + {'id': 2, 'name': 'source-2', 'target': 1}, + {'id': 3, 'name': 'source-3', 'target': None}, + {'id': 4, 'name': 'source-4', 'target': None} + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_update_with_valid_null(self): -# data = {'id': 1, 'name': 'source-1', 'target': None} -# instance = NullableForeignKeySource.objects.get(pk=1) -# serializer = NullableForeignKeySourceSerializer(instance, data=data) -# self.assertTrue(serializer.is_valid()) -# self.assertEqual(serializer.data, data) -# serializer.save() + def test_foreign_key_update_with_valid_null(self): + data = {'id': 1, 'name': 'source-1', 'target': None} + instance = NullableForeignKeySource.objects.get(pk=1) + serializer = NullableForeignKeySourceSerializer(instance, data=data) + self.assertTrue(serializer.is_valid()) + serializer.save() + self.assertEqual(serializer.data, data) -# # Ensure source 1 is updated, and everything else is as expected -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': None}, -# {'id': 2, 'name': 'source-2', 'target': 1}, -# {'id': 3, 'name': 'source-3', 'target': None} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 1 is updated, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': None}, + {'id': 2, 'name': 'source-2', 'target': 1}, + {'id': 3, 'name': 'source-3', 'target': None} + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_update_with_valid_emptystring(self): -# """ -# The emptystring should be interpreted as null in the context -# of relationships. -# """ -# data = {'id': 1, 'name': 'source-1', 'target': ''} -# expected_data = {'id': 1, 'name': 'source-1', 'target': None} -# instance = NullableForeignKeySource.objects.get(pk=1) -# serializer = NullableForeignKeySourceSerializer(instance, data=data) -# self.assertTrue(serializer.is_valid()) -# self.assertEqual(serializer.data, expected_data) -# serializer.save() + def test_foreign_key_update_with_valid_emptystring(self): + """ + The emptystring should be interpreted as null in the context + of relationships. + """ + data = {'id': 1, 'name': 'source-1', 'target': ''} + expected_data = {'id': 1, 'name': 'source-1', 'target': None} + instance = NullableForeignKeySource.objects.get(pk=1) + serializer = NullableForeignKeySourceSerializer(instance, data=data) + self.assertTrue(serializer.is_valid()) + serializer.save() + self.assertEqual(serializer.data, expected_data) -# # Ensure source 1 is updated, and everything else is as expected -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': None}, -# {'id': 2, 'name': 'source-2', 'target': 1}, -# {'id': 3, 'name': 'source-3', 'target': None} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 1 is updated, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': None}, + {'id': 2, 'name': 'source-2', 'target': 1}, + {'id': 3, 'name': 'source-3', 'target': None} + ] + self.assertEqual(serializer.data, expected) -# # reverse foreign keys MUST be read_only -# # In the general case they do not provide .remove() or .clear() -# # and cannot be arbitrarily set. + # reverse foreign keys MUST be read_only + # In the general case they do not provide .remove() or .clear() + # and cannot be arbitrarily set. -# # def test_reverse_foreign_key_update(self): -# # data = {'id': 1, 'name': 'target-1', 'sources': [1]} -# # instance = ForeignKeyTarget.objects.get(pk=1) -# # serializer = ForeignKeyTargetSerializer(instance, data=data) -# # self.assertTrue(serializer.is_valid()) -# # self.assertEqual(serializer.data, data) -# # serializer.save() + # def test_reverse_foreign_key_update(self): + # data = {'id': 1, 'name': 'target-1', 'sources': [1]} + # instance = ForeignKeyTarget.objects.get(pk=1) + # serializer = ForeignKeyTargetSerializer(instance, data=data) + # self.assertTrue(serializer.is_valid()) + # self.assertEqual(serializer.data, data) + # serializer.save() -# # # Ensure target 1 is updated, and everything else is as expected -# # queryset = ForeignKeyTarget.objects.all() -# # serializer = ForeignKeyTargetSerializer(queryset, many=True) -# # expected = [ -# # {'id': 1, 'name': 'target-1', 'sources': [1]}, -# # {'id': 2, 'name': 'target-2', 'sources': []}, -# # ] -# # self.assertEqual(serializer.data, expected) + # # Ensure target 1 is updated, and everything else is as expected + # queryset = ForeignKeyTarget.objects.all() + # serializer = ForeignKeyTargetSerializer(queryset, many=True) + # expected = [ + # {'id': 1, 'name': 'target-1', 'sources': [1]}, + # {'id': 2, 'name': 'target-2', 'sources': []}, + # ] + # self.assertEqual(serializer.data, expected) -# class PKNullableOneToOneTests(TestCase): -# def setUp(self): -# target = OneToOneTarget(name='target-1') -# target.save() -# new_target = OneToOneTarget(name='target-2') -# new_target.save() -# source = NullableOneToOneSource(name='source-1', target=new_target) -# source.save() +class PKNullableOneToOneTests(TestCase): + def setUp(self): + target = OneToOneTarget(name='target-1') + target.save() + new_target = OneToOneTarget(name='target-2') + new_target.save() + source = NullableOneToOneSource(name='source-1', target=new_target) + source.save() -# def test_reverse_foreign_key_retrieve_with_null(self): -# queryset = OneToOneTarget.objects.all() -# serializer = NullableOneToOneTargetSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'target-1', 'nullable_source': None}, -# {'id': 2, 'name': 'target-2', 'nullable_source': 1}, -# ] -# self.assertEqual(serializer.data, expected) + def test_reverse_foreign_key_retrieve_with_null(self): + queryset = OneToOneTarget.objects.all() + serializer = NullableOneToOneTargetSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'target-1', 'nullable_source': None}, + {'id': 2, 'name': 'target-2', 'nullable_source': 1}, + ] + self.assertEqual(serializer.data, expected) -# # The below models and tests ensure that serializer fields corresponding -# # to a ManyToManyField field with a user-specified ``through`` model are -# # set to read only +# The below models and tests ensure that serializer fields corresponding +# to a ManyToManyField field with a user-specified ``through`` model are +# set to read only # class ManyToManyThroughTarget(models.Model): @@ -481,7 +478,6 @@ # def test_many_to_many_create(self): # data = {'id': 2, 'name': 'source-2', 'targets': [self.target.pk]} # serializer = ManyToManyThroughSourceSerializer(data=data) -# self.assertTrue(serializer.fields['targets'].read_only) # self.assertTrue(serializer.is_valid()) # obj = serializer.save() # self.assertEqual(obj.name, 'source-2') @@ -490,9 +486,7 @@ # def test_many_to_many_reverse_create(self): # data = {'id': 2, 'name': 'target-2', 'sources': [self.source.pk]} # serializer = ManyToManyThroughTargetSerializer(data=data) -# self.assertTrue(serializer.fields['sources'].read_only) # self.assertTrue(serializer.is_valid()) -# serializer.save() # obj = serializer.save() # self.assertEqual(obj.name, 'target-2') # self.assertEqual(obj.sources.count(), 0) diff --git a/tests/test_relations_slug.py b/tests/test_relations_slug.py index f7a59a957..7bac90460 100644 --- a/tests/test_relations_slug.py +++ b/tests/test_relations_slug.py @@ -1,257 +1,268 @@ -# from django.test import TestCase -# from rest_framework import serializers -# from tests.models import NullableForeignKeySource, ForeignKeySource, ForeignKeyTarget +from django.test import TestCase +from rest_framework import serializers +from tests.models import NullableForeignKeySource, ForeignKeySource, ForeignKeyTarget -# class ForeignKeyTargetSerializer(serializers.ModelSerializer): -# sources = serializers.SlugRelatedField(many=True, slug_field='name') +class ForeignKeyTargetSerializer(serializers.ModelSerializer): + sources = serializers.SlugRelatedField( + slug_field='name', + queryset=ForeignKeySource.objects.all(), + many=True + ) -# class Meta: -# model = ForeignKeyTarget + class Meta: + model = ForeignKeyTarget -# class ForeignKeySourceSerializer(serializers.ModelSerializer): -# target = serializers.SlugRelatedField(slug_field='name') +class ForeignKeySourceSerializer(serializers.ModelSerializer): + target = serializers.SlugRelatedField( + slug_field='name', + queryset=ForeignKeyTarget.objects.all() + ) -# class Meta: -# model = ForeignKeySource + class Meta: + model = ForeignKeySource -# class NullableForeignKeySourceSerializer(serializers.ModelSerializer): -# target = serializers.SlugRelatedField(slug_field='name', required=False) +class NullableForeignKeySourceSerializer(serializers.ModelSerializer): + target = serializers.SlugRelatedField( + slug_field='name', + queryset=ForeignKeyTarget.objects.all(), + allow_null=True + ) -# class Meta: -# model = NullableForeignKeySource + class Meta: + model = NullableForeignKeySource -# # TODO: M2M Tests, FKTests (Non-nullable), One2One -# class SlugForeignKeyTests(TestCase): -# def setUp(self): -# target = ForeignKeyTarget(name='target-1') -# target.save() -# new_target = ForeignKeyTarget(name='target-2') -# new_target.save() -# for idx in range(1, 4): -# source = ForeignKeySource(name='source-%d' % idx, target=target) -# source.save() +# TODO: M2M Tests, FKTests (Non-nullable), One2One +class SlugForeignKeyTests(TestCase): + def setUp(self): + target = ForeignKeyTarget(name='target-1') + target.save() + new_target = ForeignKeyTarget(name='target-2') + new_target.save() + for idx in range(1, 4): + source = ForeignKeySource(name='source-%d' % idx, target=target) + source.save() -# def test_foreign_key_retrieve(self): -# queryset = ForeignKeySource.objects.all() -# serializer = ForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': 'target-1'}, -# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, -# {'id': 3, 'name': 'source-3', 'target': 'target-1'} -# ] -# self.assertEqual(serializer.data, expected) + def test_foreign_key_retrieve(self): + queryset = ForeignKeySource.objects.all() + serializer = ForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': 'target-1'}, + {'id': 2, 'name': 'source-2', 'target': 'target-1'}, + {'id': 3, 'name': 'source-3', 'target': 'target-1'} + ] + self.assertEqual(serializer.data, expected) -# def test_reverse_foreign_key_retrieve(self): -# queryset = ForeignKeyTarget.objects.all() -# serializer = ForeignKeyTargetSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']}, -# {'id': 2, 'name': 'target-2', 'sources': []}, -# ] -# self.assertEqual(serializer.data, expected) + def test_reverse_foreign_key_retrieve(self): + queryset = ForeignKeyTarget.objects.all() + serializer = ForeignKeyTargetSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']}, + {'id': 2, 'name': 'target-2', 'sources': []}, + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_update(self): -# data = {'id': 1, 'name': 'source-1', 'target': 'target-2'} -# instance = ForeignKeySource.objects.get(pk=1) -# serializer = ForeignKeySourceSerializer(instance, data=data) -# self.assertTrue(serializer.is_valid()) -# self.assertEqual(serializer.data, data) -# serializer.save() + def test_foreign_key_update(self): + data = {'id': 1, 'name': 'source-1', 'target': 'target-2'} + instance = ForeignKeySource.objects.get(pk=1) + serializer = ForeignKeySourceSerializer(instance, data=data) + self.assertTrue(serializer.is_valid()) + serializer.save() + self.assertEqual(serializer.data, data) -# # Ensure source 1 is updated, and everything else is as expected -# queryset = ForeignKeySource.objects.all() -# serializer = ForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': 'target-2'}, -# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, -# {'id': 3, 'name': 'source-3', 'target': 'target-1'} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 1 is updated, and everything else is as expected + queryset = ForeignKeySource.objects.all() + serializer = ForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': 'target-2'}, + {'id': 2, 'name': 'source-2', 'target': 'target-1'}, + {'id': 3, 'name': 'source-3', 'target': 'target-1'} + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_update_incorrect_type(self): -# data = {'id': 1, 'name': 'source-1', 'target': 123} -# instance = ForeignKeySource.objects.get(pk=1) -# serializer = ForeignKeySourceSerializer(instance, data=data) -# self.assertFalse(serializer.is_valid()) -# self.assertEqual(serializer.errors, {'target': ['Object with name=123 does not exist.']}) + def test_foreign_key_update_incorrect_type(self): + data = {'id': 1, 'name': 'source-1', 'target': 123} + instance = ForeignKeySource.objects.get(pk=1) + serializer = ForeignKeySourceSerializer(instance, data=data) + self.assertFalse(serializer.is_valid()) + self.assertEqual(serializer.errors, {'target': ['Object with name=123 does not exist.']}) -# def test_reverse_foreign_key_update(self): -# data = {'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']} -# instance = ForeignKeyTarget.objects.get(pk=2) -# serializer = ForeignKeyTargetSerializer(instance, data=data) -# self.assertTrue(serializer.is_valid()) -# # We shouldn't have saved anything to the db yet since save -# # hasn't been called. -# queryset = ForeignKeyTarget.objects.all() -# new_serializer = ForeignKeyTargetSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']}, -# {'id': 2, 'name': 'target-2', 'sources': []}, -# ] -# self.assertEqual(new_serializer.data, expected) + def test_reverse_foreign_key_update(self): + data = {'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']} + instance = ForeignKeyTarget.objects.get(pk=2) + serializer = ForeignKeyTargetSerializer(instance, data=data) + self.assertTrue(serializer.is_valid()) + # We shouldn't have saved anything to the db yet since save + # hasn't been called. + queryset = ForeignKeyTarget.objects.all() + new_serializer = ForeignKeyTargetSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']}, + {'id': 2, 'name': 'target-2', 'sources': []}, + ] + self.assertEqual(new_serializer.data, expected) -# serializer.save() -# self.assertEqual(serializer.data, data) + serializer.save() + self.assertEqual(serializer.data, data) -# # Ensure target 2 is update, and everything else is as expected -# queryset = ForeignKeyTarget.objects.all() -# serializer = ForeignKeyTargetSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'target-1', 'sources': ['source-2']}, -# {'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']}, -# ] -# self.assertEqual(serializer.data, expected) + # Ensure target 2 is update, and everything else is as expected + queryset = ForeignKeyTarget.objects.all() + serializer = ForeignKeyTargetSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'target-1', 'sources': ['source-2']}, + {'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']}, + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_create(self): -# data = {'id': 4, 'name': 'source-4', 'target': 'target-2'} -# serializer = ForeignKeySourceSerializer(data=data) -# serializer.is_valid() -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, data) -# self.assertEqual(obj.name, 'source-4') + def test_foreign_key_create(self): + data = {'id': 4, 'name': 'source-4', 'target': 'target-2'} + serializer = ForeignKeySourceSerializer(data=data) + serializer.is_valid() + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, data) + self.assertEqual(obj.name, 'source-4') -# # Ensure source 4 is added, and everything else is as expected -# queryset = ForeignKeySource.objects.all() -# serializer = ForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': 'target-1'}, -# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, -# {'id': 3, 'name': 'source-3', 'target': 'target-1'}, -# {'id': 4, 'name': 'source-4', 'target': 'target-2'}, -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 4 is added, and everything else is as expected + queryset = ForeignKeySource.objects.all() + serializer = ForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': 'target-1'}, + {'id': 2, 'name': 'source-2', 'target': 'target-1'}, + {'id': 3, 'name': 'source-3', 'target': 'target-1'}, + {'id': 4, 'name': 'source-4', 'target': 'target-2'}, + ] + self.assertEqual(serializer.data, expected) -# def test_reverse_foreign_key_create(self): -# data = {'id': 3, 'name': 'target-3', 'sources': ['source-1', 'source-3']} -# serializer = ForeignKeyTargetSerializer(data=data) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, data) -# self.assertEqual(obj.name, 'target-3') + def test_reverse_foreign_key_create(self): + data = {'id': 3, 'name': 'target-3', 'sources': ['source-1', 'source-3']} + serializer = ForeignKeyTargetSerializer(data=data) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, data) + self.assertEqual(obj.name, 'target-3') -# # Ensure target 3 is added, and everything else is as expected -# queryset = ForeignKeyTarget.objects.all() -# serializer = ForeignKeyTargetSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'target-1', 'sources': ['source-2']}, -# {'id': 2, 'name': 'target-2', 'sources': []}, -# {'id': 3, 'name': 'target-3', 'sources': ['source-1', 'source-3']}, -# ] -# self.assertEqual(serializer.data, expected) + # Ensure target 3 is added, and everything else is as expected + queryset = ForeignKeyTarget.objects.all() + serializer = ForeignKeyTargetSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'target-1', 'sources': ['source-2']}, + {'id': 2, 'name': 'target-2', 'sources': []}, + {'id': 3, 'name': 'target-3', 'sources': ['source-1', 'source-3']}, + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_update_with_invalid_null(self): -# data = {'id': 1, 'name': 'source-1', 'target': None} -# instance = ForeignKeySource.objects.get(pk=1) -# serializer = ForeignKeySourceSerializer(instance, data=data) -# self.assertFalse(serializer.is_valid()) -# self.assertEqual(serializer.errors, {'target': ['This field is required.']}) + def test_foreign_key_update_with_invalid_null(self): + data = {'id': 1, 'name': 'source-1', 'target': None} + instance = ForeignKeySource.objects.get(pk=1) + serializer = ForeignKeySourceSerializer(instance, data=data) + self.assertFalse(serializer.is_valid()) + self.assertEqual(serializer.errors, {'target': ['This field may not be null.']}) -# class SlugNullableForeignKeyTests(TestCase): -# def setUp(self): -# target = ForeignKeyTarget(name='target-1') -# target.save() -# for idx in range(1, 4): -# if idx == 3: -# target = None -# source = NullableForeignKeySource(name='source-%d' % idx, target=target) -# source.save() +class SlugNullableForeignKeyTests(TestCase): + def setUp(self): + target = ForeignKeyTarget(name='target-1') + target.save() + for idx in range(1, 4): + if idx == 3: + target = None + source = NullableForeignKeySource(name='source-%d' % idx, target=target) + source.save() -# def test_foreign_key_retrieve_with_null(self): -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': 'target-1'}, -# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, -# {'id': 3, 'name': 'source-3', 'target': None}, -# ] -# self.assertEqual(serializer.data, expected) + def test_foreign_key_retrieve_with_null(self): + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': 'target-1'}, + {'id': 2, 'name': 'source-2', 'target': 'target-1'}, + {'id': 3, 'name': 'source-3', 'target': None}, + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_create_with_valid_null(self): -# data = {'id': 4, 'name': 'source-4', 'target': None} -# serializer = NullableForeignKeySourceSerializer(data=data) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, data) -# self.assertEqual(obj.name, 'source-4') + def test_foreign_key_create_with_valid_null(self): + data = {'id': 4, 'name': 'source-4', 'target': None} + serializer = NullableForeignKeySourceSerializer(data=data) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, data) + self.assertEqual(obj.name, 'source-4') -# # Ensure source 4 is created, and everything else is as expected -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': 'target-1'}, -# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, -# {'id': 3, 'name': 'source-3', 'target': None}, -# {'id': 4, 'name': 'source-4', 'target': None} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 4 is created, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': 'target-1'}, + {'id': 2, 'name': 'source-2', 'target': 'target-1'}, + {'id': 3, 'name': 'source-3', 'target': None}, + {'id': 4, 'name': 'source-4', 'target': None} + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_create_with_valid_emptystring(self): -# """ -# The emptystring should be interpreted as null in the context -# of relationships. -# """ -# data = {'id': 4, 'name': 'source-4', 'target': ''} -# expected_data = {'id': 4, 'name': 'source-4', 'target': None} -# serializer = NullableForeignKeySourceSerializer(data=data) -# self.assertTrue(serializer.is_valid()) -# obj = serializer.save() -# self.assertEqual(serializer.data, expected_data) -# self.assertEqual(obj.name, 'source-4') + def test_foreign_key_create_with_valid_emptystring(self): + """ + The emptystring should be interpreted as null in the context + of relationships. + """ + data = {'id': 4, 'name': 'source-4', 'target': ''} + expected_data = {'id': 4, 'name': 'source-4', 'target': None} + serializer = NullableForeignKeySourceSerializer(data=data) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + self.assertEqual(serializer.data, expected_data) + self.assertEqual(obj.name, 'source-4') -# # Ensure source 4 is created, and everything else is as expected -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': 'target-1'}, -# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, -# {'id': 3, 'name': 'source-3', 'target': None}, -# {'id': 4, 'name': 'source-4', 'target': None} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 4 is created, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': 'target-1'}, + {'id': 2, 'name': 'source-2', 'target': 'target-1'}, + {'id': 3, 'name': 'source-3', 'target': None}, + {'id': 4, 'name': 'source-4', 'target': None} + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_update_with_valid_null(self): -# data = {'id': 1, 'name': 'source-1', 'target': None} -# instance = NullableForeignKeySource.objects.get(pk=1) -# serializer = NullableForeignKeySourceSerializer(instance, data=data) -# self.assertTrue(serializer.is_valid()) -# self.assertEqual(serializer.data, data) -# serializer.save() + def test_foreign_key_update_with_valid_null(self): + data = {'id': 1, 'name': 'source-1', 'target': None} + instance = NullableForeignKeySource.objects.get(pk=1) + serializer = NullableForeignKeySourceSerializer(instance, data=data) + self.assertTrue(serializer.is_valid()) + serializer.save() + self.assertEqual(serializer.data, data) -# # Ensure source 1 is updated, and everything else is as expected -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': None}, -# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, -# {'id': 3, 'name': 'source-3', 'target': None} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 1 is updated, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': None}, + {'id': 2, 'name': 'source-2', 'target': 'target-1'}, + {'id': 3, 'name': 'source-3', 'target': None} + ] + self.assertEqual(serializer.data, expected) -# def test_foreign_key_update_with_valid_emptystring(self): -# """ -# The emptystring should be interpreted as null in the context -# of relationships. -# """ -# data = {'id': 1, 'name': 'source-1', 'target': ''} -# expected_data = {'id': 1, 'name': 'source-1', 'target': None} -# instance = NullableForeignKeySource.objects.get(pk=1) -# serializer = NullableForeignKeySourceSerializer(instance, data=data) -# self.assertTrue(serializer.is_valid()) -# self.assertEqual(serializer.data, expected_data) -# serializer.save() + def test_foreign_key_update_with_valid_emptystring(self): + """ + The emptystring should be interpreted as null in the context + of relationships. + """ + data = {'id': 1, 'name': 'source-1', 'target': ''} + expected_data = {'id': 1, 'name': 'source-1', 'target': None} + instance = NullableForeignKeySource.objects.get(pk=1) + serializer = NullableForeignKeySourceSerializer(instance, data=data) + self.assertTrue(serializer.is_valid()) + serializer.save() + self.assertEqual(serializer.data, expected_data) -# # Ensure source 1 is updated, and everything else is as expected -# queryset = NullableForeignKeySource.objects.all() -# serializer = NullableForeignKeySourceSerializer(queryset, many=True) -# expected = [ -# {'id': 1, 'name': 'source-1', 'target': None}, -# {'id': 2, 'name': 'source-2', 'target': 'target-1'}, -# {'id': 3, 'name': 'source-3', 'target': None} -# ] -# self.assertEqual(serializer.data, expected) + # Ensure source 1 is updated, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + serializer = NullableForeignKeySourceSerializer(queryset, many=True) + expected = [ + {'id': 1, 'name': 'source-1', 'target': None}, + {'id': 2, 'name': 'source-2', 'target': 'target-1'}, + {'id': 3, 'name': 'source-3', 'target': None} + ] + self.assertEqual(serializer.data, expected) From 6b09e5f2bba9167404ec329fa12c7f0215ca51ac Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 8 Oct 2014 11:22:10 +0100 Subject: [PATCH 129/249] Tests for generic relationships --- rest_framework/relations.py | 2 +- rest_framework/serializers.py | 10 +- tests/test_genericrelations.py | 217 +++++++++++++-------------------- 3 files changed, 91 insertions(+), 138 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index e5bdf60c7..df5025b80 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -49,7 +49,7 @@ class RelatedField(Field): ]) -class StringRelatedField(Field): +class StringRelatedField(RelatedField): """ A read only field that represents its targets using their plain string representation. diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index ed024f87b..3d868a9ee 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -520,11 +520,6 @@ class ModelSerializer(Serializer): ret[field_name] = declared_fields[field_name] continue - elif field_name == api_settings.URL_FIELD_NAME: - # Create the URL field. - field_cls = HyperlinkedIdentityField - kwargs = get_url_kwargs(model) - elif field_name in info.fields_and_pk: # Create regular model fields. model_field = info.fields_and_pk[field_name] @@ -561,6 +556,11 @@ class ModelSerializer(Serializer): field_cls = ReadOnlyField kwargs = {} + elif field_name == api_settings.URL_FIELD_NAME: + # Create the URL field. + field_cls = HyperlinkedIdentityField + kwargs = get_url_kwargs(model) + else: raise ImproperlyConfigured( 'Field name `%s` is not valid for model `%s`.' % diff --git a/tests/test_genericrelations.py b/tests/test_genericrelations.py index a87ea3fdd..380ad91db 100644 --- a/tests/test_genericrelations.py +++ b/tests/test_genericrelations.py @@ -1,151 +1,104 @@ -# from __future__ import unicode_literals -# from django.contrib.contenttypes.models import ContentType -# from django.contrib.contenttypes.generic import GenericRelation, GenericForeignKey -# from django.db import models -# from django.test import TestCase -# from rest_framework import serializers -# from rest_framework.compat import python_2_unicode_compatible +from __future__ import unicode_literals +from django.contrib.contenttypes.models import ContentType +from django.contrib.contenttypes.generic import GenericRelation, GenericForeignKey +from django.db import models +from django.test import TestCase +from rest_framework import serializers +from rest_framework.compat import python_2_unicode_compatible -# @python_2_unicode_compatible -# class Tag(models.Model): -# """ -# Tags have a descriptive slug, and are attached to an arbitrary object. -# """ -# tag = models.SlugField() -# content_type = models.ForeignKey(ContentType) -# object_id = models.PositiveIntegerField() -# tagged_item = GenericForeignKey('content_type', 'object_id') +@python_2_unicode_compatible +class Tag(models.Model): + """ + Tags have a descriptive slug, and are attached to an arbitrary object. + """ + tag = models.SlugField() + content_type = models.ForeignKey(ContentType) + object_id = models.PositiveIntegerField() + tagged_item = GenericForeignKey('content_type', 'object_id') -# def __str__(self): -# return self.tag + def __str__(self): + return self.tag -# @python_2_unicode_compatible -# class Bookmark(models.Model): -# """ -# A URL bookmark that may have multiple tags attached. -# """ -# url = models.URLField() -# tags = GenericRelation(Tag) +@python_2_unicode_compatible +class Bookmark(models.Model): + """ + A URL bookmark that may have multiple tags attached. + """ + url = models.URLField() + tags = GenericRelation(Tag) -# def __str__(self): -# return 'Bookmark: %s' % self.url + def __str__(self): + return 'Bookmark: %s' % self.url -# @python_2_unicode_compatible -# class Note(models.Model): -# """ -# A textual note that may have multiple tags attached. -# """ -# text = models.TextField() -# tags = GenericRelation(Tag) +@python_2_unicode_compatible +class Note(models.Model): + """ + A textual note that may have multiple tags attached. + """ + text = models.TextField() + tags = GenericRelation(Tag) -# def __str__(self): -# return 'Note: %s' % self.text + def __str__(self): + return 'Note: %s' % self.text -# class TestGenericRelations(TestCase): -# def setUp(self): -# self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/') -# Tag.objects.create(tagged_item=self.bookmark, tag='django') -# Tag.objects.create(tagged_item=self.bookmark, tag='python') -# self.note = Note.objects.create(text='Remember the milk') -# Tag.objects.create(tagged_item=self.note, tag='reminder') +class TestGenericRelations(TestCase): + def setUp(self): + self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/') + Tag.objects.create(tagged_item=self.bookmark, tag='django') + Tag.objects.create(tagged_item=self.bookmark, tag='python') + self.note = Note.objects.create(text='Remember the milk') + Tag.objects.create(tagged_item=self.note, tag='reminder') -# def test_generic_relation(self): -# """ -# Test a relationship that spans a GenericRelation field. -# IE. A reverse generic relationship. -# """ + def test_generic_relation(self): + """ + Test a relationship that spans a GenericRelation field. + IE. A reverse generic relationship. + """ -# class BookmarkSerializer(serializers.ModelSerializer): -# tags = serializers.RelatedField(many=True) + class BookmarkSerializer(serializers.ModelSerializer): + tags = serializers.StringRelatedField(many=True) -# class Meta: -# model = Bookmark -# exclude = ('id',) + class Meta: + model = Bookmark + fields = ('tags', 'url') -# serializer = BookmarkSerializer(self.bookmark) -# expected = { -# 'tags': ['django', 'python'], -# 'url': 'https://www.djangoproject.com/' -# } -# self.assertEqual(serializer.data, expected) + serializer = BookmarkSerializer(self.bookmark) + expected = { + 'tags': ['django', 'python'], + 'url': 'https://www.djangoproject.com/' + } + self.assertEqual(serializer.data, expected) -# def test_generic_nested_relation(self): -# """ -# Test saving a GenericRelation field via a nested serializer. -# """ + def test_generic_fk(self): + """ + Test a relationship that spans a GenericForeignKey field. + IE. A forward generic relationship. + """ -# class TagSerializer(serializers.ModelSerializer): -# class Meta: -# model = Tag -# exclude = ('content_type', 'object_id') + class TagSerializer(serializers.ModelSerializer): + tagged_item = serializers.StringRelatedField() -# class BookmarkSerializer(serializers.ModelSerializer): -# tags = TagSerializer(many=True) + class Meta: + model = Tag + fields = ('tag', 'tagged_item') -# class Meta: -# model = Bookmark -# exclude = ('id',) - -# data = { -# 'url': 'https://docs.djangoproject.com/', -# 'tags': [ -# {'tag': 'contenttypes'}, -# {'tag': 'genericrelations'}, -# ] -# } -# serializer = BookmarkSerializer(data=data) -# self.assertTrue(serializer.is_valid()) -# serializer.save() -# self.assertEqual(serializer.object.tags.count(), 2) - -# def test_generic_fk(self): -# """ -# Test a relationship that spans a GenericForeignKey field. -# IE. A forward generic relationship. -# """ - -# class TagSerializer(serializers.ModelSerializer): -# tagged_item = serializers.RelatedField() - -# class Meta: -# model = Tag -# exclude = ('id', 'content_type', 'object_id') - -# serializer = TagSerializer(Tag.objects.all(), many=True) -# expected = [ -# { -# 'tag': 'django', -# 'tagged_item': 'Bookmark: https://www.djangoproject.com/' -# }, -# { -# 'tag': 'python', -# 'tagged_item': 'Bookmark: https://www.djangoproject.com/' -# }, -# { -# 'tag': 'reminder', -# 'tagged_item': 'Note: Remember the milk' -# } -# ] -# self.assertEqual(serializer.data, expected) - -# def test_restore_object_generic_fk(self): -# """ -# Ensure an object with a generic foreign key can be restored. -# """ - -# class TagSerializer(serializers.ModelSerializer): -# class Meta: -# model = Tag -# exclude = ('content_type', 'object_id') - -# serializer = TagSerializer() - -# bookmark = Bookmark(url='http://example.com') -# attrs = {'tagged_item': bookmark, 'tag': 'example'} - -# tag = serializer.restore_object(attrs) -# self.assertEqual(tag.tagged_item, bookmark) + serializer = TagSerializer(Tag.objects.all(), many=True) + expected = [ + { + 'tag': 'django', + 'tagged_item': 'Bookmark: https://www.djangoproject.com/' + }, + { + 'tag': 'python', + 'tagged_item': 'Bookmark: https://www.djangoproject.com/' + }, + { + 'tag': 'reminder', + 'tagged_item': 'Note: Remember the milk' + } + ] + self.assertEqual(serializer.data, expected) From af0f01c5b6597fe2f146268f7632f7e3954d17c2 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 8 Oct 2014 11:23:40 +0100 Subject: [PATCH 130/249] Move generic relation tests --- tests/{test_genericrelations.py => test_relations_generic.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tests/{test_genericrelations.py => test_relations_generic.py} (100%) diff --git a/tests/test_genericrelations.py b/tests/test_relations_generic.py similarity index 100% rename from tests/test_genericrelations.py rename to tests/test_relations_generic.py From 0cbb57b40fdb073c7ca09c9d1078926260c646db Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 8 Oct 2014 12:17:30 +0100 Subject: [PATCH 131/249] Tweak pre/post save hooks. Return instance in .update(). --- docs/topics/3.0-announcement.md | 26 ++++++++++++++++++-------- rest_framework/mixins.py | 13 ++++++++----- rest_framework/serializers.py | 24 ++++++++++++++---------- 3 files changed, 40 insertions(+), 23 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 4a7815032..89817ea5d 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -116,11 +116,12 @@ This would now be split out into two separate methods. instance.language = validated_data.get('language', instance.language) instance.style = validated_data.get('style', instance.style) instance.save() + return instance def create(self, validated_data): return Snippet.objects.create(**validated_data) -Note that the `.create` method should return the newly created object instance. +Note that these methods should return the newly created object instance. #### Use `.validated_data` instead of `.object`. @@ -592,18 +593,27 @@ The `UniqueTogetherValidator` should be applied to a serializer, and takes a `qu The view logic for the default method handlers has been significantly simplified, due to the new serializers API. -#### Removal of pre/post save hooks. +#### Changes to pre/post save hooks. -The following method hooks no longer exist on the new, simplified, generic views: `pre_save`, `post_save`, `pre_delete`, `post_delete`. +The `pre_save` and `post_save` hooks no longer exist, but are replaced with `perform_create(self, serializer)` and `perform_update(self, serializer)`. -If you do need custom behavior, you might choose to instead override the `.save()` method on your serializer class. For example: +These method should save the object instance by calling `serializer.save()`, adding in any explicit additional arguments as required. They may also perform any custom pre-save or post-save behavior. - def save(self, *args, **kwargs): - instance = super(MySerializer).save(*args, **kwarg) +For example: + + def perform_create(self, serializer): + # Include the owner attribute directly, rather than from request data. + instance = serializer.save(owner=self.request.user) + # Perform a custom post-save action. send_email(instance.to_email, instance.message) - return instance -Alternatively write your view logic exlpicitly, or tie your pre/post save behavior into the model class or model manager. +The `pre_delete` and `post_delete` hooks no longer exist, and are replaced with `.perform_destroy(self, instance)`, which should delete the instance and perform any custom actions. + + def perform_destroy(self, instance): + # Perform a custom pre-delete action. + send_deletion_alert(user=instance.created_by, deleted=instance) + # Delete the object instance. + instance.delete() #### Removal of view attributes. diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index 03ebb0341..4c62debb0 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -20,11 +20,11 @@ class CreateModelMixin(object): def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) - self.create_valid(serializer) + self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) - def create_valid(self, serializer): + def perform_create(self, serializer): serializer.save() def get_success_headers(self, data): @@ -67,10 +67,10 @@ class UpdateModelMixin(object): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) - self.update_valid(serializer) + self.preform_update(serializer) return Response(serializer.data) - def update_valid(self, serializer): + def preform_update(self, serializer): serializer.save() def partial_update(self, request, *args, **kwargs): @@ -84,9 +84,12 @@ class DestroyModelMixin(object): """ def destroy(self, request, *args, **kwargs): instance = self.get_object() - instance.delete() + self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT) + def perform_destroy(self, instance): + instance.delete() + # The AllowPUTAsCreateMixin was previously the default behaviour # for PUT requests. This has now been removed and must be *explicitly* diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 3d868a9ee..e7cd50d67 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -83,7 +83,10 @@ class BaseSerializer(Field): ) if self.instance is not None: - self.update(self.instance, validated_data) + self.instance = self.update(self.instance, validated_data) + assert self.instance is not None, ( + '`update()` did not return an object instance.' + ) else: self.instance = self.create(validated_data) assert self.instance is not None, ( @@ -444,19 +447,19 @@ class ModelSerializer(Serializer): self.validators.extend(validators) self._kwargs['validators'] = validators - def create(self, attrs): + def create(self, validated_attrs): ModelClass = self.Meta.model - # Remove many-to-many relationships from attrs. + # Remove many-to-many relationships from validated_attrs. # They are not valid arguments to the default `.create()` method, # as they require that the instance has already been saved. info = model_meta.get_field_info(ModelClass) many_to_many = {} for field_name, relation_info in info.relations.items(): - if relation_info.to_many and (field_name in attrs): - many_to_many[field_name] = attrs.pop(field_name) + if relation_info.to_many and (field_name in validated_attrs): + many_to_many[field_name] = validated_attrs.pop(field_name) - instance = ModelClass.objects.create(**attrs) + instance = ModelClass.objects.create(**validated_attrs) # Save many-to-many relationships after the instance is created. if many_to_many: @@ -465,10 +468,11 @@ class ModelSerializer(Serializer): return instance - def update(self, obj, attrs): - for attr, value in attrs.items(): - setattr(obj, attr, value) - obj.save() + def update(self, instance, validated_attrs): + for attr, value in validated_attrs.items(): + setattr(instance, attr, value) + instance.save() + return instance def get_unique_together_validators(self): field_names = set([ From 28f3b314f12cbff33c55602c2c5f5f5cce956171 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 8 Oct 2014 12:36:28 +0100 Subject: [PATCH 132/249] .validate() returning validated data. transform_<field> hooks. --- rest_framework/serializers.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index e7cd50d67..8513428cf 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -299,7 +299,8 @@ class Serializer(BaseSerializer): value = self.to_internal_value(data) try: self.run_validators(value) - self.validate(value) + value = self.validate(value) + assert value is not None, '.validate() should return the validated data' except ValidationError as exc: raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: exc.messages @@ -341,7 +342,12 @@ class Serializer(BaseSerializer): fields = [field for field in self.fields.values() if not field.write_only] for field in fields: - ret[field.field_name] = field.get_field_representation(instance) + value = field.get_field_representation(instance) + transform_method = getattr(self, 'transform_' + field.field_name, None) + if transform_method is not None: + value = transform_method(value) + + ret[field.field_name] = value return ret From 14ae52a24e93063f77c6010269bf9cd3316627fe Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 8 Oct 2014 16:09:37 +0100 Subject: [PATCH 133/249] More gradual deprecation --- docs/topics/3.0-announcement.md | 26 +++++----- rest_framework/request.py | 16 ++++++ rest_framework/serializers.py | 71 ++++++++++++++++++++++++++- rest_framework/utils/field_mapping.py | 22 ++++----- rest_framework/utils/model_meta.py | 4 +- 5 files changed, 113 insertions(+), 26 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 89817ea5d..6520f2bdd 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -8,10 +8,9 @@ See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-fr The most notable outstanding issues still to be resolved on the `version-3.0` branch are as follows: -* Forms support for serializers and in the browsable API. +* Finish forms support for serializers and in the browsable API. * Optimisations for serializing primary keys. * Refine style of validation errors in some cases, such as validation errors in `ListField`. -* `.transform_<field>()` method on serializers. **Your feedback on the upgrade process and 3.0 changes is hugely important!** @@ -48,12 +47,13 @@ Below is an in-depth guide to the API changes and migration notes for 3.0. #### The `.data` and `.query_params` properties. -The usage of `request.DATA` and `request.FILES` is now discouraged in favor of a single `request.data` attribute that contains *all* the parsed data. +The usage of `request.DATA` and `request.FILES` is now pending deprecation in favor of a single `request.data` attribute that contains *all* the parsed data. -Having separate attributes is reasonable for web applications that only ever parse URL encoded or MultiPart requests, but makes less sense for the general-purpose request parsing that REST framework supports. +Having separate attributes is reasonable for web applications that only ever parse url-encoded or multipart requests, but makes less sense for the general-purpose request parsing that REST framework supports. You may now pass all the request data to a serializer class in a single argument: + # Do this... ExampleSerializer(data=request.data) Instead of passing the files argument separately: @@ -62,7 +62,7 @@ Instead of passing the files argument separately: ExampleSerializer(data=request.DATA, files=request.FILES) -The usage of `request.QUERY_PARAMS` is now discouraged in favor of the lowercased `request.query_params`. +The usage of `request.QUERY_PARAMS` is now pending deprecation in favor of the lowercased `request.query_params`. ## Serializers @@ -73,7 +73,7 @@ Previously the serializers used a two-step object creation, as follows: 1. Validating the data would create an object instance. This instance would be available as `serializer.object`. 2. Calling `serializer.save()` would then save the object instance to the database. -This style is in line with how the `ModelForm` class works in Django, but is problematic for a number of reasons: +This style is in-line with how the `ModelForm` class works in Django, but is problematic for a number of reasons: * Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumented state on the object instance, or kept as state on the serializer instance so that it could be used when `.save()` is called. * Instantiating model instances directly means that you cannot use model manager classes for instance creation, eg `ExampleModel.objects.create(...)`. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints. @@ -109,7 +109,7 @@ The following example from the tutorial previously used `restore_object()` to ha This would now be split out into two separate methods. - def update(self, instance, validated_data) + def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) @@ -211,28 +211,30 @@ The `exclude` option on `ModelSerializer` is no longer available. You should use #### The `extra_kwargs` option. -The `read_only_fields` and `write_only_fields` options on `ModelSerializer` have been removed and replaced with a more generic `extra_kwargs`. +The `write_only_fields` option on `ModelSerializer` has been moved to `PendingDeprecation` and replaced with a more generic `extra_kwargs`. class MySerializer(serializer.ModelSerializer): class Meta: model = MyModel fields = ('id', 'email', 'notes', 'is_admin') extra_kwargs = { - 'is_admin': {'read_only': True} + 'is_admin': {'write_only': True} } Alternatively, specify the field explicitly on the serializer class: class MySerializer(serializer.ModelSerializer): - is_admin = serializers.BooleanField(read_only=True) + is_admin = serializers.BooleanField(write_only=True) class Meta: model = MyModel fields = ('id', 'email', 'notes', 'is_admin') +The `read_only_fields` option remains as a convenient shortcut for the more common case. + #### Changes to `HyperlinkedModelSerializer`. -The `view_name` and `lookup_field` options have been removed. They are no longer required, as you can use the `extra_kwargs` argument instead: +The `view_name` and `lookup_field` options have been moved to `PendingDeprecation`. They are no longer required, as you can use the `extra_kwargs` argument instead: class MySerializer(serializer.HyperlinkedModelSerializer): class Meta: @@ -633,7 +635,7 @@ If you need to restore the previous behavior you can include the `AllowPUTAsCrea The generic views now raise `ValidationError` for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a `400 Bad Request` response directly. -This change means that you can now easily cusomize the style of error responses across your entire API, without having to modify any of the generic views. +This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views. ## The metadata API diff --git a/rest_framework/request.py b/rest_framework/request.py index d80baa705..d43527421 100644 --- a/rest_framework/request.py +++ b/rest_framework/request.py @@ -18,6 +18,7 @@ from rest_framework import HTTP_HEADER_ENCODING from rest_framework import exceptions from rest_framework.compat import BytesIO from rest_framework.settings import api_settings +import warnings def is_form_media_type(media_type): @@ -209,6 +210,11 @@ class Request(object): """ Synonym for `.query_params`, for backwards compatibility. """ + warnings.warn( + "`request.QUERY_PARAMS` is pending deprecation. Use `request.query_params` instead.", + PendingDeprecationWarning, + stacklevel=1 + ) return self._request.GET @property @@ -225,6 +231,11 @@ class Request(object): Similar to usual behaviour of `request.POST`, except that it handles arbitrary parsers, and also works on methods other than POST (eg PUT). """ + warnings.warn( + "`request.DATA` is pending deprecation. Use `request.data` instead.", + PendingDeprecationWarning, + stacklevel=1 + ) if not _hasattr(self, '_data'): self._load_data_and_files() return self._data @@ -237,6 +248,11 @@ class Request(object): Similar to usual behaviour of `request.FILES`, except that it handles arbitrary parsers, and also works on methods other than POST (eg PUT). """ + warnings.warn( + "`request.FILES` is pending deprecation. Use `request.data` instead.", + PendingDeprecationWarning, + stacklevel=1 + ) if not _hasattr(self, '_files'): self._load_data_and_files() return self._files diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 8513428cf..9fcbcba76 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -25,6 +25,7 @@ from rest_framework.utils.field_mapping import ( from rest_framework.validators import UniqueTogetherValidator import copy import inspect +import warnings # Note: We do the following so that users of the framework can use this style: # @@ -517,12 +518,24 @@ class ModelSerializer(Serializer): depth = getattr(self.Meta, 'depth', 0) extra_kwargs = getattr(self.Meta, 'extra_kwargs', {}) + extra_kwargs = self._include_additional_options(extra_kwargs) + # Retrieve metadata about fields & relationships on the model class. info = model_meta.get_field_info(model) # Use the default set of fields 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: + warnings.warn( + "The `Meta.exclude` option is pending deprecation. " + "Use the explicit `Meta.fields` instead.", + PendingDeprecationWarning, + stacklevel=3 + ) + for field_name in exclude: + fields.remove(field_name) for field_name in fields: if field_name in declared_fields: @@ -589,13 +602,69 @@ class ModelSerializer(Serializer): ) # Populate any kwargs defined in `Meta.extra_kwargs` - kwargs.update(extra_kwargs.get(field_name, {})) + 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' + ]: + kwargs.pop(attr, None) + kwargs.update(extras) # Create the serializer field. ret[field_name] = field_cls(**kwargs) return ret + 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: + kwargs = extra_kwargs.get(field_name, {}) + kwargs['read_only'] = True + extra_kwargs[field_name] = kwargs + + # These are all pending deprecation. + write_only_fields = getattr(self.Meta, 'write_only_fields', None) + if write_only_fields is not None: + warnings.warn( + "The `Meta.write_only_fields` option is pending deprecation. " + "Use `Meta.extra_kwargs={<field_name>: {'write_only': True}}` instead.", + PendingDeprecationWarning, + stacklevel=3 + ) + for field_name in write_only_fields: + kwargs = extra_kwargs.get(field_name, {}) + kwargs['write_only'] = True + extra_kwargs[field_name] = kwargs + + view_name = getattr(self.Meta, 'view_name', None) + if view_name is not None: + warnings.warn( + "The `Meta.view_name` option is pending deprecation. " + "Use `Meta.extra_kwargs={'url': {'view_name': ...}}` instead.", + PendingDeprecationWarning, + stacklevel=3 + ) + kwargs = extra_kwargs.get(field_name, {}) + kwargs['view_name'] = view_name + extra_kwargs[api_settings.URL_FIELD_NAME] = kwargs + + lookup_field = getattr(self.Meta, 'lookup_field', None) + if lookup_field is not None: + warnings.warn( + "The `Meta.lookup_field` option is pending deprecation. " + "Use `Meta.extra_kwargs={'url': {'lookup_field': ...}}` instead.", + PendingDeprecationWarning, + stacklevel=3 + ) + kwargs = extra_kwargs.get(field_name, {}) + kwargs['lookup_field'] = lookup_field + extra_kwargs[api_settings.URL_FIELD_NAME] = kwargs + + return extra_kwargs + def _get_default_field_names(self, declared_fields, model_info): return ( [model_info.pk.name] + diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index fd6da699f..6db371469 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -71,6 +71,17 @@ def get_field_kwargs(field_name, model_field): if model_field.help_text: kwargs['help_text'] = model_field.help_text + max_digits = getattr(model_field, 'max_digits', None) + if max_digits is not None: + kwargs['max_digits'] = max_digits + + decimal_places = getattr(model_field, 'decimal_places', None) + if decimal_places is not None: + kwargs['decimal_places'] = decimal_places + + if isinstance(model_field, models.TextField): + kwargs['style'] = {'type': 'textarea'} + if isinstance(model_field, models.AutoField) or not model_field.editable: # If this field is read-only, then return early. # Further keyword arguments are not valid. @@ -86,9 +97,6 @@ def get_field_kwargs(field_name, model_field): kwargs['choices'] = model_field.flatchoices return kwargs - if isinstance(model_field, models.TextField): - kwargs['style'] = {'type': 'textarea'} - if model_field.null and not isinstance(model_field, models.NullBooleanField): kwargs['allow_null'] = True @@ -171,14 +179,6 @@ def get_field_kwargs(field_name, model_field): validator = UniqueValidator(queryset=model_field.model._default_manager) validator_kwarg.append(validator) - max_digits = getattr(model_field, 'max_digits', None) - if max_digits is not None: - kwargs['max_digits'] = max_digits - - decimal_places = getattr(model_field, 'decimal_places', None) - if decimal_places is not None: - kwargs['decimal_places'] = decimal_places - if validator_kwarg: kwargs['validators'] = validator_kwarg diff --git a/rest_framework/utils/model_meta.py b/rest_framework/utils/model_meta.py index b6c41174e..7a95bcdd1 100644 --- a/rest_framework/utils/model_meta.py +++ b/rest_framework/utils/model_meta.py @@ -107,8 +107,8 @@ def get_field_info(model): related=relation.model, to_many=True, has_through_model=( - hasattr(relation.field.rel, 'through') and - not relation.field.rel.through._meta.auto_created + (getattr(relation.field.rel, 'through', None) is not None) + and not relation.field.rel.through._meta.auto_created ) ) From 4c015df28cfb7dc7cf29f6dc4985c57e1f5cdc5d Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 8 Oct 2014 16:43:33 +0100 Subject: [PATCH 134/249] Tweaks --- docs/topics/3.0-announcement.md | 18 ++++++++++++++++++ rest_framework/relations.py | 3 ++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 6520f2bdd..26d261edd 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -144,6 +144,24 @@ The corresponding code would now look like this: logging.info('Creating ticket "%s"' % name) serializer.save(user=request.user) # Include the user when saving. +#### Change to `validate_<field_name>`. + +The `validate_<field_name>` method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field: + + def validate_score(self, attrs, source): + if attrs[score] % 10 != 0: + raise ValidationError('This field should be a multiple of ten.') + return attrs + +This is now simplified slightly, and the method hooks simply take the value to be validated, and return it's validated value. + + def validate_score(self, value): + if value % 10 != 0: + raise ValidationError('This field should be a multiple of ten.') + return value + +Any ad-hoc validation that applies to more than one field should go in the `.validate(self, attrs)` method as usual. + #### Limitations of ModelSerializer validation. This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes. diff --git a/rest_framework/relations.py b/rest_framework/relations.py index df5025b80..e9dd7ddea 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -264,9 +264,10 @@ class ManyRelation(Field): ] def to_representation(self, obj): + iterable = obj.all() if (hasattr(obj, 'all')) else obj return [ self.child_relation.to_representation(value) - for value in obj.all() + for value in iterable ] @property From 5ead8dc89d1a99d6189170dc8dac19cdc8ba7750 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 8 Oct 2014 16:59:52 +0100 Subject: [PATCH 135/249] Support empty file fields --- rest_framework/fields.py | 2 ++ tests/test_fields.py | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 5fb0ec8d7..f86f66266 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -913,6 +913,8 @@ class FileField(Field): def to_representation(self, value): if self.use_url: + if not value: + return None url = settings.MEDIA_URL + value.url request = self.context.get('request', None) if request is not None: diff --git a/tests/test_fields.py b/tests/test_fields.py index bbd9f93d8..eaa0a3c83 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -879,7 +879,8 @@ class TestFileField(FieldValues): (MockFile(name='x' * 100, size=10), ['Ensure this filename has at most 10 characters (it has 100).']) ] outputs = [ - (MockFile(name='example.txt', url='/example.txt'), '/example.txt') + (MockFile(name='example.txt', url='/example.txt'), '/example.txt'), + ('', None) ] field = fields.FileField(max_length=10) From f7d43f530a94e686d2f93781471b9ac4e90d0f58 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 8 Oct 2014 17:03:14 +0100 Subject: [PATCH 136/249] Limit blank string -> None to just be on relational fields --- rest_framework/fields.py | 4 ---- rest_framework/relations.py | 8 +++++++- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index f86f66266..b371c7d0a 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -110,7 +110,6 @@ class Field(object): default_validators = [] default_empty_html = empty initial = None - coerce_blank_to_null = True def __init__(self, read_only=False, write_only=False, required=None, default=empty, initial=empty, source=None, @@ -248,9 +247,6 @@ class Field(object): self.fail('required') return self.get_default() - if data == '' and self.coerce_blank_to_null: - data = None - if data is None: if not self.allow_null: self.fail('null') diff --git a/rest_framework/relations.py b/rest_framework/relations.py index e9dd7ddea..c1e5aa187 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -1,5 +1,5 @@ from rest_framework.compat import smart_text, urlparse -from rest_framework.fields import Field +from rest_framework.fields import empty, Field from rest_framework.reverse import reverse from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch, Resolver404 @@ -31,6 +31,12 @@ class RelatedField(Field): ) return super(RelatedField, cls).__new__(cls, *args, **kwargs) + def run_validation(self, data=empty): + # We force empty strings to None values for relational fields. + if data == '': + data = None + return super(RelatedField, self).run_validation(data) + def get_queryset(self): queryset = self.queryset if isinstance(queryset, QuerySet): From a58cfe167d837d34994b50f52098c552f6b0860e Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 9 Oct 2014 09:38:03 +0100 Subject: [PATCH 137/249] Update tutorial for 3.0 --- docs/tutorial/1-serialization.md | 81 ++++++++++--------- .../4-authentication-and-permissions.md | 14 ++-- 2 files changed, 51 insertions(+), 44 deletions(-) diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index b0565d91a..db5b9ea7b 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -41,20 +41,7 @@ Once that's done we can create an app that we'll use to create a simple Web API. python manage.py startapp snippets -The simplest way to get up and running will probably be to use an `sqlite3` database for the tutorial. Edit the `tutorial/settings.py` file, and set the default database `"ENGINE"` to `"sqlite3"`, and `"NAME"` to `"tmp.db"`. - - DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': 'tmp.db', - 'USER': '', - 'PASSWORD': '', - 'HOST': '', - 'PORT': '', - } - } - -We'll also need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. +We'll need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. Let's edit the `tutorial/settings.py` file: INSTALLED_APPS = ( ... @@ -72,7 +59,7 @@ Okay, we're ready to roll. ## Creating a model to work with -For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself. +For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets/models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself. from django.db import models from pygments.lexers import get_all_lexers @@ -98,9 +85,10 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni class Meta: ordering = ('created',) -Don't forget to sync the database for the first time. +We'll also need to create an initial migration for our snippet model, and sync the database for the first time. - python manage.py syncdb + python manage.py makemigrations snippets + python manage.py migrate ## Creating a Serializer class @@ -112,40 +100,39 @@ The first thing we need to get started on our Web API is to provide a way of ser class SnippetSerializer(serializers.Serializer): - pk = serializers.Field() # Note: `Field` is an untyped read-only field. + pk = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, max_length=100) - code = serializers.CharField(widget=widgets.Textarea, - max_length=100000) + code = serializers.CharField(style={'type': 'textarea'}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') - def restore_object(self, attrs, instance=None): + def create(self, validated_attrs): """ - Create or update a new snippet instance, given a dictionary - of deserialized field values. - - Note that if we don't define this method, then deserializing - data will simply return a dictionary of items. + Create and return a new `Snippet` instance, given the validated data. """ - if instance: - # Update existing instance - instance.title = attrs.get('title', instance.title) - instance.code = attrs.get('code', instance.code) - instance.linenos = attrs.get('linenos', instance.linenos) - instance.language = attrs.get('language', instance.language) - instance.style = attrs.get('style', instance.style) - return instance + return Snippet.objects.create(**validated_attrs) - # Create new instance - return Snippet(**attrs) + def update(self, instance, validated_attrs): + """ + Update and return an existing `Snippet` instance, given the validated data. + """ + instance.title = validated_attrs.get('title', instance.title) + instance.code = validated_attrs.get('code', instance.code) + instance.linenos = validated_attrs.get('linenos', instance.linenos) + instance.language = validated_attrs.get('language', instance.language) + instance.style = validated_attrs.get('style', instance.style) + instance.save() + return instance -The first part of the serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data. +The first part of the serializer class defines the fields that get serialized/deserialized. The `create()` and `update()` methods define how fully fledged instances are created or modified when calling `serializer.save()` -Notice that we can also use various attributes that would typically be used on form fields, such as `widget=widgets.Textarea`. These can be used to control how the serializer should render when displayed as an HTML form. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial. +A serializer class is very similar to a Django `Form` class, and includes similar validation flags on the various fields, such as `required`, `max_length` and `default`. + +The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The `style={'type': 'textarea'}` flag above is equivelent to using `widget=widgets.Textarea` on a Django `Form` class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial. We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit. @@ -219,6 +206,24 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer` model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style') +Once nice property that serializers have is that you can inspect all the fields an serializer instance, by printing it's representation. Open the Django shell with `python manange.py shell`, then try the following: + + >>> from snippets.serializers import SnippetSerializer + >>> serializer = SnippetSerializer() + >>> print repr(serializer) # In python 3 use `print(repr(serializer))` + SnippetSerializer(): + id = IntegerField(label='ID', read_only=True) + title = CharField(allow_blank=True, max_length=100, required=False) + code = CharField(style={'type': 'textarea'}) + linenos = BooleanField(required=False) + language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')... + style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')... + +It's important to remember that `ModelSerializer` classes don't do anything particularly magically, they are simply a shortcut to creating a serializer class with: + +* An automatically determined set of fields. +* Simple default implementations for the `create()` and `update()` methods. + ## Writing regular Django views using our Serializer Let's see how we can write some API views using our new Serializer class. diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 9120e2547..adab1b55a 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -92,24 +92,26 @@ Finally we need to add those views into the API, by referencing them from the UR Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request. -The way we deal with that is by overriding a `.pre_save()` method on our snippet views, that allows us to handle any information that is implicit in the incoming request or requested URL. +The way we deal with that is by overriding a `.perform_create()` method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL. -On **both** the `SnippetList` and `SnippetDetail` view classes, add the following method: +On the `SnippetList` view class, add the following method: - def pre_save(self, obj): - obj.owner = self.request.user + def perform_create(self, serializer): + serializer.save(owner=self.request.user) + +The `create()` method of our serializer will now be passed an additional `'owner'` field, along with the validated data from the request. ## Updating our serializer Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition in `serializers.py`: - owner = serializers.Field(source='owner.username') + owner = serializers.ReadOnlyField(source='owner.username') **Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class. This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language. -The field we've added is the untyped `Field` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `Field` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. +The field we've added is the untyped `ReadOnlyField` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `ReadOnlyField` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also used `CharField(read_only=True)` here. ## Adding required permissions to views From 5f4cc52ef5c0f603420c6ea809594710a372d336 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 9 Oct 2014 10:11:44 +0100 Subject: [PATCH 138/249] Tweaking --- rest_framework/validators.py | 6 ++++++ tests/test_validators.py | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/rest_framework/validators.py b/rest_framework/validators.py index 5bb69ad88..f76faaa4b 100644 --- a/rest_framework/validators.py +++ b/rest_framework/validators.py @@ -12,6 +12,9 @@ from rest_framework.utils.representation import smart_repr class UniqueValidator: + """ + Validator that corresponds to `unique=True` on a model field. + """ # Validators with `requires_context` will have the field instance # passed to them when the field is instantiated. requires_context = True @@ -46,6 +49,9 @@ class UniqueValidator: class UniqueTogetherValidator: + """ + Validator that corresponds to `unique_together = (...)` on a model class. + """ requires_context = True message = _('The fields {field_names} must make a unique set.') diff --git a/tests/test_validators.py b/tests/test_validators.py index ac04d2b4c..1d0814115 100644 --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -131,7 +131,7 @@ class TestUniquenessTogetherValidation(TestCase): 'position': 1 } - def test_ignore_exlcuded_fields(self): + def test_ignore_excluded_fields(self): """ When model fields are not included in a serializer, then uniqueness validtors should not be added for that field. From 6637b2fae0dab65447ff0bfd5ac0ba68644446eb Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 9 Oct 2014 11:08:26 +0100 Subject: [PATCH 139/249] Document the Metadata API --- docs/api-guide/metadata.md | 103 +++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 docs/api-guide/metadata.md diff --git a/docs/api-guide/metadata.md b/docs/api-guide/metadata.md new file mode 100644 index 000000000..c3f036b75 --- /dev/null +++ b/docs/api-guide/metadata.md @@ -0,0 +1,103 @@ +<a class="github" href="metadata.py"></a> + +# Metadata + +> [The `OPTIONS`] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. +> +> — [RFC7231, Section 4.3.7.][cite] + +REST framework includes a configurable mechanism for determining how your API should respond to `OPTIONS` requests. This allows you to return API schema or other resource information. + +There are not currently any widely adopted conventions for exactly what style of response should be returned for HTTP `OPTIONS` requests, so we provide an ad-hoc style that returns some useful information. + +Here's an example response that demonstrates the information that is returned by default. + + HTTP 200 OK + Allow: GET, POST, HEAD, OPTIONS + Content-Type: application/json + + { + "name": "To Do List", + "description": "List existing 'To Do' items, or create a new item.", + "renders": [ + "application/json", + "text/html" + ], + "parses": [ + "application/json", + "application/x-www-form-urlencoded", + "multipart/form-data" + ], + "actions": { + "POST": { + "note": { + "type": "string", + "required": false, + "read_only": false, + "label": "title", + "max_length": 100 + } + } + } + } + +## Setting the metadata scheme + +You can set the metadata class globally using the `'DEFAULT_METADATA_CLASS'` settings key: + + REST_FRAMEWORK = { + 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata' + } + +Or you can set the metadata class individually for a view: + + class APIRoot(APIView): + metadata_class = APIRootMetadata + + def get(self, request, format=None): + return Response({ + ... + }) + +The REST framework package only includes a single metadata class implementation, named `SimpleMetadata`. If you want to use an alternative style you'll need to implement a custom metadata class. + +## Creating schema endpoints + +If you have specific requirements for creating schema endpoints that are accessed with regular `GET` requests, you might consider re-using the metadata API for doing so. + +For example, the following additional route could be used on a viewset to provide a linkable schema endpoint. + + @list_route(methods=['GET']) + def schema(self, request): + meta = self.metadata_class() + data = meta.determine_metadata(request, self) + return Response(data) + +There are a couple of reasons that you might choose to take this approach, including that `OPTIONS` responses [are not cacheable][no-options]. + +--- + +# Custom metadata classes + +If you want to provide a custom metadata class you should override `BaseMetadata` and implement the `determine_metadata(self, request, view)` method. + +Useful things that you might want to do could include returning schema information, using a format such as [JSON schema][json-schema], or returning debug information to admin users. + +## Example + +The following class could be used to limit the information that is returned to `OPTIONS` requests. + + class MinimalMetadata(BaseMetadata): + """ + Don't include field and other information for `OPTIONS` requests. + Just return the name and description. + """ + def determine_metadata(self, request, view): + return { + 'name': view.get_view_name(), + 'description': view.get_view_description() + } + +[cite]: http://tools.ietf.org/html/rfc7231#section-4.3.7 +[no-options]: https://www.mnot.net/blog/2012/10/29/NO_OPTIONS +[json-schema]: http://json-schema.org/ From babdc78e61ac915fa4a01bdfb04e11a32dbf5d79 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 9 Oct 2014 11:39:01 +0100 Subject: [PATCH 140/249] Typo --- docs/api-guide/validators.md | 0 docs/topics/3.0-announcement.md | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 docs/api-guide/validators.md diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 26d261edd..bffc608a8 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -617,7 +617,7 @@ The view logic for the default method handlers has been significantly simplified The `pre_save` and `post_save` hooks no longer exist, but are replaced with `perform_create(self, serializer)` and `perform_update(self, serializer)`. -These method should save the object instance by calling `serializer.save()`, adding in any explicit additional arguments as required. They may also perform any custom pre-save or post-save behavior. +These methods should save the object instance by calling `serializer.save()`, adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior. For example: From 5d247a65c89594a7ab5ce2333612f23eadc6828d Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 9 Oct 2014 15:11:19 +0100 Subject: [PATCH 141/249] First pass on nested serializers in HTML --- docs/tutorial/quickstart.md | 8 ++- rest_framework/compat.py | 16 ++++- rest_framework/fields.py | 28 ++++++-- rest_framework/relations.py | 20 +++++- rest_framework/renderers.py | 10 ++- rest_framework/serializers.py | 37 +++++++--- .../fields/horizontal/fieldset.html | 5 +- .../fields/horizontal/list_fieldset.html | 13 ++++ .../fields/inline/fieldset.html | 5 +- .../fields/vertical/fieldset.html | 5 +- .../fields/vertical/list_fieldset.html | 7 ++ tests/test_bound_fields.py | 69 +++++++++++++++++++ 12 files changed, 195 insertions(+), 28 deletions(-) create mode 100644 rest_framework/templates/rest_framework/fields/horizontal/list_fieldset.html create mode 100644 rest_framework/templates/rest_framework/fields/vertical/list_fieldset.html create mode 100644 tests/test_bound_fields.py diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 813e9872c..c2dc4bea9 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -26,11 +26,13 @@ Create a new Django project named `tutorial`, then start a new app called `quick Now sync your database for the first time: - python manage.py syncdb + python manage.py migrate -Make sure to create an initial user named `admin` with a password of `password`. We'll authenticate as that user later in our example. +We'll also create an initial user named `admin` with a password of `password`. We'll authenticate as that user later in our example. -Once you've set up a database and got everything synced and ready to go, open up the app's directory and we'll get coding... + python manage.py createsuperuser + +Once you've set up a database and initial user created and ready to go, open up the app's directory and we'll get coding... ## Serializers diff --git a/rest_framework/compat.py b/rest_framework/compat.py index e4e69580f..4ab23a4da 100644 --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -114,12 +114,15 @@ else: -# MinValueValidator and MaxValueValidator only accept `message` in 1.8+ +# MinValueValidator, MaxValueValidator et al. only accept `message` in 1.8+ if django.VERSION >= (1, 8): from django.core.validators import MinValueValidator, MaxValueValidator + from django.core.validators import MinLengthValidator, MaxLengthValidator else: from django.core.validators import MinValueValidator as DjangoMinValueValidator from django.core.validators import MaxValueValidator as DjangoMaxValueValidator + from django.core.validators import MinLengthValidator as DjangoMinLengthValidator + from django.core.validators import MaxLengthValidator as DjangoMaxLengthValidator class MinValueValidator(DjangoMinValueValidator): def __init__(self, *args, **kwargs): @@ -131,6 +134,17 @@ else: self.message = kwargs.pop('message', self.message) super(MaxValueValidator, self).__init__(*args, **kwargs) + class MinLengthValidator(DjangoMinLengthValidator): + def __init__(self, *args, **kwargs): + self.message = kwargs.pop('message', self.message) + super(MinLengthValidator, self).__init__(*args, **kwargs) + + class MaxLengthValidator(DjangoMaxLengthValidator): + def __init__(self, *args, **kwargs): + self.message = kwargs.pop('message', self.message) + super(MaxLengthValidator, self).__init__(*args, **kwargs) + + # URLValidator only accepts `message` in 1.6+ if django.VERSION >= (1, 6): from django.core.validators import URLValidator diff --git a/rest_framework/fields.py b/rest_framework/fields.py index b371c7d0a..7053acee0 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -8,7 +8,10 @@ from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.encoding import is_protected_type from django.utils.translation import ugettext_lazy as _ from rest_framework import ISO_8601 -from rest_framework.compat import smart_text, EmailValidator, MinValueValidator, MaxValueValidator, URLValidator +from rest_framework.compat import ( + smart_text, EmailValidator, MinValueValidator, MaxValueValidator, + MinLengthValidator, MaxLengthValidator, URLValidator +) from rest_framework.settings import api_settings from rest_framework.utils import html, representation, humanize_datetime import copy @@ -138,7 +141,7 @@ class Field(object): self.label = label self.help_text = help_text self.style = {} if style is None else style - self.validators = validators or self.default_validators[:] + self.validators = validators[:] or self.default_validators[:] self.allow_null = allow_null # These are set up by `.bind()` when the field is added to a serializer. @@ -412,16 +415,24 @@ class NullBooleanField(Field): class CharField(Field): default_error_messages = { - 'blank': _('This field may not be blank.') + 'blank': _('This field may not be blank.'), + 'max_length': _('Ensure this field has no more than {max_length} characters.'), + 'min_length': _('Ensure this field has no more than {min_length} characters.') } initial = '' coerce_blank_to_null = False def __init__(self, **kwargs): self.allow_blank = kwargs.pop('allow_blank', False) - self.max_length = kwargs.pop('max_length', None) - self.min_length = kwargs.pop('min_length', None) + max_length = kwargs.pop('max_length', None) + min_length = kwargs.pop('min_length', None) super(CharField, self).__init__(**kwargs) + if max_length is not None: + message = self.error_messages['max_length'].format(max_length=max_length) + self.validators.append(MaxLengthValidator(max_length, message=message)) + if min_length is not None: + message = self.error_messages['min_length'].format(min_length=min_length) + self.validators.append(MinLengthValidator(min_length, message=message)) def run_validation(self, data=empty): # Test for the empty string here so that it does not get validated, @@ -857,6 +868,13 @@ class MultipleChoiceField(ChoiceField): } default_empty_html = [] + 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 dictionary.getlist(self.field_name) + 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__) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index c1e5aa187..268b95cf1 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -1,6 +1,7 @@ from rest_framework.compat import smart_text, urlparse from rest_framework.fields import empty, Field from rest_framework.reverse import reverse +from rest_framework.utils import html from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch, Resolver404 from django.db.models.query import QuerySet @@ -263,6 +264,13 @@ class ManyRelation(Field): super(ManyRelation, self).__init__(*args, **kwargs) self.child_relation.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 dictionary.getlist(self.field_name) + return dictionary.get(self.field_name, empty) + def to_internal_value(self, data): return [ self.child_relation.to_internal_value(item) @@ -278,10 +286,16 @@ class ManyRelation(Field): @property def choices(self): + queryset = self.child_relation.queryset + iterable = queryset.all() if (hasattr(queryset, 'all')) else queryset + items_and_representations = [ + (item, self.child_relation.to_representation(item)) + for item in iterable + ] return dict([ ( - str(self.child_relation.to_representation(item)), - str(item) + str(item_representation), + str(item) + ' - ' + str(item_representation) ) - for item in self.child_relation.queryset.all() + for item, item_representation in items_and_representations ]) diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 931dd434f..4fb360609 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -364,6 +364,12 @@ class HTMLFormRenderer(BaseRenderer): serializers.ManyRelation: { 'default': 'select_multiple.html', 'checkbox': 'select_checkbox.html' + }, + serializers.Serializer: { + 'default': 'fieldset.html' + }, + serializers.ListSerializer: { + 'default': 'list_fieldset.html' } }) @@ -392,7 +398,9 @@ class HTMLFormRenderer(BaseRenderer): template = loader.get_template(template_name) context = Context({ 'field': field, - 'input_type': input_type + 'input_type': input_type, + 'renderer': self, + 'layout': layout }) return template.render(context) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 9fcbcba76..1c006990b 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -166,14 +166,25 @@ class BoundField(object): Returned when iterating over a serializer instance, providing an API similar to Django forms and form fields. """ - def __init__(self, field, value, errors): + def __init__(self, field, value, errors, prefix=''): self._field = field self.value = value self.errors = errors + self.name = prefix + self.field_name def __getattr__(self, attr_name): return getattr(self._field, attr_name) + def __iter__(self): + for field in self.fields.values(): + yield self[field.field_name] + + def __getitem__(self, key): + field = self.fields[key] + value = self.value.get(key) if self.value else None + error = self.errors.get(key) if self.errors else None + return BoundField(field, value, error, prefix=self.name + '.') + @property def _proxy_class(self): return self._field.__class__ @@ -355,16 +366,23 @@ class Serializer(BaseSerializer): def validate(self, attrs): return attrs - def __iter__(self): - errors = self.errors if hasattr(self, '_errors') else {} - for field in self.fields.values(): - value = self.data.get(field.field_name) if self.data else None - error = errors.get(field.field_name) - yield BoundField(field, value, error) - def __repr__(self): return representation.serializer_repr(self, indent=1) + # The following are used for accessing `BoundField` instances on the + # serializer, for the purposes of presenting a form-like API onto the + # field values and field errors. + + def __iter__(self): + for field in self.fields.values(): + yield self[field.field_name] + + def __getitem__(self, key): + field = self.fields[key] + value = self.data.get(key) + error = self.errors.get(key) if hasattr(self, '_errors') else None + return BoundField(field, value, error) + # There's some replication of `ListField` here, # but that's probably better than obfuscating the call hierarchy. @@ -404,8 +422,9 @@ class ListSerializer(BaseSerializer): """ List of object instances -> List of dicts of primitive datatypes. """ + iterable = data.all() if (hasattr(data, 'all')) else data return ReturnList( - [self.child.to_representation(item) for item in data], + [self.child.to_representation(item) for item in iterable], serializer=self ) diff --git a/rest_framework/templates/rest_framework/fields/horizontal/fieldset.html b/rest_framework/templates/rest_framework/fields/horizontal/fieldset.html index 843a56b29..ff93c6baa 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/fieldset.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/fieldset.html @@ -1,10 +1,11 @@ +{% load rest_framework %} <fieldset> {% if field.label %} <div class="form-group" style="border-bottom: 1px solid #e5e5e5"> <legend class="control-label col-sm-2 {% if field.style.hide_label %}sr-only{% endif %}" style="border-bottom: 0">{{ field.label }}</legend> </div> {% endif %} - {% for field_item in field.value.field_items.values() %} - {{ renderer.render_field(field_item, layout=layout) }} + {% for nested_field in field %} + {% render_field nested_field layout=layout renderer=renderer %} {% endfor %} </fieldset> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/list_fieldset.html b/rest_framework/templates/rest_framework/fields/horizontal/list_fieldset.html new file mode 100644 index 000000000..68c75d4f8 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/horizontal/list_fieldset.html @@ -0,0 +1,13 @@ +{% load rest_framework %} +<fieldset> + {% if field.label %} + <div class="form-group" style="border-bottom: 1px solid #e5e5e5"> + <legend class="control-label col-sm-2 {% if field.style.hide_label %}sr-only{% endif %}" style="border-bottom: 0">{{ field.label }}</legend> + </div> + {% endif %} + <ul> + {% for child in field.value %} + <li>TODO</li> + {% endfor %} + </ul> +</fieldset> diff --git a/rest_framework/templates/rest_framework/fields/inline/fieldset.html b/rest_framework/templates/rest_framework/fields/inline/fieldset.html index 380d46272..ba9f1835a 100644 --- a/rest_framework/templates/rest_framework/fields/inline/fieldset.html +++ b/rest_framework/templates/rest_framework/fields/inline/fieldset.html @@ -1,3 +1,4 @@ -{% for field_item in field.value.field_items.values() %} - {{ renderer.render_field(field_item, layout=layout) }} +{% load rest_framework %} +{% for nested_field in field %} + {% render_field nested_field layout=layout renderer=renderer %} {% endfor %} diff --git a/rest_framework/templates/rest_framework/fields/vertical/fieldset.html b/rest_framework/templates/rest_framework/fields/vertical/fieldset.html index 8708916bd..248fe9044 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/fieldset.html +++ b/rest_framework/templates/rest_framework/fields/vertical/fieldset.html @@ -1,6 +1,7 @@ +{% load rest_framework %} <fieldset> {% if field.label %}<legend {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %} - {% for field_item in field.value.field_items.values() %} - {{ renderer.render_field(field_item, layout=layout) }} + {% for nested_field in field %} + {% render_field nested_field layout=layout renderer=renderer %} {% endfor %} </fieldset> diff --git a/rest_framework/templates/rest_framework/fields/vertical/list_fieldset.html b/rest_framework/templates/rest_framework/fields/vertical/list_fieldset.html new file mode 100644 index 000000000..6b99a8349 --- /dev/null +++ b/rest_framework/templates/rest_framework/fields/vertical/list_fieldset.html @@ -0,0 +1,7 @@ +<fieldset> + {% if field.label %}<legend {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %} +<!-- {% if field.label %}<legend {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %} + {% for field_item in field.value.field_items.values() %} + {{ renderer.render_field(field_item, layout=layout) }} + {% endfor %} --> +</fieldset> diff --git a/tests/test_bound_fields.py b/tests/test_bound_fields.py new file mode 100644 index 000000000..469437e4b --- /dev/null +++ b/tests/test_bound_fields.py @@ -0,0 +1,69 @@ +from rest_framework import serializers + + +class TestSimpleBoundField: + def test_empty_bound_field(self): + class ExampleSerializer(serializers.Serializer): + text = serializers.CharField(max_length=100) + amount = serializers.IntegerField() + + serializer = ExampleSerializer() + + assert serializer['text'].value == '' + assert serializer['text'].errors is None + assert serializer['text'].name == 'text' + assert serializer['amount'].value is None + assert serializer['amount'].errors is None + assert serializer['amount'].name == 'amount' + + def test_populated_bound_field(self): + class ExampleSerializer(serializers.Serializer): + text = serializers.CharField(max_length=100) + amount = serializers.IntegerField() + + serializer = ExampleSerializer(data={'text': 'abc', 'amount': 123}) + + assert serializer['text'].value == 'abc' + assert serializer['text'].errors is None + assert serializer['text'].name == 'text' + assert serializer['amount'].value is 123 + assert serializer['amount'].errors is None + assert serializer['amount'].name == 'amount' + + def test_error_bound_field(self): + class ExampleSerializer(serializers.Serializer): + text = serializers.CharField(max_length=100) + amount = serializers.IntegerField() + + serializer = ExampleSerializer(data={'text': 'x' * 1000, 'amount': 123}) + serializer.is_valid() + + assert serializer['text'].value == 'x' * 1000 + assert serializer['text'].errors == ['Ensure this field has no more than 100 characters.'] + assert serializer['text'].name == 'text' + assert serializer['amount'].value is 123 + assert serializer['amount'].errors is None + assert serializer['amount'].name == 'amount' + + +class TestNestedBoundField: + def test_nested_empty_bound_field(self): + class Nested(serializers.Serializer): + more_text = serializers.CharField(max_length=100) + amount = serializers.IntegerField() + + class ExampleSerializer(serializers.Serializer): + text = serializers.CharField(max_length=100) + nested = Nested() + + serializer = ExampleSerializer() + + assert serializer['text'].value == '' + assert serializer['text'].errors is None + assert serializer['text'].name == 'text' + assert serializer['nested']['more_text'].value == '' + assert serializer['nested']['more_text'].errors is None + assert serializer['nested']['more_text'].name == 'nested.more_text' + assert serializer['nested']['amount'].value is None + assert serializer['nested']['amount'].errors is None + assert serializer['nested']['amount'].name == 'nested.amount' From f83ed19d22250eb646c9d77ccb1614a78d134e75 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 9 Oct 2014 16:29:34 +0100 Subject: [PATCH 142/249] Checks and repr on BoundField --- rest_framework/serializers.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 1c006990b..3bd7b17b7 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -180,6 +180,7 @@ class BoundField(object): yield self[field.field_name] def __getitem__(self, key): + assert hasattr(self, 'fields'), '"%s" is not a nested field. Cannot perform indexing.' % self.name field = self.fields[key] value = self.value.get(key) if self.value else None error = self.errors.get(key) if self.errors else None @@ -189,6 +190,9 @@ class BoundField(object): def _proxy_class(self): return self._field.__class__ + def __repr__(self): + return '<%s value=%s errors=%s>' % (self.__class__.__name__, self.value, self.errors) + class BindingDict(object): """ From a0e852a4d52558db93209b4616f030b4ae2dcedb Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 9 Oct 2014 16:30:06 +0100 Subject: [PATCH 143/249] Use BoundField .name on fields --- rest_framework/templates/rest_framework/fields/attrs.html | 2 +- .../templates/rest_framework/fields/horizontal/checkbox.html | 2 +- .../templates/rest_framework/fields/horizontal/select.html | 2 +- .../rest_framework/fields/horizontal/select_checkbox.html | 4 ++-- .../rest_framework/fields/horizontal/select_multiple.html | 2 +- .../rest_framework/fields/horizontal/select_radio.html | 4 ++-- .../templates/rest_framework/fields/inline/checkbox.html | 2 +- .../templates/rest_framework/fields/inline/select.html | 2 +- .../rest_framework/fields/inline/select_checkbox.html | 2 +- .../rest_framework/fields/inline/select_multiple.html | 2 +- .../templates/rest_framework/fields/inline/select_radio.html | 2 +- .../templates/rest_framework/fields/vertical/checkbox.html | 2 +- .../templates/rest_framework/fields/vertical/select.html | 2 +- .../rest_framework/fields/vertical/select_checkbox.html | 4 ++-- .../rest_framework/fields/vertical/select_multiple.html | 2 +- .../rest_framework/fields/vertical/select_radio.html | 4 ++-- 16 files changed, 20 insertions(+), 20 deletions(-) diff --git a/rest_framework/templates/rest_framework/fields/attrs.html b/rest_framework/templates/rest_framework/fields/attrs.html index b5a4dbcf1..1e23c4655 100644 --- a/rest_framework/templates/rest_framework/fields/attrs.html +++ b/rest_framework/templates/rest_framework/fields/attrs.html @@ -1 +1 @@ -name="{{ field.field_name }}" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.style.rows %}rows="{{ field.style.rows }}"{% endif %} +name="{{ field.name }}" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.style.rows %}rows="{{ field.style.rows }}"{% endif %} diff --git a/rest_framework/templates/rest_framework/fields/horizontal/checkbox.html b/rest_framework/templates/rest_framework/fields/horizontal/checkbox.html index dd3c3cef1..ee3bf9366 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/checkbox.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/checkbox.html @@ -2,7 +2,7 @@ <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> - <input type="checkbox" name="{{ field.field_name }}" value="true" {% if field.value %}checked{% endif %}> + <input type="checkbox" name="{{ field.name }}" value="true" {% if field.value %}checked{% endif %}> {% if field.label %}{{ field.label }}{% endif %} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select.html b/rest_framework/templates/rest_framework/fields/horizontal/select.html index 7367d7269..10b4b1393 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/select.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/select.html @@ -1,7 +1,7 @@ <div class="form-group"> {% include "rest_framework/fields/horizontal/label.html" %} <div class="col-sm-10"> - <select class="form-control" name="{{ field.field_name }}"> + <select class="form-control" name="{{ field.name }}"> {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html b/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html index 381cda2cb..6041fa746 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html @@ -4,7 +4,7 @@ {% if field.style.inline %} {% for key, text in field.choices.items %} <label class="checkbox-inline"> - <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> + <input type="checkbox" name="{{ field.name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> {{ text }} </label> {% endfor %} @@ -12,7 +12,7 @@ {% for key, text in field.choices.items %} <div class="checkbox"> <label> - <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> + <input type="checkbox" name="{{ field.name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> {{ text }} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html b/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html index 29ba86610..c0dbb989a 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html @@ -1,7 +1,7 @@ <div class="form-group"> {% include "rest_framework/fields/horizontal/label.html" %} <div class="col-sm-10"> - <select multiple class="form-control" name="{{ field.field_name }}"> + <select multiple class="form-control" name="{{ field.name }}"> {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key in field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html b/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html index 20aab8b22..0eeb9bc67 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html @@ -4,7 +4,7 @@ {% if field.style.inline %} {% for key, text in field.choices.items %} <label class="radio-inline"> - <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> + <input type="radio" name="{{ field.name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> {{ text }} </label> {% endfor %} @@ -12,7 +12,7 @@ {% for key, text in field.choices.items %} <div class="radio"> <label> - <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> + <input type="radio" name="{{ field.name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> {{ text }} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/inline/checkbox.html b/rest_framework/templates/rest_framework/fields/inline/checkbox.html index 289bbb4d8..57fa5dc04 100644 --- a/rest_framework/templates/rest_framework/fields/inline/checkbox.html +++ b/rest_framework/templates/rest_framework/fields/inline/checkbox.html @@ -1,6 +1,6 @@ <div class="checkbox"> <label> - <input type="checkbox" name="{{ field.field_name }}" value="true" {% if field.value %}checked{% endif %}> + <input type="checkbox" name="{{ field.name }}" value="true" {% if field.value %}checked{% endif %}> {% if field.label %}{{ field.label }}{% endif %} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/inline/select.html b/rest_framework/templates/rest_framework/fields/inline/select.html index 9f361c4a0..eebb91d24 100644 --- a/rest_framework/templates/rest_framework/fields/inline/select.html +++ b/rest_framework/templates/rest_framework/fields/inline/select.html @@ -1,6 +1,6 @@ <div class="form-group"> {% include "rest_framework/fields/inline/label.html" %} - <select class="form-control" name="{{ field.field_name }}"> + <select class="form-control" name="{{ field.name }}"> {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} diff --git a/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html b/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html index 0f33fb692..b7561cd4d 100644 --- a/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html +++ b/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html @@ -3,7 +3,7 @@ {% for key, text in field.choices.items %} <div class="checkbox"> <label> - <input type="checkbox" name="{{ rest_framework/field.field_name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> + <input type="checkbox" name="{{ rest_framework/field.name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> {{ text }} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/inline/select_multiple.html b/rest_framework/templates/rest_framework/fields/inline/select_multiple.html index 7c9e51684..74e17f9fb 100644 --- a/rest_framework/templates/rest_framework/fields/inline/select_multiple.html +++ b/rest_framework/templates/rest_framework/fields/inline/select_multiple.html @@ -1,6 +1,6 @@ <div class="form-group"> {% include "rest_framework/fields/inline/label.html" %} - <select multiple class="form-control" name="{{ field.field_name }}"> + <select multiple class="form-control" name="{{ field.name }}"> {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key in field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} diff --git a/rest_framework/templates/rest_framework/fields/inline/select_radio.html b/rest_framework/templates/rest_framework/fields/inline/select_radio.html index 177c0eeba..27927a62d 100644 --- a/rest_framework/templates/rest_framework/fields/inline/select_radio.html +++ b/rest_framework/templates/rest_framework/fields/inline/select_radio.html @@ -3,7 +3,7 @@ {% for key, text in field.choices.items %} <div class="radio"> <label> - <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> + <input type="radio" name="{{ field.name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> {{ text }} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/checkbox.html b/rest_framework/templates/rest_framework/fields/vertical/checkbox.html index 01d30aaef..9fd4cdaa2 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/checkbox.html +++ b/rest_framework/templates/rest_framework/fields/vertical/checkbox.html @@ -1,6 +1,6 @@ <div class="checkbox"> <label> - <input type="checkbox" name="{{ field.field_name }}" value="true" {% if value %}checked{% endif %}> + <input type="checkbox" name="{{ field.name }}" value="true" {% if value %}checked{% endif %}> {% if field.label %}{{ field.label }}{% endif %} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/select.html b/rest_framework/templates/rest_framework/fields/vertical/select.html index dcc9a3cd9..1a651663f 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/select.html +++ b/rest_framework/templates/rest_framework/fields/vertical/select.html @@ -1,6 +1,6 @@ <div class="form-group"> {% include "rest_framework/fields/vertical/label.html" %} - <select class="form-control" name="{{ field.field_name }}"> + <select class="form-control" name="{{ field.name }}"> {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html b/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html index 1fbe6a940..2e792e6a5 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html +++ b/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html @@ -4,7 +4,7 @@ <div> {% for key, text in field.choices.items %} <label class="checkbox-inline"> - <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> + <input type="checkbox" name="{{ field.name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> {{ text }} </label> {% endfor %} @@ -13,7 +13,7 @@ {% for key, text in field.choices.items %} <div class="checkbox"> <label> - <input type="checkbox" name="{{ field.field_name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> + <input type="checkbox" name="{{ field.name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> {{ text }} </label> </div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html b/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html index 2cc40d99e..5f4166cd9 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html +++ b/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html @@ -1,6 +1,6 @@ <div class="form-group"> {% include "rest_framework/fields/vertical/label.html" %} - <select multiple class="form-control" name="{{ field.field_name }}"> + <select multiple class="form-control" name="{{ field.name }}"> {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key in field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_radio.html b/rest_framework/templates/rest_framework/fields/vertical/select_radio.html index 470bcb0b0..2aa0fe289 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/select_radio.html +++ b/rest_framework/templates/rest_framework/fields/vertical/select_radio.html @@ -4,7 +4,7 @@ <div> {% for key, text in field.choices.items %} <label class="radio-inline"> - <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> + <input type="radio" name="{{ field.name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> {{ text }} </label> {% endfor %} @@ -13,7 +13,7 @@ {% for key, text in field.choices.items %} <div class="radio"> <label> - <input type="radio" name="{{ field.field_name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> + <input type="radio" name="{{ field.name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> {{ text }} </label> </div> From d9a199ca0ddf92f999aa37b396596d0e3e0a26d9 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 10 Oct 2014 14:16:09 +0100 Subject: [PATCH 144/249] exceptions.ValidationFailed, not Django's ValidationError --- docs/topics/3.0-announcement.md | 6 +-- rest_framework/authtoken/serializers.py | 8 +-- rest_framework/exceptions.py | 14 +++++ rest_framework/fields.py | 21 +++++--- rest_framework/serializers.py | 68 ++++++++++++++----------- rest_framework/views.py | 27 ++++------ tests/test_fields.py | 23 ++++----- tests/test_relations.py | 20 ++++---- tests/test_validation.py | 11 ++-- 9 files changed, 107 insertions(+), 91 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index bffc608a8..b28670cf7 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -191,7 +191,7 @@ Using the `depth` option on `ModelSerializer` will now create **read-only nested def create(self, validated_data): profile_data = validated_data.pop['profile'] user = User.objects.create(**validated_data) - profile = Profile.objects.create(user=user, **profile_data) + Profile.objects.create(user=user, **profile_data) return user The single-step object creation makes this far simpler and more obvious than the previous `.restore_object()` behavior. @@ -223,10 +223,6 @@ We can now inspect the serializer representation in the Django shell, using `pyt rating = IntegerField() created_by = PrimaryKeyRelatedField(queryset=User.objects.all()) -#### Always use `fields`, not `exclude`. - -The `exclude` option on `ModelSerializer` is no longer available. You should use the more explicit `fields` option instead. - #### The `extra_kwargs` option. The `write_only_fields` option on `ModelSerializer` has been moved to `PendingDeprecation` and replaced with a more generic `extra_kwargs`. diff --git a/rest_framework/authtoken/serializers.py b/rest_framework/authtoken/serializers.py index c2c456dea..a808d0a32 100644 --- a/rest_framework/authtoken/serializers.py +++ b/rest_framework/authtoken/serializers.py @@ -1,7 +1,7 @@ from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ -from rest_framework import serializers +from rest_framework import exceptions, serializers class AuthTokenSerializer(serializers.Serializer): @@ -18,13 +18,13 @@ class AuthTokenSerializer(serializers.Serializer): if user: if not user.is_active: msg = _('User account is disabled.') - raise serializers.ValidationError(msg) + raise exceptions.ValidationFailed(msg) else: msg = _('Unable to log in with provided credentials.') - raise serializers.ValidationError(msg) + raise exceptions.ValidationFailed(msg) else: msg = _('Must include "username" and "password"') - raise serializers.ValidationError(msg) + raise exceptions.ValidationFailed(msg) attrs['user'] = user return attrs diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py index 06b5e8a27..b7c2d16d6 100644 --- a/rest_framework/exceptions.py +++ b/rest_framework/exceptions.py @@ -24,6 +24,20 @@ class APIException(Exception): return self.detail +class ValidationFailed(APIException): + status_code = status.HTTP_400_BAD_REQUEST + + def __init__(self, detail): + # For validation errors the 'detail' key is always required. + # The details should always be coerced to a list if not already. + if not isinstance(detail, dict) and not isinstance(detail, list): + detail = [detail] + self.detail = detail + + def __str__(self): + return str(self.detail) + + class ParseError(APIException): status_code = status.HTTP_400_BAD_REQUEST default_detail = 'Malformed request.' diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 7053acee0..b881ad13b 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1,7 +1,8 @@ -from django import forms from django.conf import settings from django.core import validators -from django.core.exceptions import ObjectDoesNotExist, ValidationError +from django.core.exceptions import ObjectDoesNotExist +from django.core.exceptions import ValidationError as DjangoValidationError +from django.forms import ImageField as DjangoImageField from django.utils import six, timezone from django.utils.datastructures import SortedDict from django.utils.dateparse import parse_date, parse_datetime, parse_time @@ -12,6 +13,7 @@ from rest_framework.compat import ( smart_text, EmailValidator, MinValueValidator, MaxValueValidator, MinLengthValidator, MaxLengthValidator, URLValidator ) +from rest_framework.exceptions import ValidationFailed from rest_framework.settings import api_settings from rest_framework.utils import html, representation, humanize_datetime import copy @@ -98,7 +100,7 @@ NOT_READ_ONLY_DEFAULT = 'May not set both `read_only` and `default`' NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`' USE_READONLYFIELD = 'Field(read_only=True) should be ReadOnlyField' MISSING_ERROR_MESSAGE = ( - 'ValidationError raised by `{class_name}`, but error key `{key}` does ' + 'ValidationFailed raised by `{class_name}`, but error key `{key}` does ' 'not exist in the `error_messages` dictionary.' ) @@ -263,7 +265,7 @@ class Field(object): def run_validators(self, value): """ Test the given value against all the validators on the field, - and either raise a `ValidationError` or simply return. + and either raise a `ValidationFailed` or simply return. """ errors = [] for validator in self.validators: @@ -271,10 +273,12 @@ class Field(object): validator.serializer_field = self try: validator(value) - except ValidationError as exc: + except ValidationFailed as exc: + errors.extend(exc.detail) + except DjangoValidationError as exc: errors.extend(exc.messages) if errors: - raise ValidationError(errors) + raise ValidationFailed(errors) def validate(self, value): pass @@ -301,7 +305,8 @@ class Field(object): class_name = self.__class__.__name__ msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key) raise AssertionError(msg) - raise ValidationError(msg.format(**kwargs)) + message_string = msg.format(**kwargs) + raise ValidationFailed(message_string) @property def root(self): @@ -946,7 +951,7 @@ class ImageField(FileField): } def __init__(self, *args, **kwargs): - self._DjangoImageField = kwargs.pop('_DjangoImageField', forms.ImageField) + self._DjangoImageField = kwargs.pop('_DjangoImageField', DjangoImageField) super(ImageField, self).__init__(*args, **kwargs) def to_internal_value(self, data): diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 3bd7b17b7..2f6835629 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -10,10 +10,11 @@ python primitives. 2. The process of marshalling between python primitives and request and response content is handled by parsers and renderers. """ -from django.core.exceptions import ImproperlyConfigured, ValidationError +from django.core.exceptions import ImproperlyConfigured from django.db import models from django.utils import six from django.utils.datastructures import SortedDict +from rest_framework.exceptions import ValidationFailed from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.settings import api_settings from rest_framework.utils import html, model_meta, representation @@ -100,14 +101,14 @@ class BaseSerializer(Field): if not hasattr(self, '_validated_data'): try: self._validated_data = self.run_validation(self._initial_data) - except ValidationError as exc: + except ValidationFailed as exc: self._validated_data = {} - self._errors = exc.message_dict + self._errors = exc.detail else: self._errors = {} if self._errors and raise_exception: - raise ValidationError(self._errors) + raise ValidationFailed(self._errors) return not bool(self._errors) @@ -175,23 +176,33 @@ class BoundField(object): def __getattr__(self, attr_name): return getattr(self._field, attr_name) - def __iter__(self): - for field in self.fields.values(): - yield self[field.field_name] - - def __getitem__(self, key): - assert hasattr(self, 'fields'), '"%s" is not a nested field. Cannot perform indexing.' % self.name - field = self.fields[key] - value = self.value.get(key) if self.value else None - error = self.errors.get(key) if self.errors else None - return BoundField(field, value, error, prefix=self.name + '.') - @property def _proxy_class(self): return self._field.__class__ def __repr__(self): - return '<%s value=%s errors=%s>' % (self.__class__.__name__, self.value, self.errors) + return '<%s value=%s errors=%s>' % ( + self.__class__.__name__, self.value, self.errors + ) + + +class NestedBoundField(BoundField): + """ + This BoundField additionally implements __iter__ and __getitem__ + in order to support nested bound fields. This class is the type of + BoundField that is used for serializer fields. + """ + def __iter__(self): + for field in self.fields.values(): + yield self[field.field_name] + + def __getitem__(self, key): + field = self.fields[key] + value = self.value.get(key) if self.value else None + error = self.errors.get(key) if self.errors else None + if isinstance(field, Serializer): + return NestedBoundField(field, value, error, prefix=self.name + '.') + return BoundField(field, value, error, prefix=self.name + '.') class BindingDict(object): @@ -308,7 +319,7 @@ class Serializer(BaseSerializer): return None if not isinstance(data, dict): - raise ValidationError({ + raise ValidationFailed({ api_settings.NON_FIELD_ERRORS_KEY: ['Invalid data'] }) @@ -317,9 +328,9 @@ class Serializer(BaseSerializer): self.run_validators(value) value = self.validate(value) assert value is not None, '.validate() should return the validated data' - except ValidationError as exc: - raise ValidationError({ - api_settings.NON_FIELD_ERRORS_KEY: exc.messages + except ValidationFailed as exc: + raise ValidationFailed({ + api_settings.NON_FIELD_ERRORS_KEY: exc.detail }) return value @@ -338,15 +349,15 @@ class Serializer(BaseSerializer): validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) - except ValidationError as exc: - errors[field.field_name] = exc.messages + except ValidationFailed as exc: + errors[field.field_name] = exc.detail except SkipField: pass else: set_value(ret, field.source_attrs, validated_value) if errors: - raise ValidationError(errors) + raise ValidationFailed(errors) return ret @@ -385,6 +396,8 @@ class Serializer(BaseSerializer): field = self.fields[key] value = self.data.get(key) error = self.errors.get(key) if hasattr(self, '_errors') else None + if isinstance(field, Serializer): + return NestedBoundField(field, value, error) return BoundField(field, value, error) @@ -538,9 +551,12 @@ class ModelSerializer(Serializer): ret = SortedDict() model = getattr(self.Meta, 'model') 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', {}) + assert not fields and exclude, "Cannot set both 'fields' and 'exclude'." + extra_kwargs = self._include_additional_options(extra_kwargs) # Retrieve metadata about fields & relationships on the model class. @@ -551,12 +567,6 @@ class ModelSerializer(Serializer): fields = self._get_default_field_names(declared_fields, info) exclude = getattr(self.Meta, 'exclude', None) if exclude is not None: - warnings.warn( - "The `Meta.exclude` option is pending deprecation. " - "Use the explicit `Meta.fields` instead.", - PendingDeprecationWarning, - stacklevel=3 - ) for field_name in exclude: fields.remove(field_name) diff --git a/rest_framework/views.py b/rest_framework/views.py index 979229eb4..292431c8a 100644 --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -3,7 +3,7 @@ Provides an APIView class that is the base of all views in REST framework. """ from __future__ import unicode_literals -from django.core.exceptions import PermissionDenied, ValidationError, NON_FIELD_ERRORS +from django.core.exceptions import PermissionDenied from django.http import Http404 from django.views.decorators.csrf import csrf_exempt from rest_framework import status, exceptions @@ -63,27 +63,20 @@ def exception_handler(exc): if getattr(exc, 'wait', None): headers['Retry-After'] = '%d' % exc.wait - return Response({'detail': exc.detail}, - status=exc.status_code, - headers=headers) + if isinstance(exc.detail, (list, dict)): + data = exc.detail + else: + data = {'detail': exc.detail} - elif isinstance(exc, ValidationError): - # ValidationErrors may include the non-field key named '__all__'. - # When returning a response we map this to a key name that can be - # modified in settings. - if NON_FIELD_ERRORS in exc.message_dict: - errors = exc.message_dict.pop(NON_FIELD_ERRORS) - exc.message_dict[api_settings.NON_FIELD_ERRORS_KEY] = errors - return Response(exc.message_dict, - status=status.HTTP_400_BAD_REQUEST) + return Response(data, status=exc.status_code, headers=headers) elif isinstance(exc, Http404): - return Response({'detail': 'Not found'}, - status=status.HTTP_404_NOT_FOUND) + data = {'detail': 'Not found'} + return Response(data, status=status.HTTP_404_NOT_FOUND) elif isinstance(exc, PermissionDenied): - return Response({'detail': 'Permission denied'}, - status=status.HTTP_403_FORBIDDEN) + data = {'detail': 'Permission denied'} + return Response(data, status=status.HTTP_403_FORBIDDEN) # Note: Unhandled exceptions will raise a 500 error. return None diff --git a/tests/test_fields.py b/tests/test_fields.py index eaa0a3c83..5e8c67c54 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1,7 +1,6 @@ from decimal import Decimal -from django.core.exceptions import ValidationError from django.utils import timezone -from rest_framework import fields, serializers +from rest_framework import exceptions, fields, serializers import datetime import django import pytest @@ -19,9 +18,9 @@ class TestEmpty: By default a field must be included in the input. """ field = fields.IntegerField() - with pytest.raises(fields.ValidationError) as exc_info: + with pytest.raises(exceptions.ValidationFailed) as exc_info: field.run_validation() - assert exc_info.value.messages == ['This field is required.'] + assert exc_info.value.detail == ['This field is required.'] def test_not_required(self): """ @@ -36,9 +35,9 @@ class TestEmpty: By default `None` is not a valid input. """ field = fields.IntegerField() - with pytest.raises(fields.ValidationError) as exc_info: + with pytest.raises(exceptions.ValidationFailed) as exc_info: field.run_validation(None) - assert exc_info.value.messages == ['This field may not be null.'] + assert exc_info.value.detail == ['This field may not be null.'] def test_allow_null(self): """ @@ -53,9 +52,9 @@ class TestEmpty: By default '' is not a valid input. """ field = fields.CharField() - with pytest.raises(fields.ValidationError) as exc_info: + with pytest.raises(exceptions.ValidationFailed) as exc_info: field.run_validation('') - assert exc_info.value.messages == ['This field may not be blank.'] + assert exc_info.value.detail == ['This field may not be blank.'] def test_allow_blank(self): """ @@ -190,7 +189,7 @@ class TestInvalidErrorKey: with pytest.raises(AssertionError) as exc_info: self.field.to_native(123) expected = ( - 'ValidationError raised by `ExampleField`, but error key ' + 'ValidationFailed raised by `ExampleField`, but error key ' '`incorrect` does not exist in the `error_messages` dictionary.' ) assert str(exc_info.value) == expected @@ -244,9 +243,9 @@ class FieldValues: Ensure that invalid values raise the expected validation error. """ for input_value, expected_failure in get_items(self.invalid_inputs): - with pytest.raises(fields.ValidationError) as exc_info: + with pytest.raises(exceptions.ValidationFailed) as exc_info: self.field.run_validation(input_value) - assert exc_info.value.messages == expected_failure + assert exc_info.value.detail == expected_failure def test_outputs(self): for output_value, expected_output in get_items(self.outputs): @@ -901,7 +900,7 @@ class TestFieldFieldWithName(FieldValues): # call into it's regular validation, or require PIL for testing. class FailImageValidation(object): def to_python(self, value): - raise ValidationError(self.error_messages['invalid_image']) + raise exceptions.ValidationFailed(self.error_messages['invalid_image']) class PassImageValidation(object): diff --git a/tests/test_relations.py b/tests/test_relations.py index 66784195e..53c1b25c7 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -1,6 +1,6 @@ from .utils import mock_reverse, fail_reverse, BadType, MockObject, MockQueryset -from django.core.exceptions import ImproperlyConfigured, ValidationError -from rest_framework import serializers +from django.core.exceptions import ImproperlyConfigured +from rest_framework import exceptions, serializers from rest_framework.test import APISimpleTestCase import pytest @@ -30,15 +30,15 @@ class TestPrimaryKeyRelatedField(APISimpleTestCase): assert instance is self.instance def test_pk_related_lookup_does_not_exist(self): - with pytest.raises(ValidationError) as excinfo: + with pytest.raises(exceptions.ValidationFailed) as excinfo: self.field.to_internal_value(4) - msg = excinfo.value.messages[0] + msg = excinfo.value.detail[0] assert msg == "Invalid pk '4' - object does not exist." def test_pk_related_lookup_invalid_type(self): - with pytest.raises(ValidationError) as excinfo: + with pytest.raises(exceptions.ValidationFailed) as excinfo: self.field.to_internal_value(BadType()) - msg = excinfo.value.messages[0] + msg = excinfo.value.detail[0] assert msg == 'Incorrect type. Expected pk value, received BadType.' def test_pk_representation(self): @@ -120,15 +120,15 @@ class TestSlugRelatedField(APISimpleTestCase): assert instance is self.instance def test_slug_related_lookup_does_not_exist(self): - with pytest.raises(ValidationError) as excinfo: + with pytest.raises(exceptions.ValidationFailed) as excinfo: self.field.to_internal_value('doesnotexist') - msg = excinfo.value.messages[0] + msg = excinfo.value.detail[0] assert msg == 'Object with name=doesnotexist does not exist.' def test_slug_related_lookup_invalid_type(self): - with pytest.raises(ValidationError) as excinfo: + with pytest.raises(exceptions.ValidationFailed) as excinfo: self.field.to_internal_value(BadType()) - msg = excinfo.value.messages[0] + msg = excinfo.value.detail[0] assert msg == 'Invalid value.' def test_representation(self): diff --git a/tests/test_validation.py b/tests/test_validation.py index ce39714d1..849c7e9d5 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -1,9 +1,8 @@ from __future__ import unicode_literals from django.core.validators import MaxValueValidator -from django.core.exceptions import ValidationError from django.db import models from django.test import TestCase -from rest_framework import generics, serializers, status +from rest_framework import exceptions, generics, serializers, status from rest_framework.test import APIRequestFactory factory = APIRequestFactory() @@ -38,7 +37,7 @@ class ShouldValidateModelSerializer(serializers.ModelSerializer): def validate_renamed(self, value): if len(value) < 3: - raise serializers.ValidationError('Minimum 3 characters.') + raise exceptions.ValidationFailed('Minimum 3 characters.') return value class Meta: @@ -74,10 +73,10 @@ class ValidationSerializer(serializers.Serializer): foo = serializers.CharField() def validate_foo(self, attrs, source): - raise serializers.ValidationError("foo invalid") + raise exceptions.ValidationFailed("foo invalid") def validate(self, attrs): - raise serializers.ValidationError("serializer invalid") + raise exceptions.ValidationFailed("serializer invalid") class TestAvoidValidation(TestCase): @@ -159,7 +158,7 @@ class TestChoiceFieldChoicesValidate(TestCase): value = self.CHOICES[0][0] try: f.to_internal_value(value) - except ValidationError: + except exceptions.ValidationFailed: self.fail("Value %s does not validate" % str(value)) # def test_nested_choices(self): From d8a8987ab1eb6abbaee1a0de8cfea38eafe21293 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 10 Oct 2014 14:32:02 +0100 Subject: [PATCH 145/249] Tweaks --- docs/topics/3.0-announcement.md | 6 ++++++ rest_framework/serializers.py | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index b28670cf7..aa0e0c7e7 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -144,6 +144,12 @@ The corresponding code would now look like this: logging.info('Creating ticket "%s"' % name) serializer.save(user=request.user) # Include the user when saving. +#### Use `rest_framework.exceptions.ValidationFailed`. + +Django's `ValidationError` class is intended for use with HTML forms and it's API makes its use slightly awkward with nested validation errors as can occur in serializers. + +We now include a simpler `ValidationFailed` exception class in REST framework that you should use when raising validation failures. + #### Change to `validate_<field_name>`. The `validate_<field_name>` method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field: diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 2f6835629..0f6cf2bcd 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -555,7 +555,7 @@ class ModelSerializer(Serializer): depth = getattr(self.Meta, 'depth', 0) extra_kwargs = getattr(self.Meta, 'extra_kwargs', {}) - assert not fields and exclude, "Cannot set both 'fields' and 'exclude'." + assert not (fields and exclude), "Cannot set both 'fields' and 'exclude'." extra_kwargs = self._include_additional_options(extra_kwargs) From b5a4216aff06bfb36238d0f587d8645db0ee4a69 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 10 Oct 2014 15:08:43 +0100 Subject: [PATCH 146/249] Flake8 --- rest_framework/serializers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 0f6cf2bcd..f3f5c837f 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -555,7 +555,7 @@ class ModelSerializer(Serializer): depth = getattr(self.Meta, 'depth', 0) extra_kwargs = getattr(self.Meta, 'extra_kwargs', {}) - assert not (fields and exclude), "Cannot set both 'fields' and 'exclude'." + assert not (fields and exclude), "Cannot set both 'fields' and 'exclude'." extra_kwargs = self._include_additional_options(extra_kwargs) From 826b5a889704452c53c05a44905f9fa62889ff34 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 10 Oct 2014 15:34:00 +0100 Subject: [PATCH 147/249] Relations in 'read_only_fields' should not include a queryset kwarg --- rest_framework/serializers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index f3f5c837f..bc9c15eb3 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -640,7 +640,7 @@ class ModelSerializer(Serializer): for attr in [ 'required', 'default', 'allow_blank', 'allow_null', 'min_length', 'max_length', 'min_value', 'max_value', - 'validators' + 'validators', 'queryset' ]: kwargs.pop(attr, None) kwargs.update(extras) From 81abf2bf341d8d7b27e2974a01a78c30c796b4d6 Mon Sep 17 00:00:00 2001 From: Andy Freeland <andy.freeland@redjack.com> Date: Sun, 12 Oct 2014 01:19:14 -0400 Subject: [PATCH 148/249] Rename `preform_update` to `perform_update` --- rest_framework/mixins.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index 4c62debb0..467ff5155 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -67,10 +67,10 @@ class UpdateModelMixin(object): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) - self.preform_update(serializer) + self.perform_update(serializer) return Response(serializer.data) - def preform_update(self, serializer): + def perform_update(self, serializer): serializer.save() def partial_update(self, request, *args, **kwargs): From f8f101268e1d3ff0621c61299c13d78914874a2b Mon Sep 17 00:00:00 2001 From: wolfe <davidgameswolfe@gmail.com> Date: Tue, 14 Oct 2014 18:58:25 -0300 Subject: [PATCH 149/249] Update 3.0-announcement.md Swap order of custom field API changes so the two "and" clauses are in the same order. --- docs/topics/3.0-announcement.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index aa0e0c7e7..dcd6d90cb 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -518,7 +518,7 @@ The `MultipleChoiceField` class has been added. This field acts like `ChoiceFiel #### Changes to the custom field API. -The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_representation(self, value)` and `to_internal_value(self, data)`. +The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`. The `field_from_native()` and `field_to_native()` methods are removed. From e272a36c9b444c1da3a3d8bc809070deb26d9c64 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 15 Oct 2014 09:24:49 +0100 Subject: [PATCH 150/249] Fix 'lookup_field' on ModelSerializer. Closes #1944. --- rest_framework/serializers.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index bc9c15eb3..c844605fc 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -680,7 +680,7 @@ class ModelSerializer(Serializer): PendingDeprecationWarning, stacklevel=3 ) - kwargs = extra_kwargs.get(field_name, {}) + kwargs = extra_kwargs.get(api_settings.URL_FIELD_NAME, {}) kwargs['view_name'] = view_name extra_kwargs[api_settings.URL_FIELD_NAME] = kwargs @@ -692,7 +692,7 @@ class ModelSerializer(Serializer): PendingDeprecationWarning, stacklevel=3 ) - kwargs = extra_kwargs.get(field_name, {}) + kwargs = extra_kwargs.get(api_settings.URL_FIELD_NAME, {}) kwargs['lookup_field'] = lookup_field extra_kwargs[api_settings.URL_FIELD_NAME] = kwargs From e558f806c0e87a329915b7077783f9ed3a79bb07 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 15 Oct 2014 10:04:01 +0100 Subject: [PATCH 151/249] Drop template includes --- rest_framework/templates/rest_framework/fields/attrs.html | 1 - .../templates/rest_framework/fields/horizontal/input.html | 6 ++++-- .../templates/rest_framework/fields/horizontal/label.html | 1 - .../rest_framework/fields/horizontal/select.html | 8 +++++--- .../rest_framework/fields/horizontal/select_checkbox.html | 4 +++- .../rest_framework/fields/horizontal/select_multiple.html | 4 +++- .../rest_framework/fields/horizontal/select_radio.html | 4 +++- .../rest_framework/fields/horizontal/textarea.html | 6 ++++-- .../templates/rest_framework/fields/inline/input.html | 6 ++++-- .../templates/rest_framework/fields/inline/label.html | 1 - .../templates/rest_framework/fields/inline/select.html | 4 +++- .../rest_framework/fields/inline/select_checkbox.html | 4 +++- .../rest_framework/fields/inline/select_multiple.html | 4 +++- .../rest_framework/fields/inline/select_radio.html | 4 +++- .../templates/rest_framework/fields/inline/textarea.html | 6 ++++-- .../templates/rest_framework/fields/vertical/input.html | 6 ++++-- .../templates/rest_framework/fields/vertical/label.html | 1 - .../templates/rest_framework/fields/vertical/select.html | 4 +++- .../rest_framework/fields/vertical/select_checkbox.html | 4 +++- .../rest_framework/fields/vertical/select_multiple.html | 4 +++- .../rest_framework/fields/vertical/select_radio.html | 4 +++- .../rest_framework/fields/vertical/textarea.html | 6 ++++-- 22 files changed, 62 insertions(+), 30 deletions(-) delete mode 100644 rest_framework/templates/rest_framework/fields/attrs.html delete mode 100644 rest_framework/templates/rest_framework/fields/horizontal/label.html delete mode 100644 rest_framework/templates/rest_framework/fields/inline/label.html delete mode 100644 rest_framework/templates/rest_framework/fields/vertical/label.html diff --git a/rest_framework/templates/rest_framework/fields/attrs.html b/rest_framework/templates/rest_framework/fields/attrs.html deleted file mode 100644 index 1e23c4655..000000000 --- a/rest_framework/templates/rest_framework/fields/attrs.html +++ /dev/null @@ -1 +0,0 @@ -name="{{ field.name }}" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.style.rows %}rows="{{ field.style.rows }}"{% endif %} diff --git a/rest_framework/templates/rest_framework/fields/horizontal/input.html b/rest_framework/templates/rest_framework/fields/horizontal/input.html index 6f1a504b5..6621c7e60 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/input.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/input.html @@ -1,7 +1,9 @@ <div class="form-group"> - {% include "rest_framework/fields/horizontal/label.html" %} + {% if field.label %} + <label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> + {% endif %} <div class="col-sm-10"> - <input type="{{ input_type }}" class="form-control" {% include "rest_framework/fields/attrs.html" %} {% if field.value %}value="{{ field.value }}"{% endif %}> + <input name="{{ field.name }}" type="{{ input_type }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} </div> </div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/label.html b/rest_framework/templates/rest_framework/fields/horizontal/label.html deleted file mode 100644 index bf21f78cc..000000000 --- a/rest_framework/templates/rest_framework/fields/horizontal/label.html +++ /dev/null @@ -1 +0,0 @@ -{% if field.label %}<label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label>{% endif %} diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select.html b/rest_framework/templates/rest_framework/fields/horizontal/select.html index 10b4b1393..eaa6d575a 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/select.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/select.html @@ -1,10 +1,12 @@ <div class="form-group"> - {% include "rest_framework/fields/horizontal/label.html" %} + {% if field.label %} + <label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> + {% endif %} <div class="col-sm-10"> <select class="form-control" name="{{ field.name }}"> - {% for key, text in field.choices.items %} + {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option> - {% endfor %} + {% endfor %} </select> </div> </div> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html b/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html index 6041fa746..ff3fab573 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html @@ -1,5 +1,7 @@ <div class="form-group"> - {% include "rest_framework/fields/horizontal/label.html" %} + {% if field.label %} + <label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> + {% endif %} <div class="col-sm-10"> {% if field.style.inline %} {% for key, text in field.choices.items %} diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html b/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html index c0dbb989a..3ed2874b2 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html @@ -1,5 +1,7 @@ <div class="form-group"> - {% include "rest_framework/fields/horizontal/label.html" %} + {% if field.label %} + <label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> + {% endif %} <div class="col-sm-10"> <select multiple class="form-control" name="{{ field.name }}"> {% for key, text in field.choices.items %} diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html b/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html index 0eeb9bc67..6e56afb52 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html @@ -1,5 +1,7 @@ <div class="form-group"> - {% include "rest_framework/fields/horizontal/label.html" %} + {% if field.label %} + <label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> + {% endif %} <div class="col-sm-10"> {% if field.style.inline %} {% for key, text in field.choices.items %} diff --git a/rest_framework/templates/rest_framework/fields/horizontal/textarea.html b/rest_framework/templates/rest_framework/fields/horizontal/textarea.html index 3d0161950..ae263c48c 100644 --- a/rest_framework/templates/rest_framework/fields/horizontal/textarea.html +++ b/rest_framework/templates/rest_framework/fields/horizontal/textarea.html @@ -1,7 +1,9 @@ <div class="form-group"> - {% include "rest_framework/fields/horizontal/label.html" %} + {% if field.label %} + <label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> + {% endif %} <div class="col-sm-10"> - <textarea class="form-control" {% include "rest_framework/fields/attrs.html" %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> + <textarea name="{{ field.name }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.style.rows %}rows="{{ field.style.rows }}"{% endif %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} </div> </div> diff --git a/rest_framework/templates/rest_framework/fields/inline/input.html b/rest_framework/templates/rest_framework/fields/inline/input.html index e4a92ccd1..bdf25ffe6 100644 --- a/rest_framework/templates/rest_framework/fields/inline/input.html +++ b/rest_framework/templates/rest_framework/fields/inline/input.html @@ -1,4 +1,6 @@ <div class="form-group"> - {% include "rest_framework/fields/inline/label.html" %} - <input type="{{ input_type }}" class="form-control" {% include "rest_framework/fields/attrs.html" %} {% if field.value %}value="{{ field.value }}"{% endif %}> + {% if field.label %} + <label class="sr-only">{{ field.label }}</label> + {% endif %} + <input name="{{ field.name }}" type="{{ input_type }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> </div> diff --git a/rest_framework/templates/rest_framework/fields/inline/label.html b/rest_framework/templates/rest_framework/fields/inline/label.html deleted file mode 100644 index 7d546a571..000000000 --- a/rest_framework/templates/rest_framework/fields/inline/label.html +++ /dev/null @@ -1 +0,0 @@ -{% if field.label %}<label class="sr-only">{{ field.label }}</label>{% endif %} diff --git a/rest_framework/templates/rest_framework/fields/inline/select.html b/rest_framework/templates/rest_framework/fields/inline/select.html index eebb91d24..730fcce61 100644 --- a/rest_framework/templates/rest_framework/fields/inline/select.html +++ b/rest_framework/templates/rest_framework/fields/inline/select.html @@ -1,5 +1,7 @@ <div class="form-group"> - {% include "rest_framework/fields/inline/label.html" %} + {% if field.label %} + <label class="sr-only">{{ field.label }}</label> + {% endif %} <select class="form-control" name="{{ field.name }}"> {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option> diff --git a/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html b/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html index b7561cd4d..cca71d689 100644 --- a/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html +++ b/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html @@ -1,5 +1,7 @@ <div class="form-group"> - {% include "rest_framework/fields/inline/label.html" %} + {% if field.label %} + <label class="sr-only">{{ field.label }}</label> + {% endif %} {% for key, text in field.choices.items %} <div class="checkbox"> <label> diff --git a/rest_framework/templates/rest_framework/fields/inline/select_multiple.html b/rest_framework/templates/rest_framework/fields/inline/select_multiple.html index 74e17f9fb..3f9b27017 100644 --- a/rest_framework/templates/rest_framework/fields/inline/select_multiple.html +++ b/rest_framework/templates/rest_framework/fields/inline/select_multiple.html @@ -1,5 +1,7 @@ <div class="form-group"> - {% include "rest_framework/fields/inline/label.html" %} + {% if field.label %} + <label class="sr-only">{{ field.label }}</label> + {% endif %} <select multiple class="form-control" name="{{ field.name }}"> {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key in field.value %}selected{% endif %}>{{ text }}</option> diff --git a/rest_framework/templates/rest_framework/fields/inline/select_radio.html b/rest_framework/templates/rest_framework/fields/inline/select_radio.html index 27927a62d..3fffceac4 100644 --- a/rest_framework/templates/rest_framework/fields/inline/select_radio.html +++ b/rest_framework/templates/rest_framework/fields/inline/select_radio.html @@ -1,5 +1,7 @@ <div class="form-group"> - {% include "rest_framework/fields/inline/label.html" %} + {% if field.label %} + <label class="sr-only">{{ field.label }}</label> + {% endif %} {% for key, text in field.choices.items %} <div class="radio"> <label> diff --git a/rest_framework/templates/rest_framework/fields/inline/textarea.html b/rest_framework/templates/rest_framework/fields/inline/textarea.html index 8259487b3..a644ea382 100644 --- a/rest_framework/templates/rest_framework/fields/inline/textarea.html +++ b/rest_framework/templates/rest_framework/fields/inline/textarea.html @@ -1,4 +1,6 @@ <div class="form-group"> - {% include "rest_framework/fields/inline/label.html" %} - <textarea class="form-control" {% include "rest_framework/fields/attrs.html" %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> + {% if field.label %} + <label class="sr-only">{{ field.label }}</label> + {% endif %} + <textarea name="{{ field.name }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.style.rows %}rows="{{ field.style.rows }}"{% endif %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> </div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/input.html b/rest_framework/templates/rest_framework/fields/vertical/input.html index 3ee2716af..10a576b2a 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/input.html +++ b/rest_framework/templates/rest_framework/fields/vertical/input.html @@ -1,5 +1,7 @@ <div class="form-group"> - {% include "rest_framework/fields/vertical/label.html" %} - <input type="{{ input_type }}" class="form-control" {% include "rest_framework/fields/attrs.html" %} {% if field.value %}value="{{ field.value }}"{% endif %}> + {% if field.label %} + <label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + {% endif %} + <input name="{{ field.name }}" type="{{ input_type }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.style.rows %}rows="{{ field.style.rows }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} </div> diff --git a/rest_framework/templates/rest_framework/fields/vertical/label.html b/rest_framework/templates/rest_framework/fields/vertical/label.html deleted file mode 100644 index 651939b26..000000000 --- a/rest_framework/templates/rest_framework/fields/vertical/label.html +++ /dev/null @@ -1 +0,0 @@ -{% if field.label %}<label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label>{% endif %} diff --git a/rest_framework/templates/rest_framework/fields/vertical/select.html b/rest_framework/templates/rest_framework/fields/vertical/select.html index 1a651663f..b0545f7e1 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/select.html +++ b/rest_framework/templates/rest_framework/fields/vertical/select.html @@ -1,5 +1,7 @@ <div class="form-group"> - {% include "rest_framework/fields/vertical/label.html" %} + {% if field.label %} + <label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + {% endif %} <select class="form-control" name="{{ field.name }}"> {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option> diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html b/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html index 2e792e6a5..c486b1b39 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html +++ b/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html @@ -1,5 +1,7 @@ <div class="form-group"> - {% include "rest_framework/fields/vertical/label.html" %} + {% if field.label %} + <label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + {% endif %} {% if field.style.inline %} <div> {% for key, text in field.choices.items %} diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html b/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html index 5f4166cd9..ca63192e9 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html +++ b/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html @@ -1,5 +1,7 @@ <div class="form-group"> - {% include "rest_framework/fields/vertical/label.html" %} + {% if field.label %} + <label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + {% endif %} <select multiple class="form-control" name="{{ field.name }}"> {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key in field.value %}selected{% endif %}>{{ text }}</option> diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_radio.html b/rest_framework/templates/rest_framework/fields/vertical/select_radio.html index 2aa0fe289..d7655b008 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/select_radio.html +++ b/rest_framework/templates/rest_framework/fields/vertical/select_radio.html @@ -1,5 +1,7 @@ <div class="form-group"> - {% include "rest_framework/fields/vertical/label.html" %} + {% if field.label %} + <label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + {% endif %} {% if field.style.inline %} <div> {% for key, text in field.choices.items %} diff --git a/rest_framework/templates/rest_framework/fields/vertical/textarea.html b/rest_framework/templates/rest_framework/fields/vertical/textarea.html index 406cfa77d..8d9514961 100644 --- a/rest_framework/templates/rest_framework/fields/vertical/textarea.html +++ b/rest_framework/templates/rest_framework/fields/vertical/textarea.html @@ -1,5 +1,7 @@ <div class="form-group"> - {% include "rest_framework/fields/vertical/label.html" %} - <textarea class="form-control" {% include "rest_framework/fields/attrs.html" %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> + {% if field.label %} + <label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + {% endif %} + <textarea name="{{ field.name }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.style.rows %}rows="{{ field.style.rows }}"{% endif %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} </div> From cc1c4232554153ac6a24b6b4f89ecaac80b28bfd Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 15 Oct 2014 11:12:34 +0100 Subject: [PATCH 152/249] Reorganize to use template_pack in form rendering --- rest_framework/renderers.py | 15 +++------ .../fields/inline/textarea.html | 6 ---- .../templates/rest_framework/form.html | 33 ------------------- .../fields}/checkbox.html | 0 .../fields}/fieldset.html | 0 .../fields}/input.html | 0 .../fields}/list_fieldset.html | 0 .../fields}/select.html | 0 .../fields}/select_checkbox.html | 0 .../fields}/select_multiple.html | 0 .../fields}/select_radio.html | 0 .../fields}/textarea.html | 0 .../rest_framework/horizontal/form.html | 15 +++++++++ .../inline => inline/fields}/checkbox.html | 0 .../inline => inline/fields}/fieldset.html | 0 .../inline => inline/fields}/input.html | 0 .../inline => inline/fields}/select.html | 0 .../fields}/select_checkbox.html | 0 .../fields}/select_multiple.html | 0 .../fields}/select_radio.html | 0 .../inline/fields/textarea.html | 6 ++++ .../templates/rest_framework/inline/form.html | 11 +++++++ .../fields}/checkbox.html | 0 .../fields}/fieldset.html | 0 .../vertical => vertical/fields}/input.html | 0 .../fields}/list_fieldset.html | 0 .../vertical => vertical/fields}/select.html | 0 .../fields}/select_checkbox.html | 0 .../fields}/select_multiple.html | 0 .../fields}/select_radio.html | 0 .../fields}/textarea.html | 0 .../rest_framework/vertical/form.html | 11 +++++++ rest_framework/templatetags/rest_framework.py | 4 +-- 33 files changed, 49 insertions(+), 52 deletions(-) delete mode 100644 rest_framework/templates/rest_framework/fields/inline/textarea.html delete mode 100644 rest_framework/templates/rest_framework/form.html rename rest_framework/templates/rest_framework/{fields/horizontal => horizontal/fields}/checkbox.html (100%) rename rest_framework/templates/rest_framework/{fields/horizontal => horizontal/fields}/fieldset.html (100%) rename rest_framework/templates/rest_framework/{fields/horizontal => horizontal/fields}/input.html (100%) rename rest_framework/templates/rest_framework/{fields/horizontal => horizontal/fields}/list_fieldset.html (100%) rename rest_framework/templates/rest_framework/{fields/horizontal => horizontal/fields}/select.html (100%) rename rest_framework/templates/rest_framework/{fields/horizontal => horizontal/fields}/select_checkbox.html (100%) rename rest_framework/templates/rest_framework/{fields/horizontal => horizontal/fields}/select_multiple.html (100%) rename rest_framework/templates/rest_framework/{fields/horizontal => horizontal/fields}/select_radio.html (100%) rename rest_framework/templates/rest_framework/{fields/horizontal => horizontal/fields}/textarea.html (100%) create mode 100644 rest_framework/templates/rest_framework/horizontal/form.html rename rest_framework/templates/rest_framework/{fields/inline => inline/fields}/checkbox.html (100%) rename rest_framework/templates/rest_framework/{fields/inline => inline/fields}/fieldset.html (100%) rename rest_framework/templates/rest_framework/{fields/inline => inline/fields}/input.html (100%) rename rest_framework/templates/rest_framework/{fields/inline => inline/fields}/select.html (100%) rename rest_framework/templates/rest_framework/{fields/inline => inline/fields}/select_checkbox.html (100%) rename rest_framework/templates/rest_framework/{fields/inline => inline/fields}/select_multiple.html (100%) rename rest_framework/templates/rest_framework/{fields/inline => inline/fields}/select_radio.html (100%) create mode 100644 rest_framework/templates/rest_framework/inline/fields/textarea.html create mode 100644 rest_framework/templates/rest_framework/inline/form.html rename rest_framework/templates/rest_framework/{fields/vertical => vertical/fields}/checkbox.html (100%) rename rest_framework/templates/rest_framework/{fields/vertical => vertical/fields}/fieldset.html (100%) rename rest_framework/templates/rest_framework/{fields/vertical => vertical/fields}/input.html (100%) rename rest_framework/templates/rest_framework/{fields/vertical => vertical/fields}/list_fieldset.html (100%) rename rest_framework/templates/rest_framework/{fields/vertical => vertical/fields}/select.html (100%) rename rest_framework/templates/rest_framework/{fields/vertical => vertical/fields}/select_checkbox.html (100%) rename rest_framework/templates/rest_framework/{fields/vertical => vertical/fields}/select_multiple.html (100%) rename rest_framework/templates/rest_framework/{fields/vertical => vertical/fields}/select_radio.html (100%) rename rest_framework/templates/rest_framework/{fields/vertical => vertical/fields}/textarea.html (100%) create mode 100644 rest_framework/templates/rest_framework/vertical/form.html diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 4fb360609..5fae75f2e 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -339,7 +339,6 @@ class HTMLFormRenderer(BaseRenderer): """ media_type = 'text/html' format = 'form' - template = 'rest_framework/form.html' charset = 'utf-8' field_templates = ClassLookupDict({ @@ -383,26 +382,21 @@ class HTMLFormRenderer(BaseRenderer): serializers.TimeField: 'time', }) - def render_field(self, field, layout=None): - layout = layout or 'vertical' + def render_field(self, field, template_pack=None): style_type = field.style.get('type', 'default') - if style_type == 'textarea' and layout == 'inline': - style_type = 'default' input_type = self.input_type[field] if input_type == 'datetime-local' and isinstance(field.value, six.text_type): field.value = field.value.rstrip('Z') base = self.field_templates[field][style_type] - template_name = 'rest_framework/fields/' + layout + '/' + base + template_name = template_pack + '/fields/' + base template = loader.get_template(template_name) context = Context({ 'field': field, 'input_type': input_type, 'renderer': self, - 'layout': layout }) - return template.render(context) def render(self, data, accepted_media_type=None, renderer_context=None): @@ -411,11 +405,10 @@ class HTMLFormRenderer(BaseRenderer): """ renderer_context = renderer_context or {} request = renderer_context['request'] - - template = loader.get_template(self.template) + template = loader.get_template('rest_framework/horizontal/form.html') context = RequestContext(request, { 'form': data.serializer, - 'layout': getattr(getattr(data, 'Meta', None), 'layout', 'horizontal'), + 'template_pack': 'rest_framework/horizontal', 'renderer': self }) return template.render(context) diff --git a/rest_framework/templates/rest_framework/fields/inline/textarea.html b/rest_framework/templates/rest_framework/fields/inline/textarea.html deleted file mode 100644 index a644ea382..000000000 --- a/rest_framework/templates/rest_framework/fields/inline/textarea.html +++ /dev/null @@ -1,6 +0,0 @@ -<div class="form-group"> - {% if field.label %} - <label class="sr-only">{{ field.label }}</label> - {% endif %} - <textarea name="{{ field.name }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.style.rows %}rows="{{ field.style.rows }}"{% endif %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> -</div> diff --git a/rest_framework/templates/rest_framework/form.html b/rest_framework/templates/rest_framework/form.html deleted file mode 100644 index 162c56336..000000000 --- a/rest_framework/templates/rest_framework/form.html +++ /dev/null @@ -1,33 +0,0 @@ -<!-- <html> -<head> - <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> -</head> -<body> -<div class="container"> - -<h1>User update</h1> -<div class="well"> --> - -{% load rest_framework %} -<form {% if layout == "inline" %}class="form-inline"{% elif layout == "horizontal" %}class="form-horizontal"{% endif %} role="form" action="." method="POST"> - {% csrf_token %} - {% for field in form %} - {% if not field.read_only %} - {% render_field field layout=layout renderer=renderer %} - {% endif %} - {% endfor %} - <!-- form.non_field_errors --> - {% if layout == "horizontal" %} - <div class="form-group"> - <div class="col-sm-offset-2 col-sm-10"> - <button type="submit" class="btn btn-default">Submit</button> - </div> - </div> - {% else %} - <button type="submit" class="btn btn-default">Submit</button> - {% endif %} -</form> -<!-- -</div> -</div></body> -</html> --> diff --git a/rest_framework/templates/rest_framework/fields/horizontal/checkbox.html b/rest_framework/templates/rest_framework/horizontal/fields/checkbox.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/horizontal/checkbox.html rename to rest_framework/templates/rest_framework/horizontal/fields/checkbox.html diff --git a/rest_framework/templates/rest_framework/fields/horizontal/fieldset.html b/rest_framework/templates/rest_framework/horizontal/fields/fieldset.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/horizontal/fieldset.html rename to rest_framework/templates/rest_framework/horizontal/fields/fieldset.html diff --git a/rest_framework/templates/rest_framework/fields/horizontal/input.html b/rest_framework/templates/rest_framework/horizontal/fields/input.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/horizontal/input.html rename to rest_framework/templates/rest_framework/horizontal/fields/input.html diff --git a/rest_framework/templates/rest_framework/fields/horizontal/list_fieldset.html b/rest_framework/templates/rest_framework/horizontal/fields/list_fieldset.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/horizontal/list_fieldset.html rename to rest_framework/templates/rest_framework/horizontal/fields/list_fieldset.html diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select.html b/rest_framework/templates/rest_framework/horizontal/fields/select.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/horizontal/select.html rename to rest_framework/templates/rest_framework/horizontal/fields/select.html diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html b/rest_framework/templates/rest_framework/horizontal/fields/select_checkbox.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/horizontal/select_checkbox.html rename to rest_framework/templates/rest_framework/horizontal/fields/select_checkbox.html diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html b/rest_framework/templates/rest_framework/horizontal/fields/select_multiple.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/horizontal/select_multiple.html rename to rest_framework/templates/rest_framework/horizontal/fields/select_multiple.html diff --git a/rest_framework/templates/rest_framework/fields/horizontal/select_radio.html b/rest_framework/templates/rest_framework/horizontal/fields/select_radio.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/horizontal/select_radio.html rename to rest_framework/templates/rest_framework/horizontal/fields/select_radio.html diff --git a/rest_framework/templates/rest_framework/fields/horizontal/textarea.html b/rest_framework/templates/rest_framework/horizontal/fields/textarea.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/horizontal/textarea.html rename to rest_framework/templates/rest_framework/horizontal/fields/textarea.html diff --git a/rest_framework/templates/rest_framework/horizontal/form.html b/rest_framework/templates/rest_framework/horizontal/form.html new file mode 100644 index 000000000..7560d8a26 --- /dev/null +++ b/rest_framework/templates/rest_framework/horizontal/form.html @@ -0,0 +1,15 @@ +{% load rest_framework %} +<form class="form-horizontal" role="form" action="." method="POST"> + {% csrf_token %} + {% for field in form %} + {% if not field.read_only %} + {% render_field field template_pack=template_pack renderer=renderer %} + {% endif %} + {% endfor %} + <!-- form.non_field_errors --> + <div class="form-group"> + <div class="col-sm-offset-2 col-sm-10"> + <button type="submit" class="btn btn-default">Submit</button> + </div> + </div> +</form> diff --git a/rest_framework/templates/rest_framework/fields/inline/checkbox.html b/rest_framework/templates/rest_framework/inline/fields/checkbox.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/inline/checkbox.html rename to rest_framework/templates/rest_framework/inline/fields/checkbox.html diff --git a/rest_framework/templates/rest_framework/fields/inline/fieldset.html b/rest_framework/templates/rest_framework/inline/fields/fieldset.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/inline/fieldset.html rename to rest_framework/templates/rest_framework/inline/fields/fieldset.html diff --git a/rest_framework/templates/rest_framework/fields/inline/input.html b/rest_framework/templates/rest_framework/inline/fields/input.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/inline/input.html rename to rest_framework/templates/rest_framework/inline/fields/input.html diff --git a/rest_framework/templates/rest_framework/fields/inline/select.html b/rest_framework/templates/rest_framework/inline/fields/select.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/inline/select.html rename to rest_framework/templates/rest_framework/inline/fields/select.html diff --git a/rest_framework/templates/rest_framework/fields/inline/select_checkbox.html b/rest_framework/templates/rest_framework/inline/fields/select_checkbox.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/inline/select_checkbox.html rename to rest_framework/templates/rest_framework/inline/fields/select_checkbox.html diff --git a/rest_framework/templates/rest_framework/fields/inline/select_multiple.html b/rest_framework/templates/rest_framework/inline/fields/select_multiple.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/inline/select_multiple.html rename to rest_framework/templates/rest_framework/inline/fields/select_multiple.html diff --git a/rest_framework/templates/rest_framework/fields/inline/select_radio.html b/rest_framework/templates/rest_framework/inline/fields/select_radio.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/inline/select_radio.html rename to rest_framework/templates/rest_framework/inline/fields/select_radio.html diff --git a/rest_framework/templates/rest_framework/inline/fields/textarea.html b/rest_framework/templates/rest_framework/inline/fields/textarea.html new file mode 100644 index 000000000..bdf25ffe6 --- /dev/null +++ b/rest_framework/templates/rest_framework/inline/fields/textarea.html @@ -0,0 +1,6 @@ +<div class="form-group"> + {% if field.label %} + <label class="sr-only">{{ field.label }}</label> + {% endif %} + <input name="{{ field.name }}" type="{{ input_type }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> +</div> diff --git a/rest_framework/templates/rest_framework/inline/form.html b/rest_framework/templates/rest_framework/inline/form.html new file mode 100644 index 000000000..b13d16614 --- /dev/null +++ b/rest_framework/templates/rest_framework/inline/form.html @@ -0,0 +1,11 @@ +{% load rest_framework %} +<form class="form-inline" role="form" action="." method="POST"> + {% csrf_token %} + {% for field in form %} + {% if not field.read_only %} + {% render_field field template_pack=template_pack renderer=renderer %} + {% endif %} + {% endfor %} + <!-- form.non_field_errors --> + <button type="submit" class="btn btn-default">Submit</button> +</form> diff --git a/rest_framework/templates/rest_framework/fields/vertical/checkbox.html b/rest_framework/templates/rest_framework/vertical/fields/checkbox.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/vertical/checkbox.html rename to rest_framework/templates/rest_framework/vertical/fields/checkbox.html diff --git a/rest_framework/templates/rest_framework/fields/vertical/fieldset.html b/rest_framework/templates/rest_framework/vertical/fields/fieldset.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/vertical/fieldset.html rename to rest_framework/templates/rest_framework/vertical/fields/fieldset.html diff --git a/rest_framework/templates/rest_framework/fields/vertical/input.html b/rest_framework/templates/rest_framework/vertical/fields/input.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/vertical/input.html rename to rest_framework/templates/rest_framework/vertical/fields/input.html diff --git a/rest_framework/templates/rest_framework/fields/vertical/list_fieldset.html b/rest_framework/templates/rest_framework/vertical/fields/list_fieldset.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/vertical/list_fieldset.html rename to rest_framework/templates/rest_framework/vertical/fields/list_fieldset.html diff --git a/rest_framework/templates/rest_framework/fields/vertical/select.html b/rest_framework/templates/rest_framework/vertical/fields/select.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/vertical/select.html rename to rest_framework/templates/rest_framework/vertical/fields/select.html diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html b/rest_framework/templates/rest_framework/vertical/fields/select_checkbox.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/vertical/select_checkbox.html rename to rest_framework/templates/rest_framework/vertical/fields/select_checkbox.html diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_multiple.html b/rest_framework/templates/rest_framework/vertical/fields/select_multiple.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/vertical/select_multiple.html rename to rest_framework/templates/rest_framework/vertical/fields/select_multiple.html diff --git a/rest_framework/templates/rest_framework/fields/vertical/select_radio.html b/rest_framework/templates/rest_framework/vertical/fields/select_radio.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/vertical/select_radio.html rename to rest_framework/templates/rest_framework/vertical/fields/select_radio.html diff --git a/rest_framework/templates/rest_framework/fields/vertical/textarea.html b/rest_framework/templates/rest_framework/vertical/fields/textarea.html similarity index 100% rename from rest_framework/templates/rest_framework/fields/vertical/textarea.html rename to rest_framework/templates/rest_framework/vertical/fields/textarea.html diff --git a/rest_framework/templates/rest_framework/vertical/form.html b/rest_framework/templates/rest_framework/vertical/form.html new file mode 100644 index 000000000..fe908af02 --- /dev/null +++ b/rest_framework/templates/rest_framework/vertical/form.html @@ -0,0 +1,11 @@ +{% load rest_framework %} +<form role="form" action="." method="POST"> + {% csrf_token %} + {% for field in form %} + {% if not field.read_only %} + {% render_field field template_pack=template_pack renderer=renderer %} + {% endif %} + {% endfor %} + <!-- form.non_field_errors --> + <button type="submit" class="btn btn-default">Submit</button> +</form> diff --git a/rest_framework/templatetags/rest_framework.py b/rest_framework/templatetags/rest_framework.py index 49a4c3389..c092d39f6 100644 --- a/rest_framework/templatetags/rest_framework.py +++ b/rest_framework/templatetags/rest_framework.py @@ -32,8 +32,8 @@ class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])') # And the template tags themselves... @register.simple_tag -def render_field(field, layout=None, renderer=None): - return renderer.render_field(field, layout) +def render_field(field, template_pack=None, renderer=None): + return renderer.render_field(field, template_pack) @register.simple_tag From 36fbc7678c3437dfe2d70380ab1b153429641bb5 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 15 Oct 2014 13:35:12 +0100 Subject: [PATCH 153/249] Moar form styling --- .../templates/rest_framework/base.html | 2 +- .../horizontal/fields/checkbox.html | 8 +++++++- ...t_checkbox.html => checkbox_multiple.html} | 10 ++++++++-- .../horizontal/fields/fieldset.html | 4 ++-- .../horizontal/fields/input.html | 13 ++++++++---- .../horizontal/fields/list_fieldset.html | 2 +- .../fields/{select_radio.html => radio.html} | 10 ++++++++-- .../horizontal/fields/select.html | 8 +++++++- .../horizontal/fields/select_multiple.html | 8 +++++++- .../horizontal/fields/textarea.html | 13 ++++++++---- .../inline/fields/checkbox.html | 12 ++++++----- ...t_checkbox.html => checkbox_multiple.html} | 2 +- .../inline/fields/fieldset.html | 2 +- .../rest_framework/inline/fields/input.html | 4 ++-- .../fields/{select_radio.html => radio.html} | 2 +- .../rest_framework/inline/fields/select.html | 2 +- .../inline/fields/select_multiple.html | 2 +- .../inline/fields/textarea.html | 4 ++-- .../vertical/fields/checkbox.html | 20 +++++++++++++------ ...t_checkbox.html => checkbox_multiple.html} | 12 ++++++++--- .../vertical/fields/fieldset.html | 4 ++-- .../rest_framework/vertical/fields/input.html | 13 ++++++++---- .../vertical/fields/list_fieldset.html | 4 ++-- .../fields/{select_radio.html => radio.html} | 12 ++++++++--- .../vertical/fields/select.html | 10 ++++++++-- .../vertical/fields/select_multiple.html | 10 ++++++++-- .../vertical/fields/textarea.html | 13 ++++++++---- 27 files changed, 145 insertions(+), 61 deletions(-) rename rest_framework/templates/rest_framework/horizontal/fields/{select_checkbox.html => checkbox_multiple.html} (66%) rename rest_framework/templates/rest_framework/horizontal/fields/{select_radio.html => radio.html} (66%) rename rest_framework/templates/rest_framework/inline/fields/{select_checkbox.html => checkbox_multiple.html} (85%) rename rest_framework/templates/rest_framework/inline/fields/{select_radio.html => radio.html} (85%) rename rest_framework/templates/rest_framework/vertical/fields/{select_checkbox.html => checkbox_multiple.html} (62%) rename rest_framework/templates/rest_framework/vertical/fields/{select_radio.html => radio.html} (62%) diff --git a/rest_framework/templates/rest_framework/base.html b/rest_framework/templates/rest_framework/base.html index 2e03dd987..4b6c7fcfc 100644 --- a/rest_framework/templates/rest_framework/base.html +++ b/rest_framework/templates/rest_framework/base.html @@ -59,7 +59,7 @@ <ul class="breadcrumb"> {% for breadcrumb_name, breadcrumb_url in breadcrumblist %} {% if forloop.last %} - <li class="active">{{ breadcrumb_name }}</li> + <li class="active"><a href="{{ breadcrumb_url }}">{{ breadcrumb_name }}</a></li> {% else %} <li><a href="{{ breadcrumb_url }}">{{ breadcrumb_name }}</a></li> {% endif %} diff --git a/rest_framework/templates/rest_framework/horizontal/fields/checkbox.html b/rest_framework/templates/rest_framework/horizontal/fields/checkbox.html index ee3bf9366..07a7308f0 100644 --- a/rest_framework/templates/rest_framework/horizontal/fields/checkbox.html +++ b/rest_framework/templates/rest_framework/horizontal/fields/checkbox.html @@ -1,4 +1,4 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> @@ -6,5 +6,11 @@ {% if field.label %}{{ field.label }}{% endif %} </label> </div> + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> + {% endif %} </div> </div> diff --git a/rest_framework/templates/rest_framework/horizontal/fields/select_checkbox.html b/rest_framework/templates/rest_framework/horizontal/fields/checkbox_multiple.html similarity index 66% rename from rest_framework/templates/rest_framework/horizontal/fields/select_checkbox.html rename to rest_framework/templates/rest_framework/horizontal/fields/checkbox_multiple.html index ff3fab573..ec7d59356 100644 --- a/rest_framework/templates/rest_framework/horizontal/fields/select_checkbox.html +++ b/rest_framework/templates/rest_framework/horizontal/fields/checkbox_multiple.html @@ -1,9 +1,9 @@ <div class="form-group"> {% if field.label %} - <label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> + <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> {% endif %} <div class="col-sm-10"> - {% if field.style.inline %} + {% if style.inline %} {% for key, text in field.choices.items %} <label class="checkbox-inline"> <input type="checkbox" name="{{ field.name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}> @@ -20,5 +20,11 @@ </div> {% endfor %} {% endif %} + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> + {% endif %} </div> </div> diff --git a/rest_framework/templates/rest_framework/horizontal/fields/fieldset.html b/rest_framework/templates/rest_framework/horizontal/fields/fieldset.html index ff93c6baa..f6d5dd9d2 100644 --- a/rest_framework/templates/rest_framework/horizontal/fields/fieldset.html +++ b/rest_framework/templates/rest_framework/horizontal/fields/fieldset.html @@ -2,10 +2,10 @@ <fieldset> {% if field.label %} <div class="form-group" style="border-bottom: 1px solid #e5e5e5"> - <legend class="control-label col-sm-2 {% if field.style.hide_label %}sr-only{% endif %}" style="border-bottom: 0">{{ field.label }}</legend> + <legend class="control-label col-sm-2 {% if style.hide_label %}sr-only{% endif %}" style="border-bottom: 0">{{ field.label }}</legend> </div> {% endif %} {% for nested_field in field %} - {% render_field nested_field layout=layout renderer=renderer %} + {% render_field nested_field template_pack=template_pack renderer=renderer %} {% endfor %} </fieldset> diff --git a/rest_framework/templates/rest_framework/horizontal/fields/input.html b/rest_framework/templates/rest_framework/horizontal/fields/input.html index 6621c7e60..43ab41512 100644 --- a/rest_framework/templates/rest_framework/horizontal/fields/input.html +++ b/rest_framework/templates/rest_framework/horizontal/fields/input.html @@ -1,9 +1,14 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} - <label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> + <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> {% endif %} <div class="col-sm-10"> - <input name="{{ field.name }}" type="{{ input_type }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> - {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} + <input name="{{ field.name }}" class="form-control" type="{{ style.input_type }}" novalidate {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> + {% endif %} </div> </div> diff --git a/rest_framework/templates/rest_framework/horizontal/fields/list_fieldset.html b/rest_framework/templates/rest_framework/horizontal/fields/list_fieldset.html index 68c75d4f8..a30514c68 100644 --- a/rest_framework/templates/rest_framework/horizontal/fields/list_fieldset.html +++ b/rest_framework/templates/rest_framework/horizontal/fields/list_fieldset.html @@ -2,7 +2,7 @@ <fieldset> {% if field.label %} <div class="form-group" style="border-bottom: 1px solid #e5e5e5"> - <legend class="control-label col-sm-2 {% if field.style.hide_label %}sr-only{% endif %}" style="border-bottom: 0">{{ field.label }}</legend> + <legend class="control-label col-sm-2 {% if style.hide_label %}sr-only{% endif %}" style="border-bottom: 0">{{ field.label }}</legend> </div> {% endif %} <ul> diff --git a/rest_framework/templates/rest_framework/horizontal/fields/select_radio.html b/rest_framework/templates/rest_framework/horizontal/fields/radio.html similarity index 66% rename from rest_framework/templates/rest_framework/horizontal/fields/select_radio.html rename to rest_framework/templates/rest_framework/horizontal/fields/radio.html index 6e56afb52..52238bb1a 100644 --- a/rest_framework/templates/rest_framework/horizontal/fields/select_radio.html +++ b/rest_framework/templates/rest_framework/horizontal/fields/radio.html @@ -1,9 +1,9 @@ <div class="form-group"> {% if field.label %} - <label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> + <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> {% endif %} <div class="col-sm-10"> - {% if field.style.inline %} + {% if style.inline %} {% for key, text in field.choices.items %} <label class="radio-inline"> <input type="radio" name="{{ field.name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}> @@ -20,5 +20,11 @@ </div> {% endfor %} {% endif %} + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> + {% endif %} </div> </div> diff --git a/rest_framework/templates/rest_framework/horizontal/fields/select.html b/rest_framework/templates/rest_framework/horizontal/fields/select.html index eaa6d575a..1d00f4241 100644 --- a/rest_framework/templates/rest_framework/horizontal/fields/select.html +++ b/rest_framework/templates/rest_framework/horizontal/fields/select.html @@ -1,6 +1,6 @@ <div class="form-group"> {% if field.label %} - <label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> + <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> {% endif %} <div class="col-sm-10"> <select class="form-control" name="{{ field.name }}"> @@ -8,5 +8,11 @@ <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} </select> + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> + {% endif %} </div> </div> diff --git a/rest_framework/templates/rest_framework/horizontal/fields/select_multiple.html b/rest_framework/templates/rest_framework/horizontal/fields/select_multiple.html index 3ed2874b2..01c251fb0 100644 --- a/rest_framework/templates/rest_framework/horizontal/fields/select_multiple.html +++ b/rest_framework/templates/rest_framework/horizontal/fields/select_multiple.html @@ -1,6 +1,6 @@ <div class="form-group"> {% if field.label %} - <label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> + <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> {% endif %} <div class="col-sm-10"> <select multiple class="form-control" name="{{ field.name }}"> @@ -8,5 +8,11 @@ <option value="{{ key }}" {% if key in field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} </select> + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> + {% endif %} </div> </div> diff --git a/rest_framework/templates/rest_framework/horizontal/fields/textarea.html b/rest_framework/templates/rest_framework/horizontal/fields/textarea.html index ae263c48c..ec1075495 100644 --- a/rest_framework/templates/rest_framework/horizontal/fields/textarea.html +++ b/rest_framework/templates/rest_framework/horizontal/fields/textarea.html @@ -1,9 +1,14 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} - <label class="col-sm-2 control-label {% if field.style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> + <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> {% endif %} <div class="col-sm-10"> - <textarea name="{{ field.name }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.style.rows %}rows="{{ field.style.rows }}"{% endif %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> - {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} + <textarea name="{{ field.name }}" class="form-control" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if style.rows %}rows="{{ style.rows }}"{% endif %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> + {% endif %} </div> </div> diff --git a/rest_framework/templates/rest_framework/inline/fields/checkbox.html b/rest_framework/templates/rest_framework/inline/fields/checkbox.html index 57fa5dc04..71737f15f 100644 --- a/rest_framework/templates/rest_framework/inline/fields/checkbox.html +++ b/rest_framework/templates/rest_framework/inline/fields/checkbox.html @@ -1,6 +1,8 @@ -<div class="checkbox"> - <label> - <input type="checkbox" name="{{ field.name }}" value="true" {% if field.value %}checked{% endif %}> - {% if field.label %}{{ field.label }}{% endif %} - </label> +<div class="form-group {% if field.errors %}has-error{% endif %}"> + <div class="checkbox"> + <label> + <input type="checkbox" name="{{ field.name }}" value="true" {% if field.value %}checked{% endif %}> + {% if field.label %}{{ field.label }}{% endif %} + </label> + </div> </div> diff --git a/rest_framework/templates/rest_framework/inline/fields/select_checkbox.html b/rest_framework/templates/rest_framework/inline/fields/checkbox_multiple.html similarity index 85% rename from rest_framework/templates/rest_framework/inline/fields/select_checkbox.html rename to rest_framework/templates/rest_framework/inline/fields/checkbox_multiple.html index cca71d689..6caf64403 100644 --- a/rest_framework/templates/rest_framework/inline/fields/select_checkbox.html +++ b/rest_framework/templates/rest_framework/inline/fields/checkbox_multiple.html @@ -1,4 +1,4 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} <label class="sr-only">{{ field.label }}</label> {% endif %} diff --git a/rest_framework/templates/rest_framework/inline/fields/fieldset.html b/rest_framework/templates/rest_framework/inline/fields/fieldset.html index ba9f1835a..5ee182a5b 100644 --- a/rest_framework/templates/rest_framework/inline/fields/fieldset.html +++ b/rest_framework/templates/rest_framework/inline/fields/fieldset.html @@ -1,4 +1,4 @@ {% load rest_framework %} {% for nested_field in field %} - {% render_field nested_field layout=layout renderer=renderer %} + {% render_field nested_field template_pack=template_pack renderer=renderer %} {% endfor %} diff --git a/rest_framework/templates/rest_framework/inline/fields/input.html b/rest_framework/templates/rest_framework/inline/fields/input.html index bdf25ffe6..0d3eb8845 100644 --- a/rest_framework/templates/rest_framework/inline/fields/input.html +++ b/rest_framework/templates/rest_framework/inline/fields/input.html @@ -1,6 +1,6 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} <label class="sr-only">{{ field.label }}</label> {% endif %} - <input name="{{ field.name }}" type="{{ input_type }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> + <input name="{{ field.name }}" class="form-control" type="{{ style.input_type }}" novalidate {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> </div> diff --git a/rest_framework/templates/rest_framework/inline/fields/select_radio.html b/rest_framework/templates/rest_framework/inline/fields/radio.html similarity index 85% rename from rest_framework/templates/rest_framework/inline/fields/select_radio.html rename to rest_framework/templates/rest_framework/inline/fields/radio.html index 3fffceac4..1915f4f84 100644 --- a/rest_framework/templates/rest_framework/inline/fields/select_radio.html +++ b/rest_framework/templates/rest_framework/inline/fields/radio.html @@ -1,4 +1,4 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} <label class="sr-only">{{ field.label }}</label> {% endif %} diff --git a/rest_framework/templates/rest_framework/inline/fields/select.html b/rest_framework/templates/rest_framework/inline/fields/select.html index 730fcce61..e9fcebb48 100644 --- a/rest_framework/templates/rest_framework/inline/fields/select.html +++ b/rest_framework/templates/rest_framework/inline/fields/select.html @@ -1,4 +1,4 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} <label class="sr-only">{{ field.label }}</label> {% endif %} diff --git a/rest_framework/templates/rest_framework/inline/fields/select_multiple.html b/rest_framework/templates/rest_framework/inline/fields/select_multiple.html index 3f9b27017..feddf7abd 100644 --- a/rest_framework/templates/rest_framework/inline/fields/select_multiple.html +++ b/rest_framework/templates/rest_framework/inline/fields/select_multiple.html @@ -1,4 +1,4 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} <label class="sr-only">{{ field.label }}</label> {% endif %} diff --git a/rest_framework/templates/rest_framework/inline/fields/textarea.html b/rest_framework/templates/rest_framework/inline/fields/textarea.html index bdf25ffe6..0766a01c5 100644 --- a/rest_framework/templates/rest_framework/inline/fields/textarea.html +++ b/rest_framework/templates/rest_framework/inline/fields/textarea.html @@ -1,6 +1,6 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} <label class="sr-only">{{ field.label }}</label> {% endif %} - <input name="{{ field.name }}" type="{{ input_type }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> + <input name="{{ field.name }}" type="text" class="form-control" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> </div> diff --git a/rest_framework/templates/rest_framework/vertical/fields/checkbox.html b/rest_framework/templates/rest_framework/vertical/fields/checkbox.html index 9fd4cdaa2..e21a8e902 100644 --- a/rest_framework/templates/rest_framework/vertical/fields/checkbox.html +++ b/rest_framework/templates/rest_framework/vertical/fields/checkbox.html @@ -1,6 +1,14 @@ -<div class="checkbox"> - <label> - <input type="checkbox" name="{{ field.name }}" value="true" {% if value %}checked{% endif %}> - {% if field.label %}{{ field.label }}{% endif %} - </label> -</div> +<div class="form-group {% if field.errors %}has-error{% endif %}"> + <div class="checkbox"> + <label> + <input type="checkbox" name="{{ field.name }}" value="true" {% if value %}checked{% endif %}> + {% if field.label %}{{ field.label }}{% endif %} + </label> + </div> + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> + {% endif %} +</div> \ No newline at end of file diff --git a/rest_framework/templates/rest_framework/vertical/fields/select_checkbox.html b/rest_framework/templates/rest_framework/vertical/fields/checkbox_multiple.html similarity index 62% rename from rest_framework/templates/rest_framework/vertical/fields/select_checkbox.html rename to rest_framework/templates/rest_framework/vertical/fields/checkbox_multiple.html index c486b1b39..134cca661 100644 --- a/rest_framework/templates/rest_framework/vertical/fields/select_checkbox.html +++ b/rest_framework/templates/rest_framework/vertical/fields/checkbox_multiple.html @@ -1,8 +1,8 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} - <label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> {% endif %} - {% if field.style.inline %} + {% if style.inline %} <div> {% for key, text in field.choices.items %} <label class="checkbox-inline"> @@ -21,4 +21,10 @@ </div> {% endfor %} {% endif %} + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> + {% endif %} </div> diff --git a/rest_framework/templates/rest_framework/vertical/fields/fieldset.html b/rest_framework/templates/rest_framework/vertical/fields/fieldset.html index 248fe9044..824e6098f 100644 --- a/rest_framework/templates/rest_framework/vertical/fields/fieldset.html +++ b/rest_framework/templates/rest_framework/vertical/fields/fieldset.html @@ -1,7 +1,7 @@ {% load rest_framework %} <fieldset> - {% if field.label %}<legend {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %} + {% if field.label %}<legend {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %} {% for nested_field in field %} - {% render_field nested_field layout=layout renderer=renderer %} + {% render_field nested_field template_pack=template_pack renderer=renderer %} {% endfor %} </fieldset> diff --git a/rest_framework/templates/rest_framework/vertical/fields/input.html b/rest_framework/templates/rest_framework/vertical/fields/input.html index 10a576b2a..4f4cb017a 100644 --- a/rest_framework/templates/rest_framework/vertical/fields/input.html +++ b/rest_framework/templates/rest_framework/vertical/fields/input.html @@ -1,7 +1,12 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} - <label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + {% endif %} + <input name="{{ field.name }}" class="form-control" type="{{ style.input_type }}" novalidate {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> {% endif %} - <input name="{{ field.name }}" type="{{ input_type }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.style.rows %}rows="{{ field.style.rows }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> - {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} </div> diff --git a/rest_framework/templates/rest_framework/vertical/fields/list_fieldset.html b/rest_framework/templates/rest_framework/vertical/fields/list_fieldset.html index 6b99a8349..74bbf4483 100644 --- a/rest_framework/templates/rest_framework/vertical/fields/list_fieldset.html +++ b/rest_framework/templates/rest_framework/vertical/fields/list_fieldset.html @@ -1,6 +1,6 @@ <fieldset> - {% if field.label %}<legend {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %} -<!-- {% if field.label %}<legend {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %} + {% if field.label %}<legend {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %} +<!-- {% if field.label %}<legend {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %} {% for field_item in field.value.field_items.values() %} {{ renderer.render_field(field_item, layout=layout) }} {% endfor %} --> diff --git a/rest_framework/templates/rest_framework/vertical/fields/select_radio.html b/rest_framework/templates/rest_framework/vertical/fields/radio.html similarity index 62% rename from rest_framework/templates/rest_framework/vertical/fields/select_radio.html rename to rest_framework/templates/rest_framework/vertical/fields/radio.html index d7655b008..ed9f9ddbb 100644 --- a/rest_framework/templates/rest_framework/vertical/fields/select_radio.html +++ b/rest_framework/templates/rest_framework/vertical/fields/radio.html @@ -1,8 +1,8 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} - <label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> {% endif %} - {% if field.style.inline %} + {% if style.inline %} <div> {% for key, text in field.choices.items %} <label class="radio-inline"> @@ -21,4 +21,10 @@ </div> {% endfor %} {% endif %} + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> + {% endif %} </div> diff --git a/rest_framework/templates/rest_framework/vertical/fields/select.html b/rest_framework/templates/rest_framework/vertical/fields/select.html index b0545f7e1..7c673ebb5 100644 --- a/rest_framework/templates/rest_framework/vertical/fields/select.html +++ b/rest_framework/templates/rest_framework/vertical/fields/select.html @@ -1,10 +1,16 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} - <label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> {% endif %} <select class="form-control" name="{{ field.name }}"> {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} </select> + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> + {% endif %} </div> diff --git a/rest_framework/templates/rest_framework/vertical/fields/select_multiple.html b/rest_framework/templates/rest_framework/vertical/fields/select_multiple.html index ca63192e9..54839294a 100644 --- a/rest_framework/templates/rest_framework/vertical/fields/select_multiple.html +++ b/rest_framework/templates/rest_framework/vertical/fields/select_multiple.html @@ -1,10 +1,16 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} - <label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> {% endif %} <select multiple class="form-control" name="{{ field.name }}"> {% for key, text in field.choices.items %} <option value="{{ key }}" {% if key in field.value %}selected{% endif %}>{{ text }}</option> {% endfor %} </select> + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> + {% endif %} </div> diff --git a/rest_framework/templates/rest_framework/vertical/fields/textarea.html b/rest_framework/templates/rest_framework/vertical/fields/textarea.html index 8d9514961..840ea853c 100644 --- a/rest_framework/templates/rest_framework/vertical/fields/textarea.html +++ b/rest_framework/templates/rest_framework/vertical/fields/textarea.html @@ -1,7 +1,12 @@ -<div class="form-group"> +<div class="form-group {% if field.errors %}has-error{% endif %}"> {% if field.label %} - <label {% if field.style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> + {% endif %} + <textarea name="{{ field.name }}" class="form-control" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if style.rows %}rows="{{ style.rows }}"{% endif %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> + {% if field.errors %} + {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} + {% endif %} + {% if field.help_text %} + <span class="help-block">{{ field.help_text }}</span> {% endif %} - <textarea name="{{ field.name }}" class="form-control" {% if field.style.placeholder %}placeholder="{{ field.style.placeholder }}"{% endif %} {% if field.style.rows %}rows="{{ field.style.rows }}"{% endif %}>{% if field.value %}{{ field.value }}{% endif %}</textarea> - {% if field.help_text %}<p class="help-block">{{ field.help_text }}</p>{% endif %} </div> From e8ea365c15b13185efc2ba03e57a3302f783d538 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 15 Oct 2014 15:11:01 +0100 Subject: [PATCH 154/249] Moar form styling --- rest_framework/templates/rest_framework/base.html | 4 ++-- .../rest_framework/horizontal/{fields => }/checkbox.html | 0 .../horizontal/{fields => }/checkbox_multiple.html | 0 .../rest_framework/horizontal/{fields => }/fieldset.html | 0 rest_framework/templates/rest_framework/horizontal/form.html | 4 ++-- .../rest_framework/horizontal/{fields => }/input.html | 2 +- .../rest_framework/horizontal/{fields => }/list_fieldset.html | 0 .../rest_framework/horizontal/{fields => }/radio.html | 0 .../rest_framework/horizontal/{fields => }/select.html | 0 .../horizontal/{fields => }/select_multiple.html | 0 .../rest_framework/horizontal/{fields => }/textarea.html | 0 .../rest_framework/inline/{fields => }/checkbox.html | 0 .../rest_framework/inline/{fields => }/checkbox_multiple.html | 0 .../rest_framework/inline/{fields => }/fieldset.html | 0 rest_framework/templates/rest_framework/inline/form.html | 4 ++-- .../templates/rest_framework/inline/{fields => }/input.html | 2 +- .../templates/rest_framework/inline/{fields => }/radio.html | 0 .../templates/rest_framework/inline/{fields => }/select.html | 0 .../rest_framework/inline/{fields => }/select_multiple.html | 0 .../rest_framework/inline/{fields => }/textarea.html | 0 .../rest_framework/vertical/{fields => }/checkbox.html | 0 .../vertical/{fields => }/checkbox_multiple.html | 0 .../rest_framework/vertical/{fields => }/fieldset.html | 0 rest_framework/templates/rest_framework/vertical/form.html | 4 ++-- .../templates/rest_framework/vertical/{fields => }/input.html | 2 +- .../rest_framework/vertical/{fields => }/list_fieldset.html | 0 .../templates/rest_framework/vertical/{fields => }/radio.html | 0 .../rest_framework/vertical/{fields => }/select.html | 0 .../rest_framework/vertical/{fields => }/select_multiple.html | 0 .../rest_framework/vertical/{fields => }/textarea.html | 0 30 files changed, 11 insertions(+), 11 deletions(-) rename rest_framework/templates/rest_framework/horizontal/{fields => }/checkbox.html (100%) rename rest_framework/templates/rest_framework/horizontal/{fields => }/checkbox_multiple.html (100%) rename rest_framework/templates/rest_framework/horizontal/{fields => }/fieldset.html (100%) rename rest_framework/templates/rest_framework/horizontal/{fields => }/input.html (77%) rename rest_framework/templates/rest_framework/horizontal/{fields => }/list_fieldset.html (100%) rename rest_framework/templates/rest_framework/horizontal/{fields => }/radio.html (100%) rename rest_framework/templates/rest_framework/horizontal/{fields => }/select.html (100%) rename rest_framework/templates/rest_framework/horizontal/{fields => }/select_multiple.html (100%) rename rest_framework/templates/rest_framework/horizontal/{fields => }/textarea.html (100%) rename rest_framework/templates/rest_framework/inline/{fields => }/checkbox.html (100%) rename rest_framework/templates/rest_framework/inline/{fields => }/checkbox_multiple.html (100%) rename rest_framework/templates/rest_framework/inline/{fields => }/fieldset.html (100%) rename rest_framework/templates/rest_framework/inline/{fields => }/input.html (58%) rename rest_framework/templates/rest_framework/inline/{fields => }/radio.html (100%) rename rest_framework/templates/rest_framework/inline/{fields => }/select.html (100%) rename rest_framework/templates/rest_framework/inline/{fields => }/select_multiple.html (100%) rename rest_framework/templates/rest_framework/inline/{fields => }/textarea.html (100%) rename rest_framework/templates/rest_framework/vertical/{fields => }/checkbox.html (100%) rename rest_framework/templates/rest_framework/vertical/{fields => }/checkbox_multiple.html (100%) rename rest_framework/templates/rest_framework/vertical/{fields => }/fieldset.html (100%) rename rest_framework/templates/rest_framework/vertical/{fields => }/input.html (75%) rename rest_framework/templates/rest_framework/vertical/{fields => }/list_fieldset.html (100%) rename rest_framework/templates/rest_framework/vertical/{fields => }/radio.html (100%) rename rest_framework/templates/rest_framework/vertical/{fields => }/select.html (100%) rename rest_framework/templates/rest_framework/vertical/{fields => }/select_multiple.html (100%) rename rest_framework/templates/rest_framework/vertical/{fields => }/textarea.html (100%) diff --git a/rest_framework/templates/rest_framework/base.html b/rest_framework/templates/rest_framework/base.html index 4b6c7fcfc..dcb0da2c0 100644 --- a/rest_framework/templates/rest_framework/base.html +++ b/rest_framework/templates/rest_framework/base.html @@ -153,7 +153,7 @@ <div class="tab-pane" id="object-form"> {% with form=post_form %} <form action="{{ request.get_full_path }}" - method="POST" enctype="multipart/form-data" class="form-horizontal"> + method="POST" enctype="multipart/form-data" class="form-horizontal" novalidate> <fieldset> {{ post_form }} <div class="form-actions"> @@ -198,7 +198,7 @@ {% if put_form %} <div class="tab-pane" id="object-form"> <form action="{{ request.get_full_path }}" - method="POST" enctype="multipart/form-data" class="form-horizontal"> + method="POST" enctype="multipart/form-data" class="form-horizontal" novalidate> <fieldset> {{ put_form }} <div class="form-actions"> diff --git a/rest_framework/templates/rest_framework/horizontal/fields/checkbox.html b/rest_framework/templates/rest_framework/horizontal/checkbox.html similarity index 100% rename from rest_framework/templates/rest_framework/horizontal/fields/checkbox.html rename to rest_framework/templates/rest_framework/horizontal/checkbox.html diff --git a/rest_framework/templates/rest_framework/horizontal/fields/checkbox_multiple.html b/rest_framework/templates/rest_framework/horizontal/checkbox_multiple.html similarity index 100% rename from rest_framework/templates/rest_framework/horizontal/fields/checkbox_multiple.html rename to rest_framework/templates/rest_framework/horizontal/checkbox_multiple.html diff --git a/rest_framework/templates/rest_framework/horizontal/fields/fieldset.html b/rest_framework/templates/rest_framework/horizontal/fieldset.html similarity index 100% rename from rest_framework/templates/rest_framework/horizontal/fields/fieldset.html rename to rest_framework/templates/rest_framework/horizontal/fieldset.html diff --git a/rest_framework/templates/rest_framework/horizontal/form.html b/rest_framework/templates/rest_framework/horizontal/form.html index 7560d8a26..fd15b6261 100644 --- a/rest_framework/templates/rest_framework/horizontal/form.html +++ b/rest_framework/templates/rest_framework/horizontal/form.html @@ -1,9 +1,9 @@ {% load rest_framework %} -<form class="form-horizontal" role="form" action="." method="POST"> +<form class="form-horizontal" role="form" action="." method="POST" novalidate> {% csrf_token %} {% for field in form %} {% if not field.read_only %} - {% render_field field template_pack=template_pack renderer=renderer %} + {% render_field field style=style %} {% endif %} {% endfor %} <!-- form.non_field_errors --> diff --git a/rest_framework/templates/rest_framework/horizontal/fields/input.html b/rest_framework/templates/rest_framework/horizontal/input.html similarity index 77% rename from rest_framework/templates/rest_framework/horizontal/fields/input.html rename to rest_framework/templates/rest_framework/horizontal/input.html index 43ab41512..df4aa40fc 100644 --- a/rest_framework/templates/rest_framework/horizontal/fields/input.html +++ b/rest_framework/templates/rest_framework/horizontal/input.html @@ -3,7 +3,7 @@ <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> {% endif %} <div class="col-sm-10"> - <input name="{{ field.name }}" class="form-control" type="{{ style.input_type }}" novalidate {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> + <input name="{{ field.name }}" class="form-control" type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> {% if field.errors %} {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} {% endif %} diff --git a/rest_framework/templates/rest_framework/horizontal/fields/list_fieldset.html b/rest_framework/templates/rest_framework/horizontal/list_fieldset.html similarity index 100% rename from rest_framework/templates/rest_framework/horizontal/fields/list_fieldset.html rename to rest_framework/templates/rest_framework/horizontal/list_fieldset.html diff --git a/rest_framework/templates/rest_framework/horizontal/fields/radio.html b/rest_framework/templates/rest_framework/horizontal/radio.html similarity index 100% rename from rest_framework/templates/rest_framework/horizontal/fields/radio.html rename to rest_framework/templates/rest_framework/horizontal/radio.html diff --git a/rest_framework/templates/rest_framework/horizontal/fields/select.html b/rest_framework/templates/rest_framework/horizontal/select.html similarity index 100% rename from rest_framework/templates/rest_framework/horizontal/fields/select.html rename to rest_framework/templates/rest_framework/horizontal/select.html diff --git a/rest_framework/templates/rest_framework/horizontal/fields/select_multiple.html b/rest_framework/templates/rest_framework/horizontal/select_multiple.html similarity index 100% rename from rest_framework/templates/rest_framework/horizontal/fields/select_multiple.html rename to rest_framework/templates/rest_framework/horizontal/select_multiple.html diff --git a/rest_framework/templates/rest_framework/horizontal/fields/textarea.html b/rest_framework/templates/rest_framework/horizontal/textarea.html similarity index 100% rename from rest_framework/templates/rest_framework/horizontal/fields/textarea.html rename to rest_framework/templates/rest_framework/horizontal/textarea.html diff --git a/rest_framework/templates/rest_framework/inline/fields/checkbox.html b/rest_framework/templates/rest_framework/inline/checkbox.html similarity index 100% rename from rest_framework/templates/rest_framework/inline/fields/checkbox.html rename to rest_framework/templates/rest_framework/inline/checkbox.html diff --git a/rest_framework/templates/rest_framework/inline/fields/checkbox_multiple.html b/rest_framework/templates/rest_framework/inline/checkbox_multiple.html similarity index 100% rename from rest_framework/templates/rest_framework/inline/fields/checkbox_multiple.html rename to rest_framework/templates/rest_framework/inline/checkbox_multiple.html diff --git a/rest_framework/templates/rest_framework/inline/fields/fieldset.html b/rest_framework/templates/rest_framework/inline/fieldset.html similarity index 100% rename from rest_framework/templates/rest_framework/inline/fields/fieldset.html rename to rest_framework/templates/rest_framework/inline/fieldset.html diff --git a/rest_framework/templates/rest_framework/inline/form.html b/rest_framework/templates/rest_framework/inline/form.html index b13d16614..6a0ea81d3 100644 --- a/rest_framework/templates/rest_framework/inline/form.html +++ b/rest_framework/templates/rest_framework/inline/form.html @@ -1,9 +1,9 @@ {% load rest_framework %} -<form class="form-inline" role="form" action="." method="POST"> +<form class="form-inline" role="form" action="." method="POST" novalidate> {% csrf_token %} {% for field in form %} {% if not field.read_only %} - {% render_field field template_pack=template_pack renderer=renderer %} + {% render_field field style=style %} {% endif %} {% endfor %} <!-- form.non_field_errors --> diff --git a/rest_framework/templates/rest_framework/inline/fields/input.html b/rest_framework/templates/rest_framework/inline/input.html similarity index 58% rename from rest_framework/templates/rest_framework/inline/fields/input.html rename to rest_framework/templates/rest_framework/inline/input.html index 0d3eb8845..f8ec4faf2 100644 --- a/rest_framework/templates/rest_framework/inline/fields/input.html +++ b/rest_framework/templates/rest_framework/inline/input.html @@ -2,5 +2,5 @@ {% if field.label %} <label class="sr-only">{{ field.label }}</label> {% endif %} - <input name="{{ field.name }}" class="form-control" type="{{ style.input_type }}" novalidate {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> + <input name="{{ field.name }}" class="form-control" type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> </div> diff --git a/rest_framework/templates/rest_framework/inline/fields/radio.html b/rest_framework/templates/rest_framework/inline/radio.html similarity index 100% rename from rest_framework/templates/rest_framework/inline/fields/radio.html rename to rest_framework/templates/rest_framework/inline/radio.html diff --git a/rest_framework/templates/rest_framework/inline/fields/select.html b/rest_framework/templates/rest_framework/inline/select.html similarity index 100% rename from rest_framework/templates/rest_framework/inline/fields/select.html rename to rest_framework/templates/rest_framework/inline/select.html diff --git a/rest_framework/templates/rest_framework/inline/fields/select_multiple.html b/rest_framework/templates/rest_framework/inline/select_multiple.html similarity index 100% rename from rest_framework/templates/rest_framework/inline/fields/select_multiple.html rename to rest_framework/templates/rest_framework/inline/select_multiple.html diff --git a/rest_framework/templates/rest_framework/inline/fields/textarea.html b/rest_framework/templates/rest_framework/inline/textarea.html similarity index 100% rename from rest_framework/templates/rest_framework/inline/fields/textarea.html rename to rest_framework/templates/rest_framework/inline/textarea.html diff --git a/rest_framework/templates/rest_framework/vertical/fields/checkbox.html b/rest_framework/templates/rest_framework/vertical/checkbox.html similarity index 100% rename from rest_framework/templates/rest_framework/vertical/fields/checkbox.html rename to rest_framework/templates/rest_framework/vertical/checkbox.html diff --git a/rest_framework/templates/rest_framework/vertical/fields/checkbox_multiple.html b/rest_framework/templates/rest_framework/vertical/checkbox_multiple.html similarity index 100% rename from rest_framework/templates/rest_framework/vertical/fields/checkbox_multiple.html rename to rest_framework/templates/rest_framework/vertical/checkbox_multiple.html diff --git a/rest_framework/templates/rest_framework/vertical/fields/fieldset.html b/rest_framework/templates/rest_framework/vertical/fieldset.html similarity index 100% rename from rest_framework/templates/rest_framework/vertical/fields/fieldset.html rename to rest_framework/templates/rest_framework/vertical/fieldset.html diff --git a/rest_framework/templates/rest_framework/vertical/form.html b/rest_framework/templates/rest_framework/vertical/form.html index fe908af02..e68835c0e 100644 --- a/rest_framework/templates/rest_framework/vertical/form.html +++ b/rest_framework/templates/rest_framework/vertical/form.html @@ -1,9 +1,9 @@ {% load rest_framework %} -<form role="form" action="." method="POST"> +<form role="form" action="." method="POST" novalidate> {% csrf_token %} {% for field in form %} {% if not field.read_only %} - {% render_field field template_pack=template_pack renderer=renderer %} + {% render_field field style=style %} {% endif %} {% endfor %} <!-- form.non_field_errors --> diff --git a/rest_framework/templates/rest_framework/vertical/fields/input.html b/rest_framework/templates/rest_framework/vertical/input.html similarity index 75% rename from rest_framework/templates/rest_framework/vertical/fields/input.html rename to rest_framework/templates/rest_framework/vertical/input.html index 4f4cb017a..e1e21ca1f 100644 --- a/rest_framework/templates/rest_framework/vertical/fields/input.html +++ b/rest_framework/templates/rest_framework/vertical/input.html @@ -2,7 +2,7 @@ {% if field.label %} <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> {% endif %} - <input name="{{ field.name }}" class="form-control" type="{{ style.input_type }}" novalidate {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> + <input name="{{ field.name }}" class="form-control" type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> {% if field.errors %} {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} {% endif %} diff --git a/rest_framework/templates/rest_framework/vertical/fields/list_fieldset.html b/rest_framework/templates/rest_framework/vertical/list_fieldset.html similarity index 100% rename from rest_framework/templates/rest_framework/vertical/fields/list_fieldset.html rename to rest_framework/templates/rest_framework/vertical/list_fieldset.html diff --git a/rest_framework/templates/rest_framework/vertical/fields/radio.html b/rest_framework/templates/rest_framework/vertical/radio.html similarity index 100% rename from rest_framework/templates/rest_framework/vertical/fields/radio.html rename to rest_framework/templates/rest_framework/vertical/radio.html diff --git a/rest_framework/templates/rest_framework/vertical/fields/select.html b/rest_framework/templates/rest_framework/vertical/select.html similarity index 100% rename from rest_framework/templates/rest_framework/vertical/fields/select.html rename to rest_framework/templates/rest_framework/vertical/select.html diff --git a/rest_framework/templates/rest_framework/vertical/fields/select_multiple.html b/rest_framework/templates/rest_framework/vertical/select_multiple.html similarity index 100% rename from rest_framework/templates/rest_framework/vertical/fields/select_multiple.html rename to rest_framework/templates/rest_framework/vertical/select_multiple.html diff --git a/rest_framework/templates/rest_framework/vertical/fields/textarea.html b/rest_framework/templates/rest_framework/vertical/textarea.html similarity index 100% rename from rest_framework/templates/rest_framework/vertical/fields/textarea.html rename to rest_framework/templates/rest_framework/vertical/textarea.html From b4f3379c7002f0c80a26605fdd9c69d7cef2f16f Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 15 Oct 2014 15:13:28 +0100 Subject: [PATCH 155/249] Support fields that reference a simple callable --- rest_framework/fields.py | 4 +- rest_framework/renderers.py | 105 +++++++++++------- rest_framework/serializers.py | 4 +- .../rest_framework/css/bootstrap-tweaks.css | 4 - .../static/rest_framework/css/default.css | 4 + rest_framework/templatetags/rest_framework.py | 7 +- 6 files changed, 78 insertions(+), 50 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index b881ad13b..24dfaaf54 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -66,6 +66,8 @@ def get_attribute(instance, attrs): return instance[attr] except (KeyError, TypeError, AttributeError): raise exc + if is_simple_callable(instance): + return instance() return instance @@ -1025,8 +1027,6 @@ class ReadOnlyField(Field): super(ReadOnlyField, self).__init__(**kwargs) def to_representation(self, value): - if is_simple_callable(value): - return value() return value diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 5fae75f2e..d5defa318 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -340,76 +340,101 @@ class HTMLFormRenderer(BaseRenderer): media_type = 'text/html' format = 'form' charset = 'utf-8' + template_pack = 'rest_framework/horizontal/' + base_template = 'form.html' - field_templates = ClassLookupDict({ + default_style = ClassLookupDict({ serializers.Field: { - 'default': 'input.html' + 'base_template': 'input.html', + 'input_type': 'text' + }, + serializers.EmailField: { + 'base_template': 'input.html', + 'input_type': 'email' + }, + serializers.URLField: { + 'base_template': 'input.html', + 'input_type': 'url' + }, + serializers.IntegerField: { + 'base_template': 'input.html', + 'input_type': 'number' + }, + serializers.DateTimeField: { + 'base_template': 'input.html', + 'input_type': 'datetime-local' + }, + serializers.DateField: { + 'base_template': 'input.html', + 'input_type': 'date' + }, + serializers.TimeField: { + 'base_template': 'input.html', + 'input_type': 'time' }, serializers.BooleanField: { - 'default': 'checkbox.html' - }, - serializers.CharField: { - 'default': 'input.html', - 'textarea': 'textarea.html' + 'base_template': 'checkbox.html' }, serializers.ChoiceField: { - 'default': 'select.html', - 'radio': 'select_radio.html' + 'base_template': 'select.html', # Also valid: 'radio.html' }, serializers.MultipleChoiceField: { - 'default': 'select_multiple.html', - 'checkbox': 'select_checkbox.html' + 'base_template': 'select_multiple.html', # Also valid: 'checkbox_multiple.html' }, serializers.ManyRelation: { - 'default': 'select_multiple.html', - 'checkbox': 'select_checkbox.html' + 'base_template': 'select_multiple.html', # Also valid: 'checkbox_multiple.html' }, serializers.Serializer: { - 'default': 'fieldset.html' + 'base_template': 'fieldset.html' }, serializers.ListSerializer: { - 'default': 'list_fieldset.html' + 'base_template': 'list_fieldset.html' } }) - input_type = ClassLookupDict({ - serializers.Field: 'text', - serializers.EmailField: 'email', - serializers.URLField: 'url', - serializers.IntegerField: 'number', - serializers.DateTimeField: 'datetime-local', - serializers.DateField: 'date', - serializers.TimeField: 'time', - }) + def render_field(self, field, parent_style): + style = dict(self.default_style[field]) + style.update(field.style) + if 'template_pack' not in style: + style['template_pack'] = parent_style['template_pack'] + style['renderer'] = self - def render_field(self, field, template_pack=None): - style_type = field.style.get('type', 'default') - - input_type = self.input_type[field] - if input_type == 'datetime-local' and isinstance(field.value, six.text_type): + if style.get('input_type') == 'datetime-local' and isinstance(field.value, six.text_type): field.value = field.value.rstrip('Z') - base = self.field_templates[field][style_type] - template_name = template_pack + '/fields/' + base + if 'template' in style: + template_name = style['template'] + else: + template_name = style['template_pack'].strip('/') + '/' + style['base_template'] + template = loader.get_template(template_name) - context = Context({ - 'field': field, - 'input_type': input_type, - 'renderer': self, - }) + context = Context({'field': field, 'style': style}) return template.render(context) 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', {}) + 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 + + if '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 = loader.get_template('rest_framework/horizontal/form.html') + template = loader.get_template(template_name) context = RequestContext(request, { - 'form': data.serializer, - 'template_pack': 'rest_framework/horizontal', - 'renderer': self + 'form': form, + 'style': style }) return template.render(context) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index c844605fc..534be6f90 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -115,7 +115,7 @@ class BaseSerializer(Field): @property def data(self): if not hasattr(self, '_data'): - if self.instance is not None: + if self.instance is not None and not getattr(self, '_errors', None): self._data = self.to_representation(self.instance) else: self._data = self.get_initial() @@ -339,7 +339,7 @@ class Serializer(BaseSerializer): Dict of native values <- Dict of primitive datatypes. """ ret = {} - errors = {} + errors = ReturnDict(serializer=self) fields = [field for field in self.fields.values() if not field.read_only] for field in fields: diff --git a/rest_framework/static/rest_framework/css/bootstrap-tweaks.css b/rest_framework/static/rest_framework/css/bootstrap-tweaks.css index 6a37cae23..36c7be481 100644 --- a/rest_framework/static/rest_framework/css/bootstrap-tweaks.css +++ b/rest_framework/static/rest_framework/css/bootstrap-tweaks.css @@ -115,10 +115,6 @@ html, body { margin-bottom: 0; } -.well form .help-block { - color: #999999; -} - .nav-tabs { border: 0; } diff --git a/rest_framework/static/rest_framework/css/default.css b/rest_framework/static/rest_framework/css/default.css index 82c6033b6..4f52cc566 100644 --- a/rest_framework/static/rest_framework/css/default.css +++ b/rest_framework/static/rest_framework/css/default.css @@ -36,6 +36,10 @@ ul.breadcrumb { margin: 70px 0 0 0; } +.breadcrumb li.active a { + color: #777; +} + form select, form input, form textarea { width: 90%; } diff --git a/rest_framework/templatetags/rest_framework.py b/rest_framework/templatetags/rest_framework.py index c092d39f6..d9424f022 100644 --- a/rest_framework/templatetags/rest_framework.py +++ b/rest_framework/templatetags/rest_framework.py @@ -8,6 +8,7 @@ from django.utils.html import escape from django.utils.safestring import SafeData, mark_safe from django.utils.html import smart_urlquote from rest_framework.compat import urlparse, force_text +from rest_framework.renderers import HTMLFormRenderer import re register = template.Library() @@ -32,8 +33,10 @@ class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])') # And the template tags themselves... @register.simple_tag -def render_field(field, template_pack=None, renderer=None): - return renderer.render_field(field, template_pack) +def render_field(field, style=None): + style = style or {} + renderer = style.get('renderer', HTMLFormRenderer()) + return renderer.render_field(field, style) @register.simple_tag From 4248a6c499cf31d2e38199f05a42e7a131dc014e Mon Sep 17 00:00:00 2001 From: Marty Alchin <marty@heroku.com> Date: Wed, 15 Oct 2014 17:54:58 -0700 Subject: [PATCH 156/249] Add a keys method to BindingDict --- rest_framework/serializers.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 534be6f90..2066fcf70 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -230,6 +230,9 @@ class BindingDict(object): def items(self): return self.fields.items() + def keys(self): + return self.fields.keys() + def values(self): return self.fields.values() From d0f610be4457947f78d20da4f2bdb04ef52d0db3 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 16 Oct 2014 20:43:35 +0100 Subject: [PATCH 157/249] Update release notes --- docs/topics/3.0-announcement.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index dcd6d90cb..f868b344a 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -653,7 +653,7 @@ If you need to restore the previous behavior you can include the `AllowPUTAsCrea #### Customizing error responses. -The generic views now raise `ValidationError` for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a `400 Bad Request` response directly. +The generic views now raise `ValidationFailed` exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a `400 Bad Request` response directly. This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views. From 7b666e982c461e237567435851dcc93bc76581e5 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 16 Oct 2014 20:45:18 +0100 Subject: [PATCH 158/249] Stricter checking for failure cases. --- rest_framework/serializers.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 2066fcf70..f72ecb0bf 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -77,6 +77,13 @@ class BaseSerializer(Field): raise NotImplementedError('`create()` must be implemented.') def save(self, **kwargs): + assert not hasattr(self, 'restore_object'), ( + 'Serializer %s has old-style version 2 `.restore_object()` ' + 'that is no longer compatible with REST framework 3. ' + 'Use the new-style `.create()` and `.update()` methods instead.' % + self.__class__.__name__ + ) + validated_data = self.validated_data if kwargs: validated_data = dict( @@ -494,6 +501,16 @@ class ModelSerializer(Serializer): self._kwargs['validators'] = validators def create(self, validated_attrs): + assert not any( + isinstance(field, BaseSerializer) and not field.read_only + for field in self.fields.values() + ), ( + 'The `.create()` method does not suport nested writable fields ' + 'by default. Write an explicit `.create()` method for serializer ' + '%s, or set `read_only=True` on nested serializer fields.' % + self.__class__.__name__ + ) + ModelClass = self.Meta.model # Remove many-to-many relationships from validated_attrs. @@ -515,6 +532,16 @@ class ModelSerializer(Serializer): return instance def update(self, instance, validated_attrs): + assert not any( + isinstance(field, BaseSerializer) and not field.read_only + for field in self.fields.values() + ), ( + 'The `.update()` method does not suport nested writable fields ' + 'by default. Write an explicit `.update()` method for serializer ' + '%s, or set `read_only=True` on nested serializer fields.' % + self.__class__.__name__ + ) + for attr, value in validated_attrs.items(): setattr(instance, attr, value) instance.save() From 32fd82ba0d6082418e5ca5633f9e9709bd44e86b Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 16 Oct 2014 20:45:36 +0100 Subject: [PATCH 159/249] get_attribute method on fields --- rest_framework/fields.py | 9 +++------ rest_framework/serializers.py | 6 +++++- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 24dfaaf54..597d5e122 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -212,15 +212,12 @@ class Field(object): return self.default_empty_html if (ret == '') else ret return dictionary.get(self.field_name, empty) - def get_field_representation(self, instance): + def get_attribute(self, instance): """ - Given the outgoing object instance, return the primitive value + Given the *outgoing* object instance, return the primitive value that should be used for this field. """ - attribute = get_attribute(instance, self.source_attrs) - if attribute is None: - return None - return self.to_representation(attribute) + return get_attribute(instance, self.source_attrs) def get_default(self): """ diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index f72ecb0bf..30e6bfeb1 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -379,7 +379,11 @@ class Serializer(BaseSerializer): fields = [field for field in self.fields.values() if not field.write_only] for field in fields: - value = field.get_field_representation(instance) + attribute = field.get_attribute(instance) + if attribute is None: + value = None + else: + value = field.to_representation(attribute) transform_method = getattr(self, 'transform_' + field.field_name, None) if transform_method is not None: value = transform_method(value) From 3af5df19552103aaea3f4c6338acfb61f54c0d34 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 16 Oct 2014 20:47:34 +0100 Subject: [PATCH 160/249] Performance for PK fields --- rest_framework/relations.py | 42 ++++++++++++++++++++++++++++++++++--- tests/test_relations_pk.py | 12 +++++++---- 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 268b95cf1..1665dd35e 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -1,5 +1,5 @@ from rest_framework.compat import smart_text, urlparse -from rest_framework.fields import empty, Field +from rest_framework.fields import get_attribute, empty, Field from rest_framework.reverse import reverse from rest_framework.utils import html from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured @@ -9,6 +9,11 @@ from django.utils import six from django.utils.translation import ugettext_lazy as _ +class PKOnlyObject(object): + def __init__(self, pk): + self.pk = pk + + class RelatedField(Field): def __init__(self, **kwargs): self.queryset = kwargs.pop('queryset', None) @@ -45,6 +50,10 @@ class RelatedField(Field): queryset = queryset.all() return queryset + def get_iterable(self, instance, source): + relationship = get_attribute(instance, [source]) + return relationship.all() if (hasattr(relationship, 'all')) else relationship + @property def choices(self): return dict([ @@ -85,6 +94,31 @@ class PrimaryKeyRelatedField(RelatedField): 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: + return PKOnlyObject(pk=instance.serializable_value(self.source)) + except AttributeError: + return get_attribute(instance, [self.source]) + + def get_iterable(self, instance, source): + # 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-primative 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) + return [ + PKOnlyObject(pk=item.serializable_value('pk')) + for item in relationship + ] + def to_representation(self, value): return value.pk @@ -277,8 +311,10 @@ class ManyRelation(Field): for item in data ] - def to_representation(self, obj): - iterable = obj.all() if (hasattr(obj, 'all')) else obj + def get_attribute(self, instance): + return self.child_relation.get_iterable(instance, self.source) + + def to_representation(self, iterable): return [ self.child_relation.to_representation(value) for value in iterable diff --git a/tests/test_relations_pk.py b/tests/test_relations_pk.py index da3c57863..ba5f6c178 100644 --- a/tests/test_relations_pk.py +++ b/tests/test_relations_pk.py @@ -68,7 +68,8 @@ class PKManyToManyTests(TestCase): {'id': 2, 'name': 'source-2', 'targets': [1, 2]}, {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]} ] - self.assertEqual(serializer.data, expected) + with self.assertNumQueries(4): + self.assertEqual(serializer.data, expected) def test_reverse_many_to_many_retrieve(self): queryset = ManyToManyTarget.objects.all() @@ -78,7 +79,8 @@ class PKManyToManyTests(TestCase): {'id': 2, 'name': 'target-2', 'sources': [2, 3]}, {'id': 3, 'name': 'target-3', 'sources': [3]} ] - self.assertEqual(serializer.data, expected) + with self.assertNumQueries(4): + self.assertEqual(serializer.data, expected) def test_many_to_many_update(self): data = {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]} @@ -173,7 +175,8 @@ class PKForeignKeyTests(TestCase): {'id': 2, 'name': 'source-2', 'target': 1}, {'id': 3, 'name': 'source-3', 'target': 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() @@ -182,7 +185,8 @@ class PKForeignKeyTests(TestCase): {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, {'id': 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 = {'id': 1, 'name': 'source-1', 'target': 2} From 5882a7a9d52de1084d2be68adc73dc19bc706e4a Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 16 Oct 2014 20:47:40 +0100 Subject: [PATCH 161/249] Tweak --- rest_framework/renderers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index d5defa318..4dfd0f498 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -396,7 +396,7 @@ class HTMLFormRenderer(BaseRenderer): style = dict(self.default_style[field]) style.update(field.style) if 'template_pack' not in style: - style['template_pack'] = parent_style['template_pack'] + style['template_pack'] = parent_style.get('template_pack', self.template_pack) style['renderer'] = self if style.get('input_type') == 'datetime-local' and isinstance(field.value, six.text_type): From 05cbec9dd7f9f0b6a9b59b29ac6c9272b6ae50d8 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 17 Oct 2014 13:23:14 +0100 Subject: [PATCH 162/249] Use serializers.ValidationError --- docs/topics/3.0-announcement.md | 14 ++- rest_framework/authtoken/serializers.py | 6 +- rest_framework/exceptions.py | 9 +- rest_framework/fields.py | 12 +-- rest_framework/serializers.py | 32 +++--- tests/test_fields.py | 134 ++++++++++++------------ tests/test_relations.py | 10 +- tests/test_validation.py | 10 +- 8 files changed, 120 insertions(+), 107 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index f868b344a..658b50d31 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -144,11 +144,15 @@ The corresponding code would now look like this: logging.info('Creating ticket "%s"' % name) serializer.save(user=request.user) # Include the user when saving. -#### Use `rest_framework.exceptions.ValidationFailed`. +#### Using `serializers.ValidationError`. -Django's `ValidationError` class is intended for use with HTML forms and it's API makes its use slightly awkward with nested validation errors as can occur in serializers. +Previously `serializers.ValidationError` error was simply a synonym for `django.core.exceptions.ValidationError`. This has now been altered so that it inherits from the standard `APIException` base class. -We now include a simpler `ValidationFailed` exception class in REST framework that you should use when raising validation failures. +The reason behind this is that Django's `ValidationError` class is intended for use with HTML forms and its API makes using it slightly awkward with nested validation errors that can occur in serializers. + +For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you are always using the `serializers.ValidationError` exception class, and not Django's built-in exception. + +We strongly recommend that you use the namespaced import style of `import serializers` and not `from serializers import ValidationError` in order to avoid any potential confusion. #### Change to `validate_<field_name>`. @@ -156,14 +160,14 @@ The `validate_<field_name>` method hooks that can be attached to serializer clas def validate_score(self, attrs, source): if attrs[score] % 10 != 0: - raise ValidationError('This field should be a multiple of ten.') + raise serializers.ValidationError('This field should be a multiple of ten.') return attrs This is now simplified slightly, and the method hooks simply take the value to be validated, and return it's validated value. def validate_score(self, value): if value % 10 != 0: - raise ValidationError('This field should be a multiple of ten.') + raise serializers.ValidationError('This field should be a multiple of ten.') return value Any ad-hoc validation that applies to more than one field should go in the `.validate(self, attrs)` method as usual. diff --git a/rest_framework/authtoken/serializers.py b/rest_framework/authtoken/serializers.py index a808d0a32..f31dded17 100644 --- a/rest_framework/authtoken/serializers.py +++ b/rest_framework/authtoken/serializers.py @@ -18,13 +18,13 @@ class AuthTokenSerializer(serializers.Serializer): if user: if not user.is_active: msg = _('User account is disabled.') - raise exceptions.ValidationFailed(msg) + raise exceptions.ValidationError(msg) else: msg = _('Unable to log in with provided credentials.') - raise exceptions.ValidationFailed(msg) + raise exceptions.ValidationError(msg) else: msg = _('Must include "username" and "password"') - raise exceptions.ValidationFailed(msg) + raise exceptions.ValidationError(msg) attrs['user'] = user return attrs diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py index b7c2d16d6..388d3dee9 100644 --- a/rest_framework/exceptions.py +++ b/rest_framework/exceptions.py @@ -24,7 +24,14 @@ class APIException(Exception): return self.detail -class ValidationFailed(APIException): +# The recommended style for using `ValidationError` is to keep it namespaced +# under `serializers`, in order to minimize potential confusion with Django's +# built in `ValidationError`. For example: +# +# from rest_framework import serializers +# raise serializers.ValidationError('Value was invalid') + +class ValidationError(APIException): status_code = status.HTTP_400_BAD_REQUEST def __init__(self, detail): diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 597d5e122..2da4aa8b2 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -13,7 +13,7 @@ from rest_framework.compat import ( smart_text, EmailValidator, MinValueValidator, MaxValueValidator, MinLengthValidator, MaxLengthValidator, URLValidator ) -from rest_framework.exceptions import ValidationFailed +from rest_framework.exceptions import ValidationError from rest_framework.settings import api_settings from rest_framework.utils import html, representation, humanize_datetime import copy @@ -102,7 +102,7 @@ NOT_READ_ONLY_DEFAULT = 'May not set both `read_only` and `default`' NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`' USE_READONLYFIELD = 'Field(read_only=True) should be ReadOnlyField' MISSING_ERROR_MESSAGE = ( - 'ValidationFailed raised by `{class_name}`, but error key `{key}` does ' + 'ValidationError raised by `{class_name}`, but error key `{key}` does ' 'not exist in the `error_messages` dictionary.' ) @@ -264,7 +264,7 @@ class Field(object): def run_validators(self, value): """ Test the given value against all the validators on the field, - and either raise a `ValidationFailed` or simply return. + and either raise a `ValidationError` or simply return. """ errors = [] for validator in self.validators: @@ -272,12 +272,12 @@ class Field(object): validator.serializer_field = self try: validator(value) - except ValidationFailed as exc: + except ValidationError as exc: errors.extend(exc.detail) except DjangoValidationError as exc: errors.extend(exc.messages) if errors: - raise ValidationFailed(errors) + raise ValidationError(errors) def validate(self, value): pass @@ -305,7 +305,7 @@ class Field(object): msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key) raise AssertionError(msg) message_string = msg.format(**kwargs) - raise ValidationFailed(message_string) + raise ValidationError(message_string) @property def root(self): diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 30e6bfeb1..d29dc684a 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -14,7 +14,7 @@ from django.core.exceptions import ImproperlyConfigured from django.db import models from django.utils import six from django.utils.datastructures import SortedDict -from rest_framework.exceptions import ValidationFailed +from rest_framework.exceptions import ValidationError from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.settings import api_settings from rest_framework.utils import html, model_meta, representation @@ -77,13 +77,6 @@ class BaseSerializer(Field): raise NotImplementedError('`create()` must be implemented.') def save(self, **kwargs): - assert not hasattr(self, 'restore_object'), ( - 'Serializer %s has old-style version 2 `.restore_object()` ' - 'that is no longer compatible with REST framework 3. ' - 'Use the new-style `.create()` and `.update()` methods instead.' % - self.__class__.__name__ - ) - validated_data = self.validated_data if kwargs: validated_data = dict( @@ -105,17 +98,24 @@ class BaseSerializer(Field): return self.instance def is_valid(self, raise_exception=False): + assert not hasattr(self, 'restore_object'), ( + 'Serializer %s has old-style version 2 `.restore_object()` ' + 'that is no longer compatible with REST framework 3. ' + 'Use the new-style `.create()` and `.update()` methods instead.' % + self.__class__.__name__ + ) + if not hasattr(self, '_validated_data'): try: self._validated_data = self.run_validation(self._initial_data) - except ValidationFailed as exc: + except ValidationError as exc: self._validated_data = {} self._errors = exc.detail else: self._errors = {} if self._errors and raise_exception: - raise ValidationFailed(self._errors) + raise ValidationError(self._errors) return not bool(self._errors) @@ -124,6 +124,8 @@ class BaseSerializer(Field): if not hasattr(self, '_data'): if self.instance is not None and not getattr(self, '_errors', None): self._data = self.to_representation(self.instance) + elif hasattr(self, '_validated_data') and not getattr(self, '_errors', None): + self._data = self.to_representation(self.validated_data) else: self._data = self.get_initial() return self._data @@ -329,7 +331,7 @@ class Serializer(BaseSerializer): return None if not isinstance(data, dict): - raise ValidationFailed({ + raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: ['Invalid data'] }) @@ -338,8 +340,8 @@ class Serializer(BaseSerializer): self.run_validators(value) value = self.validate(value) assert value is not None, '.validate() should return the validated data' - except ValidationFailed as exc: - raise ValidationFailed({ + except ValidationError as exc: + raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: exc.detail }) return value @@ -359,7 +361,7 @@ class Serializer(BaseSerializer): validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) - except ValidationFailed as exc: + except ValidationError as exc: errors[field.field_name] = exc.detail except SkipField: pass @@ -367,7 +369,7 @@ class Serializer(BaseSerializer): set_value(ret, field.source_attrs, validated_value) if errors: - raise ValidationFailed(errors) + raise ValidationError(errors) return ret diff --git a/tests/test_fields.py b/tests/test_fields.py index 5e8c67c54..6dc5f87d2 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1,6 +1,6 @@ from decimal import Decimal from django.utils import timezone -from rest_framework import exceptions, fields, serializers +from rest_framework import serializers import datetime import django import pytest @@ -17,8 +17,8 @@ class TestEmpty: """ By default a field must be included in the input. """ - field = fields.IntegerField() - with pytest.raises(exceptions.ValidationFailed) as exc_info: + field = serializers.IntegerField() + with pytest.raises(serializers.ValidationError) as exc_info: field.run_validation() assert exc_info.value.detail == ['This field is required.'] @@ -26,16 +26,16 @@ class TestEmpty: """ If `required=False` then a field may be omitted from the input. """ - field = fields.IntegerField(required=False) - with pytest.raises(fields.SkipField): + field = serializers.IntegerField(required=False) + with pytest.raises(serializers.SkipField): field.run_validation() def test_disallow_null(self): """ By default `None` is not a valid input. """ - field = fields.IntegerField() - with pytest.raises(exceptions.ValidationFailed) as exc_info: + field = serializers.IntegerField() + with pytest.raises(serializers.ValidationError) as exc_info: field.run_validation(None) assert exc_info.value.detail == ['This field may not be null.'] @@ -43,7 +43,7 @@ class TestEmpty: """ If `allow_null=True` then `None` is a valid input. """ - field = fields.IntegerField(allow_null=True) + field = serializers.IntegerField(allow_null=True) output = field.run_validation(None) assert output is None @@ -51,8 +51,8 @@ class TestEmpty: """ By default '' is not a valid input. """ - field = fields.CharField() - with pytest.raises(exceptions.ValidationFailed) as exc_info: + field = serializers.CharField() + with pytest.raises(serializers.ValidationError) as exc_info: field.run_validation('') assert exc_info.value.detail == ['This field may not be blank.'] @@ -60,7 +60,7 @@ class TestEmpty: """ If `allow_blank=True` then '' is a valid input. """ - field = fields.CharField(allow_blank=True) + field = serializers.CharField(allow_blank=True) output = field.run_validation('') assert output is '' @@ -68,7 +68,7 @@ class TestEmpty: """ If `default` is set, then omitted values get the default input. """ - field = fields.IntegerField(default=123) + field = serializers.IntegerField(default=123) output = field.run_validation() assert output is 123 @@ -96,13 +96,13 @@ class TestSource: class TestReadOnly: def setup(self): class TestSerializer(serializers.Serializer): - read_only = fields.ReadOnlyField() - writable = fields.IntegerField() + read_only = serializers.ReadOnlyField() + writable = serializers.IntegerField() self.Serializer = TestSerializer def test_validate_read_only(self): """ - Read-only fields should not be included in validation. + Read-only serializers.should not be included in validation. """ data = {'read_only': 123, 'writable': 456} serializer = self.Serializer(data=data) @@ -111,7 +111,7 @@ class TestReadOnly: def test_serialize_read_only(self): """ - Read-only fields should be serialized. + Read-only serializers.should be serialized. """ instance = {'read_only': 123, 'writable': 456} serializer = self.Serializer(instance) @@ -121,13 +121,13 @@ class TestReadOnly: class TestWriteOnly: def setup(self): class TestSerializer(serializers.Serializer): - write_only = fields.IntegerField(write_only=True) - readable = fields.IntegerField() + write_only = serializers.IntegerField(write_only=True) + readable = serializers.IntegerField() self.Serializer = TestSerializer def test_validate_write_only(self): """ - Write-only fields should be included in validation. + Write-only serializers.should be included in validation. """ data = {'write_only': 123, 'readable': 456} serializer = self.Serializer(data=data) @@ -136,7 +136,7 @@ class TestWriteOnly: def test_serialize_write_only(self): """ - Write-only fields should not be serialized. + Write-only serializers.should not be serialized. """ instance = {'write_only': 123, 'readable': 456} serializer = self.Serializer(instance) @@ -146,8 +146,8 @@ class TestWriteOnly: class TestInitial: def setup(self): class TestSerializer(serializers.Serializer): - initial_field = fields.IntegerField(initial=123) - blank_field = fields.IntegerField() + initial_field = serializers.IntegerField(initial=123) + blank_field = serializers.IntegerField() self.serializer = TestSerializer() def test_initial(self): @@ -163,7 +163,7 @@ class TestInitial: class TestLabel: def setup(self): class TestSerializer(serializers.Serializer): - labeled = fields.IntegerField(label='My label') + labeled = serializers.IntegerField(label='My label') self.serializer = TestSerializer() def test_label(self): @@ -189,7 +189,7 @@ class TestInvalidErrorKey: with pytest.raises(AssertionError) as exc_info: self.field.to_native(123) expected = ( - 'ValidationFailed raised by `ExampleField`, but error key ' + 'ValidationError raised by `ExampleField`, but error key ' '`incorrect` does not exist in the `error_messages` dictionary.' ) assert str(exc_info.value) == expected @@ -198,7 +198,7 @@ class TestInvalidErrorKey: class TestBooleanHTMLInput: def setup(self): class TestSerializer(serializers.Serializer): - archived = fields.BooleanField() + archived = serializers.BooleanField() self.Serializer = TestSerializer def test_empty_html_checkbox(self): @@ -243,7 +243,7 @@ class FieldValues: Ensure that invalid values raise the expected validation error. """ for input_value, expected_failure in get_items(self.invalid_inputs): - with pytest.raises(exceptions.ValidationFailed) as exc_info: + with pytest.raises(serializers.ValidationError) as exc_info: self.field.run_validation(input_value) assert exc_info.value.detail == expected_failure @@ -283,7 +283,7 @@ class TestBooleanField(FieldValues): False: False, 'other': True } - field = fields.BooleanField() + field = serializers.BooleanField() class TestNullBooleanField(FieldValues): @@ -310,7 +310,7 @@ class TestNullBooleanField(FieldValues): None: None, 'other': True } - field = fields.NullBooleanField() + field = serializers.NullBooleanField() # String types... @@ -330,7 +330,7 @@ class TestCharField(FieldValues): 1: '1', 'abc': 'abc' } - field = fields.CharField() + field = serializers.CharField() class TestEmailField(FieldValues): @@ -345,7 +345,7 @@ class TestEmailField(FieldValues): 'examplecom': ['Enter a valid email address.'] } outputs = {} - field = fields.EmailField() + field = serializers.EmailField() class TestRegexField(FieldValues): @@ -359,7 +359,7 @@ class TestRegexField(FieldValues): 'A9': ["This value does not match the required pattern."] } outputs = {} - field = fields.RegexField(regex='[a-z][0-9]') + field = serializers.RegexField(regex='[a-z][0-9]') class TestSlugField(FieldValues): @@ -373,7 +373,7 @@ class TestSlugField(FieldValues): 'slug 99': ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."] } outputs = {} - field = fields.SlugField() + field = serializers.SlugField() class TestURLField(FieldValues): @@ -387,7 +387,7 @@ class TestURLField(FieldValues): 'example.com': ['Enter a valid URL.'] } outputs = {} - field = fields.URLField() + field = serializers.URLField() # Number types... @@ -415,7 +415,7 @@ class TestIntegerField(FieldValues): 1.0: 1, 0.0: 0 } - field = fields.IntegerField() + field = serializers.IntegerField() class TestMinMaxIntegerField(FieldValues): @@ -435,7 +435,7 @@ class TestMinMaxIntegerField(FieldValues): '4': ['Ensure this value is less than or equal to 3.'], } outputs = {} - field = fields.IntegerField(min_value=1, max_value=3) + field = serializers.IntegerField(min_value=1, max_value=3) class TestFloatField(FieldValues): @@ -461,7 +461,7 @@ class TestFloatField(FieldValues): 1.0: 1.0, 0.0: 0.0, } - field = fields.FloatField() + field = serializers.FloatField() class TestMinMaxFloatField(FieldValues): @@ -483,7 +483,7 @@ class TestMinMaxFloatField(FieldValues): '3.1': ['Ensure this value is less than or equal to 3.'], } outputs = {} - field = fields.FloatField(min_value=1, max_value=3) + field = serializers.FloatField(min_value=1, max_value=3) class TestDecimalField(FieldValues): @@ -518,7 +518,7 @@ class TestDecimalField(FieldValues): Decimal('1.09'): '1.1', Decimal('0.04'): '0.0' } - field = fields.DecimalField(max_digits=3, decimal_places=1) + field = serializers.DecimalField(max_digits=3, decimal_places=1) class TestMinMaxDecimalField(FieldValues): @@ -534,7 +534,7 @@ class TestMinMaxDecimalField(FieldValues): '20.1': ['Ensure this value is less than or equal to 20.'], } outputs = {} - field = fields.DecimalField( + field = serializers.DecimalField( max_digits=3, decimal_places=1, min_value=10, max_value=20 ) @@ -554,13 +554,13 @@ class TestNoStringCoercionDecimalField(FieldValues): Decimal('1.09'): Decimal('1.1'), Decimal('0.04'): Decimal('0.0'), } - field = fields.DecimalField( + field = serializers.DecimalField( max_digits=3, decimal_places=1, coerce_to_string=False ) -# Date & time fields... +# Date & time serializers... class TestDateField(FieldValues): """ @@ -578,7 +578,7 @@ class TestDateField(FieldValues): outputs = { datetime.date(2001, 1, 1): '2001-01-01' } - field = fields.DateField() + field = serializers.DateField() class TestCustomInputFormatDateField(FieldValues): @@ -592,7 +592,7 @@ class TestCustomInputFormatDateField(FieldValues): '2001-01-01': ['Date has wrong format. Use one of these formats instead: DD [Jan-Dec] YYYY'] } outputs = {} - field = fields.DateField(input_formats=['%d %b %Y']) + field = serializers.DateField(input_formats=['%d %b %Y']) class TestCustomOutputFormatDateField(FieldValues): @@ -604,7 +604,7 @@ class TestCustomOutputFormatDateField(FieldValues): outputs = { datetime.date(2001, 1, 1): '01 Jan 2001' } - field = fields.DateField(format='%d %b %Y') + field = serializers.DateField(format='%d %b %Y') class TestNoOutputFormatDateField(FieldValues): @@ -616,7 +616,7 @@ class TestNoOutputFormatDateField(FieldValues): outputs = { datetime.date(2001, 1, 1): datetime.date(2001, 1, 1) } - field = fields.DateField(format=None) + field = serializers.DateField(format=None) class TestDateTimeField(FieldValues): @@ -641,7 +641,7 @@ class TestDateTimeField(FieldValues): 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' } - field = fields.DateTimeField(default_timezone=timezone.UTC()) + field = serializers.DateTimeField(default_timezone=timezone.UTC()) class TestCustomInputFormatDateTimeField(FieldValues): @@ -655,7 +655,7 @@ class TestCustomInputFormatDateTimeField(FieldValues): '2001-01-01T20:50': ['Datetime has wrong format. Use one of these formats instead: hh:mm[AM|PM], DD [Jan-Dec] YYYY'] } outputs = {} - field = fields.DateTimeField(default_timezone=timezone.UTC(), input_formats=['%I:%M%p, %d %b %Y']) + field = serializers.DateTimeField(default_timezone=timezone.UTC(), input_formats=['%I:%M%p, %d %b %Y']) class TestCustomOutputFormatDateTimeField(FieldValues): @@ -667,7 +667,7 @@ class TestCustomOutputFormatDateTimeField(FieldValues): outputs = { datetime.datetime(2001, 1, 1, 13, 00): '01:00PM, 01 Jan 2001', } - field = fields.DateTimeField(format='%I:%M%p, %d %b %Y') + field = serializers.DateTimeField(format='%I:%M%p, %d %b %Y') class TestNoOutputFormatDateTimeField(FieldValues): @@ -679,7 +679,7 @@ class TestNoOutputFormatDateTimeField(FieldValues): outputs = { datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00), } - field = fields.DateTimeField(format=None) + field = serializers.DateTimeField(format=None) class TestNaiveDateTimeField(FieldValues): @@ -692,7 +692,7 @@ class TestNaiveDateTimeField(FieldValues): } invalid_inputs = {} outputs = {} - field = fields.DateTimeField(default_timezone=None) + field = serializers.DateTimeField(default_timezone=None) class TestTimeField(FieldValues): @@ -710,7 +710,7 @@ class TestTimeField(FieldValues): outputs = { datetime.time(13, 00): '13:00:00' } - field = fields.TimeField() + field = serializers.TimeField() class TestCustomInputFormatTimeField(FieldValues): @@ -724,7 +724,7 @@ class TestCustomInputFormatTimeField(FieldValues): '13:00': ['Time has wrong format. Use one of these formats instead: hh:mm[AM|PM]'], } outputs = {} - field = fields.TimeField(input_formats=['%I:%M%p']) + field = serializers.TimeField(input_formats=['%I:%M%p']) class TestCustomOutputFormatTimeField(FieldValues): @@ -736,7 +736,7 @@ class TestCustomOutputFormatTimeField(FieldValues): outputs = { datetime.time(13, 00): '01:00PM' } - field = fields.TimeField(format='%I:%M%p') + field = serializers.TimeField(format='%I:%M%p') class TestNoOutputFormatTimeField(FieldValues): @@ -748,7 +748,7 @@ class TestNoOutputFormatTimeField(FieldValues): outputs = { datetime.time(13, 00): datetime.time(13, 00) } - field = fields.TimeField(format=None) + field = serializers.TimeField(format=None) # Choice types... @@ -768,7 +768,7 @@ class TestChoiceField(FieldValues): outputs = { 'good': 'good' } - field = fields.ChoiceField( + field = serializers.ChoiceField( choices=[ ('poor', 'Poor quality'), ('medium', 'Medium quality'), @@ -794,7 +794,7 @@ class TestChoiceFieldWithType(FieldValues): '1': 1, 1: 1 } - field = fields.ChoiceField( + field = serializers.ChoiceField( choices=[ (1, 'Poor quality'), (2, 'Medium quality'), @@ -819,7 +819,7 @@ class TestChoiceFieldWithListChoices(FieldValues): outputs = { 'good': 'good' } - field = fields.ChoiceField(choices=('poor', 'medium', 'good')) + field = serializers.ChoiceField(choices=('poor', 'medium', 'good')) class TestMultipleChoiceField(FieldValues): @@ -838,7 +838,7 @@ class TestMultipleChoiceField(FieldValues): outputs = [ (['aircon', 'manual'], set(['aircon', 'manual'])) ] - field = fields.MultipleChoiceField( + field = serializers.MultipleChoiceField( choices=[ ('aircon', 'AirCon'), ('manual', 'Manual drive'), @@ -847,7 +847,7 @@ class TestMultipleChoiceField(FieldValues): ) -# File fields... +# File serializers... class MockFile: def __init__(self, name='', size=0, url=''): @@ -881,7 +881,7 @@ class TestFileField(FieldValues): (MockFile(name='example.txt', url='/example.txt'), '/example.txt'), ('', None) ] - field = fields.FileField(max_length=10) + field = serializers.FileField(max_length=10) class TestFieldFieldWithName(FieldValues): @@ -893,14 +893,14 @@ class TestFieldFieldWithName(FieldValues): outputs = [ (MockFile(name='example.txt', url='/example.txt'), 'example.txt') ] - field = fields.FileField(use_url=False) + field = serializers.FileField(use_url=False) # Stub out mock Django `forms.ImageField` class so we don't *actually* # call into it's regular validation, or require PIL for testing. class FailImageValidation(object): def to_python(self, value): - raise exceptions.ValidationFailed(self.error_messages['invalid_image']) + raise serializers.ValidationError(self.error_messages['invalid_image']) class PassImageValidation(object): @@ -917,7 +917,7 @@ class TestInvalidImageField(FieldValues): (MockFile(name='example.txt', size=10), ['Upload a valid image. The file you uploaded was either not an image or a corrupted image.']) ] outputs = {} - field = fields.ImageField(_DjangoImageField=FailImageValidation) + field = serializers.ImageField(_DjangoImageField=FailImageValidation) class TestValidImageField(FieldValues): @@ -929,10 +929,10 @@ class TestValidImageField(FieldValues): ] invalid_inputs = {} outputs = {} - field = fields.ImageField(_DjangoImageField=PassImageValidation) + field = serializers.ImageField(_DjangoImageField=PassImageValidation) -# Composite fields... +# Composite serializers... class TestListField(FieldValues): """ @@ -950,7 +950,7 @@ class TestListField(FieldValues): ([1, 2, 3], [1, 2, 3]), (['1', '2', '3'], [1, 2, 3]) ] - field = fields.ListField(child=fields.IntegerField()) + field = serializers.ListField(child=serializers.IntegerField()) # Tests for FieldField. @@ -963,7 +963,7 @@ class MockRequest: class TestFileFieldContext: def test_fully_qualified_when_request_in_context(self): - field = fields.FileField(max_length=10) + field = serializers.FileField(max_length=10) field._context = {'request': MockRequest()} obj = MockFile(name='example.txt', url='/example.txt') value = field.to_representation(obj) diff --git a/tests/test_relations.py b/tests/test_relations.py index 53c1b25c7..16ead1f2f 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -1,6 +1,6 @@ from .utils import mock_reverse, fail_reverse, BadType, MockObject, MockQueryset from django.core.exceptions import ImproperlyConfigured -from rest_framework import exceptions, serializers +from rest_framework import serializers from rest_framework.test import APISimpleTestCase import pytest @@ -30,13 +30,13 @@ class TestPrimaryKeyRelatedField(APISimpleTestCase): assert instance is self.instance def test_pk_related_lookup_does_not_exist(self): - with pytest.raises(exceptions.ValidationFailed) as excinfo: + with pytest.raises(serializers.ValidationError) as excinfo: self.field.to_internal_value(4) msg = excinfo.value.detail[0] assert msg == "Invalid pk '4' - object does not exist." def test_pk_related_lookup_invalid_type(self): - with pytest.raises(exceptions.ValidationFailed) as excinfo: + with pytest.raises(serializers.ValidationError) as excinfo: self.field.to_internal_value(BadType()) msg = excinfo.value.detail[0] assert msg == 'Incorrect type. Expected pk value, received BadType.' @@ -120,13 +120,13 @@ class TestSlugRelatedField(APISimpleTestCase): assert instance is self.instance def test_slug_related_lookup_does_not_exist(self): - with pytest.raises(exceptions.ValidationFailed) as excinfo: + with pytest.raises(serializers.ValidationError) as excinfo: self.field.to_internal_value('doesnotexist') msg = excinfo.value.detail[0] assert msg == 'Object with name=doesnotexist does not exist.' def test_slug_related_lookup_invalid_type(self): - with pytest.raises(exceptions.ValidationFailed) as excinfo: + with pytest.raises(serializers.ValidationError) as excinfo: self.field.to_internal_value(BadType()) msg = excinfo.value.detail[0] assert msg == 'Invalid value.' diff --git a/tests/test_validation.py b/tests/test_validation.py index 849c7e9d5..4d64e6e11 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -2,7 +2,7 @@ from __future__ import unicode_literals from django.core.validators import MaxValueValidator from django.db import models from django.test import TestCase -from rest_framework import exceptions, generics, serializers, status +from rest_framework import generics, serializers, status from rest_framework.test import APIRequestFactory factory = APIRequestFactory() @@ -37,7 +37,7 @@ class ShouldValidateModelSerializer(serializers.ModelSerializer): def validate_renamed(self, value): if len(value) < 3: - raise exceptions.ValidationFailed('Minimum 3 characters.') + raise serializers.ValidationError('Minimum 3 characters.') return value class Meta: @@ -73,10 +73,10 @@ class ValidationSerializer(serializers.Serializer): foo = serializers.CharField() def validate_foo(self, attrs, source): - raise exceptions.ValidationFailed("foo invalid") + raise serializers.ValidationError("foo invalid") def validate(self, attrs): - raise exceptions.ValidationFailed("serializer invalid") + raise serializers.ValidationError("serializer invalid") class TestAvoidValidation(TestCase): @@ -158,7 +158,7 @@ class TestChoiceFieldChoicesValidate(TestCase): value = self.CHOICES[0][0] try: f.to_internal_value(value) - except exceptions.ValidationFailed: + except serializers.ValidationError: self.fail("Value %s does not validate" % str(value)) # def test_nested_choices(self): From 140f8620aea44daa368b244d96c68377716fac7e Mon Sep 17 00:00:00 2001 From: Carl Meyer <carl@oddbird.net> Date: Thu, 16 Oct 2014 12:16:13 -0600 Subject: [PATCH 163/249] Set up serializer fields lazily on-demand. This avoids AppRegistryNotReady problems in Django 1.7 with nested serializers, which are instantiated at import time, possibly before Django's app registry is fully populated. --- rest_framework/serializers.py | 6 +++++- tests/test_relations.py | 5 +++-- tests/test_serializer.py | 4 +++- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index b3db35823..340c6be01 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -22,6 +22,7 @@ from django.db import models from django.forms import widgets from django.utils import six from django.utils.datastructures import SortedDict +from django.utils.functional import cached_property from django.core.exceptions import ObjectDoesNotExist from rest_framework.settings import api_settings @@ -197,7 +198,6 @@ class BaseSerializer(WritableField): self.init_data = data self.init_files = files self.object = instance - self.fields = self.get_fields() self._data = None self._files = None @@ -212,6 +212,10 @@ class BaseSerializer(WritableField): ##### # Methods to determine which fields to use when (de)serializing objects. + @cached_property + def fields(self): + return self.get_fields() + def get_default_fields(self): """ Return the complete set of default fields for the object, as a dict. diff --git a/tests/test_relations.py b/tests/test_relations.py index bc1db69fc..501a9208f 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -102,7 +102,7 @@ class RelatedFieldSourceTests(TestCase): self.assertEqual(value, ['BlogPost object']) # Regression for #1129 - def test_exception_for_incorect_fk(self): + def test_exception_for_incorrect_fk(self): """ Check that the exception message are correct if the source field doesn't exist. @@ -123,8 +123,9 @@ class RelatedFieldSourceTests(TestCase): (serializers.ModelSerializer,), attrs ) + serializer = TestSerializer(data={'name': 'foo'}) with self.assertRaises(AttributeError): - TestSerializer(data={'name': 'foo'}) + serializer.fields @unittest.skipIf(get_version() < '1.6.0', 'Upstream behaviour changed in v1.6') diff --git a/tests/test_serializer.py b/tests/test_serializer.py index 90f37cf2e..e72b723f0 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -327,7 +327,9 @@ class BasicTests(TestCase): """ Regression test for #652. """ - self.assertRaises(AssertionError, PersonSerializerInvalidReadOnly, []) + serializer = PersonSerializerInvalidReadOnly() + with self.assertRaises(AssertionError): + serializer.fields def test_serializer_data_is_cleared_on_save(self): """ From c5d1be8eac6cdb5cce000ec7c55e1847bfcf2359 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 22 Oct 2014 10:32:32 +0100 Subject: [PATCH 164/249] .validate() can raise field errors or non-field errors --- docs/topics/3.0-announcement.md | 45 +++++++++++++++++++++++++++++++-- rest_framework/serializers.py | 34 ++++++++++++++++++------- tests/test_serializer.py | 26 +++++++++++++++++++ 3 files changed, 94 insertions(+), 11 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 658b50d31..9aeb5df6f 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -163,7 +163,7 @@ The `validate_<field_name>` method hooks that can be attached to serializer clas raise serializers.ValidationError('This field should be a multiple of ten.') return attrs -This is now simplified slightly, and the method hooks simply take the value to be validated, and return it's validated value. +This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value. def validate_score(self, value): if value % 10 != 0: @@ -172,6 +172,22 @@ This is now simplified slightly, and the method hooks simply take the value to b Any ad-hoc validation that applies to more than one field should go in the `.validate(self, attrs)` method as usual. +Because `.validate_<field_name>` would previously accept the complete dictionary of attributes, it could be used to validate a field depending on the input in another field. Now if you need to do this you should use `.validate()` instead. + +You can either return `non_field_errors` from the validate method by raising a simple `ValidationError` + + def validate(self, attrs): + # serializer.errors == {'non_field_errors': ['A non field error']} + raise serailizers.ValidationError('A non field error') + +Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the `ValidationError`, like so: + + def validate(self, attrs): + # serializer.errors == {'my_field': ['A field error']} + raise serailizers.ValidationError({'my_field': 'A field error'}) + +This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field. + #### Limitations of ModelSerializer validation. This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes. @@ -189,7 +205,32 @@ REST framework 2.x attempted to automatically support writable nested serializat * It's unclear what behavior the user should expect when related models are passed `None` data. * It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records. -Using the `depth` option on `ModelSerializer` will now create **read-only nested serializers** by default. To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the `create()` and/or `update()` methods explicitly. +Using the `depth` option on `ModelSerializer` will now create **read-only nested serializers** by default. + +If you try to use a writable nested serializer without writing a custom `create()` and/or `update()` method you'll see an assertion error when you attempt to save the serializer. For example: + + >>> class ProfileSerializer(serializers.ModelSerializer): + >>> class Meta: + >>> model = Profile + >>> fields = ('address', 'phone') + >>> + >>> class UserSerializer(serializers.ModelSerializer): + >>> profile = ProfileSerializer() + >>> class Meta: + >>> model = User + >>> fields = ('username', 'email', 'profile') + >>> + >>> data = { + >>> 'username': 'lizzy', + >>> 'email': 'lizzy@example.com', + >>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'} + >>> } + >>> + >>> serializer = UserSerializer(data=data) + >>> serializer.save() + AssertionError: The `.create()` method does not suport nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields. + +To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the `create()` and/or `update()` methods explicitly. class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index d29dc684a..59f38a73d 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -99,10 +99,10 @@ class BaseSerializer(Field): def is_valid(self, raise_exception=False): assert not hasattr(self, 'restore_object'), ( - 'Serializer %s has old-style version 2 `.restore_object()` ' + 'Serializer `%s.%s` has old-style version 2 `.restore_object()` ' 'that is no longer compatible with REST framework 3. ' 'Use the new-style `.create()` and `.update()` methods instead.' % - self.__class__.__name__ + (self.__class__.__module__, self.__class__.__name__) ) if not hasattr(self, '_validated_data'): @@ -341,9 +341,22 @@ class Serializer(BaseSerializer): value = self.validate(value) assert value is not None, '.validate() should return the validated data' except ValidationError as exc: - raise ValidationError({ - api_settings.NON_FIELD_ERRORS_KEY: exc.detail - }) + 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] + }) + return value def to_internal_value(self, data): @@ -507,14 +520,17 @@ class ModelSerializer(Serializer): self._kwargs['validators'] = validators def create(self, validated_attrs): + # 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 not field.read_only for field in self.fields.values() ), ( 'The `.create()` method does not suport nested writable fields ' 'by default. Write an explicit `.create()` method for serializer ' - '%s, or set `read_only=True` on nested serializer fields.' % - self.__class__.__name__ + '`%s.%s`, or set `read_only=True` on nested serializer fields.' % + (self.__class__.__module__, self.__class__.__name__) ) ModelClass = self.Meta.model @@ -544,8 +560,8 @@ class ModelSerializer(Serializer): ), ( 'The `.update()` method does not suport nested writable fields ' 'by default. Write an explicit `.update()` method for serializer ' - '%s, or set `read_only=True` on nested serializer fields.' % - self.__class__.__name__ + '`%s.%s`, or set `read_only=True` on nested serializer fields.' % + (self.__class__.__module__, self.__class__.__name__) ) for attr, value in validated_attrs.items(): diff --git a/tests/test_serializer.py b/tests/test_serializer.py index 4df1b7364..77d5c3199 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -43,6 +43,32 @@ class TestSerializer: serializer.data +class TestValidateMethod: + def test_non_field_error_validate_method(self): + class ExampleSerializer(serializers.Serializer): + char = serializers.CharField() + integer = serializers.IntegerField() + + def validate(self, attrs): + raise serializers.ValidationError('Non field error') + + serializer = ExampleSerializer(data={'char': 'abc', 'integer': 123}) + assert not serializer.is_valid() + assert serializer.errors == {'non_field_errors': ['Non field error']} + + def test_field_error_validate_method(self): + class ExampleSerializer(serializers.Serializer): + char = serializers.CharField() + integer = serializers.IntegerField() + + def validate(self, attrs): + raise serializers.ValidationError({'char': 'Field error'}) + + serializer = ExampleSerializer(data={'char': 'abc', 'integer': 123}) + assert not serializer.is_valid() + assert serializer.errors == {'char': ['Field error']} + + class TestBaseSerializer: def setup(self): class ExampleSerializer(serializers.BaseSerializer): From ae53fdff9c6bb3e81a1ec005134462f0d629688f Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 22 Oct 2014 13:30:28 +0100 Subject: [PATCH 165/249] First pass at unique_for_date, unique_for_month, unique_for_year --- rest_framework/fields.py | 10 ++- rest_framework/serializers.py | 26 +++++--- rest_framework/validators.py | 121 +++++++++++++++++++++++++++------- tests/test_validators.py | 68 +++++++++++++++++++ 4 files changed, 191 insertions(+), 34 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 2da4aa8b2..e939b2f29 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -268,11 +268,17 @@ class Field(object): """ errors = [] for validator in self.validators: - if getattr(validator, 'requires_context', False): - validator.serializer_field = self + if hasattr(validator, 'set_context'): + validator.set_context(self) + try: validator(value) except ValidationError as exc: + # If the validation error contains a mapping of fields to + # errors then simply raise it immediately rather than + # attempting to accumulate a list of errors. + if isinstance(exc.detail, dict): + raise errors.extend(exc.detail) except DjangoValidationError as exc: errors.extend(exc.messages) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 59f38a73d..5770fcf6a 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -23,7 +23,9 @@ from rest_framework.utils.field_mapping import ( get_relation_kwargs, get_nested_relation_kwargs, ClassLookupDict ) -from rest_framework.validators import UniqueTogetherValidator +from rest_framework.validators import ( + UniqueForDateValidator, UniqueTogetherValidator +) import copy import inspect import warnings @@ -578,15 +580,9 @@ class ModelSerializer(Serializer): validators = [] model_class = self.Meta.model - for unique_together in model_class._meta.unique_together: - if field_names.issuperset(set(unique_together)): - validator = UniqueTogetherValidator( - queryset=model_class._default_manager, - fields=unique_together - ) - validators.append(validator) - - for parent_class in model_class._meta.parents.keys(): + # 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( @@ -595,6 +591,16 @@ class ModelSerializer(Serializer): ) validators.append(validator) + 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) + return validators def _get_base_fields(self): diff --git a/rest_framework/validators.py b/rest_framework/validators.py index f76faaa4b..e302a0e41 100644 --- a/rest_framework/validators.py +++ b/rest_framework/validators.py @@ -6,38 +6,36 @@ This gives us better separation of concerns, allows us to use single-step object creation, and makes it possible to switch between using the implicit `ModelSerializer` class and an equivelent explicit `Serializer` class. """ -from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ +from rest_framework.exceptions import ValidationError from rest_framework.utils.representation import smart_repr class UniqueValidator: """ Validator that corresponds to `unique=True` on a model field. + + Should be applied to an individual field on the serializer. """ - # Validators with `requires_context` will have the field instance - # passed to them when the field is instantiated. - requires_context = True message = _('This field must be unique.') def __init__(self, queryset): self.queryset = queryset self.serializer_field = None - def __call__(self, value): - field = self.serializer_field - - # Determine the model field name that the serializer field corresponds to. - field_name = field.source_attrs[0] if field.source_attrs else field.field_name - + 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] # Determine the existing instance, if this is an update operation. - instance = getattr(field.parent, 'instance', None) + self.instance = getattr(serializer_field.parent, 'instance', None) + def __call__(self, value): # Ensure uniqueness. - filter_kwargs = {field_name: value} + filter_kwargs = {self.field_name: value} queryset = self.queryset.filter(**filter_kwargs) - if instance: - queryset = queryset.exclude(pk=instance.pk) + if self.instance is not None: + queryset = queryset.exclude(pk=self.instance.pk) if queryset.exists(): raise ValidationError(self.message) @@ -51,8 +49,9 @@ class UniqueValidator: class UniqueTogetherValidator: """ Validator that corresponds to `unique_together = (...)` on a model class. + + Should be applied to the serializer class, not to an individual field. """ - requires_context = True message = _('The fields {field_names} must make a unique set.') def __init__(self, queryset, fields): @@ -60,19 +59,18 @@ class UniqueTogetherValidator: self.fields = fields self.serializer_field = None - def __call__(self, value): - serializer = self.serializer_field - + def set_context(self, serializer): # Determine the existing instance, if this is an update operation. - instance = getattr(serializer, 'instance', None) + self.instance = getattr(serializer, 'instance', None) + def __call__(self, attrs): # Ensure uniqueness. filter_kwargs = dict([ - (field_name, value[field_name]) for field_name in self.fields + (field_name, attrs[field_name]) for field_name in self.fields ]) queryset = self.queryset.filter(**filter_kwargs) - if instance: - queryset = queryset.exclude(pk=instance.pk) + if self.instance is not None: + queryset = queryset.exclude(pk=self.instance.pk) if queryset.exists(): field_names = ', '.join(self.fields) raise ValidationError(self.message.format(field_names=field_names)) @@ -83,3 +81,82 @@ class UniqueTogetherValidator: smart_repr(self.queryset), smart_repr(self.fields) ) + + +class BaseUniqueForValidator: + message = None + + def __init__(self, queryset, field, date_field): + self.queryset = queryset + self.field = field + self.date_field = date_field + + 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] + # Determine the existing instance, if this is an update operation. + self.instance = getattr(serializer, 'instance', None) + + def get_filter_kwargs(self, attrs): + raise NotImplementedError('`get_filter_kwargs` must be implemented.') + + def __call__(self, attrs): + filter_kwargs = self.get_filter_kwargs(attrs) + + queryset = self.queryset.filter(**filter_kwargs) + if self.instance is not None: + queryset = queryset.exclude(pk=self.instance.pk) + if queryset.exists(): + message = self.message.format(date_field=self.date_field) + raise ValidationError({self.field: message}) + + def __repr__(self): + return '<%s(queryset=%s, field=%s, date_field=%s)>' % ( + self.__class__.__name__, + smart_repr(self.queryset), + smart_repr(self.field), + smart_repr(self.date_field) + ) + + +class UniqueForDateValidator(BaseUniqueForValidator): + message = _('This field must be unique for the "{date_field}" date.') + + def get_filter_kwargs(self, attrs): + value = attrs[self.field] + date = attrs[self.date_field] + + filter_kwargs = {} + filter_kwargs[self.field_name] = value + 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 filter_kwargs + + +class UniqueForMonthValidator(BaseUniqueForValidator): + message = _('This field must be unique for the "{date_field}" month.') + + def get_filter_kwargs(self, attrs): + value = attrs[self.field] + date = attrs[self.date_field] + + filter_kwargs = {} + filter_kwargs[self.field_name] = value + filter_kwargs['%s__month' % self.date_field_name] = date.month + return filter_kwargs + + +class UniqueForYearValidator(BaseUniqueForValidator): + message = _('This field must be unique for the "{date_field}" year.') + + def get_filter_kwargs(self, attrs): + value = attrs[self.field] + date = attrs[self.date_field] + + filter_kwargs = {} + filter_kwargs[self.field_name] = value + filter_kwargs['%s__year' % self.date_field_name] = date.year + return filter_kwargs diff --git a/tests/test_validators.py b/tests/test_validators.py index 1d0814115..5adb76783 100644 --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -1,6 +1,7 @@ from django.db import models from django.test import TestCase from rest_framework import serializers +import datetime def dedent(blocktext): @@ -147,3 +148,70 @@ class TestUniquenessTogetherValidation(TestCase): race_name = CharField(max_length=100) """) assert repr(serializer) == expected + + +# Tests for `UniqueForDateValidator` +# ---------------------------------- + +class UniqueForDateModel(models.Model): + slug = models.CharField(max_length=100, unique_for_date='published') + published = models.DateField() + + +class UniqueForDateSerializer(serializers.ModelSerializer): + class Meta: + model = UniqueForDateModel + + +class TestUniquenessForDateValidation(TestCase): + def setUp(self): + self.instance = UniqueForDateModel.objects.create( + slug='existing', + published='2000-01-01' + ) + + def test_repr(self): + serializer = UniqueForDateSerializer() + expected = dedent(""" + UniqueForDateSerializer(validators=[<UniqueForDateValidator(queryset=UniqueForDateModel.objects.all(), field='slug', date_field='published')>]): + id = IntegerField(label='ID', read_only=True) + slug = CharField(max_length=100) + published = DateField() + """) + assert repr(serializer) == expected + + def test_is_not_unique_for_date(self): + """ + Failing unique for date validation should result in field error. + """ + data = {'slug': 'existing', 'published': '2000-01-01'} + serializer = UniqueForDateSerializer(data=data) + assert not serializer.is_valid() + assert serializer.errors == { + 'slug': ['This field must be unique for the "published" date.'] + } + + def test_is_unique_for_date(self): + """ + Passing unique for date validation. + """ + data = {'slug': 'existing', 'published': '2000-01-02'} + serializer = UniqueForDateSerializer(data=data) + assert serializer.is_valid() + assert serializer.validated_data == { + 'slug': 'existing', + 'published': datetime.date(2000, 1, 2) + } + + def test_updated_instance_excluded_from_unique_for_date(self): + """ + When performing an update, the existing instance does not count + as a match against unique_for_date. + """ + data = {'slug': 'existing', 'published': '2000-01-01'} + serializer = UniqueForDateSerializer(instance=self.instance, data=data) + assert serializer.is_valid() + assert serializer.validated_data == { + 'slug': 'existing', + 'published': datetime.date(2000, 1, 1) + } From f9c0e6ee1b045f69920cf9c3aceda4e44f110bfb Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 22 Oct 2014 16:29:09 +0100 Subject: [PATCH 166/249] unique_for_month, unique_for_year --- rest_framework/serializers.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 5770fcf6a..b45f343a4 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -24,7 +24,8 @@ from rest_framework.utils.field_mapping import ( ClassLookupDict ) from rest_framework.validators import ( - UniqueForDateValidator, UniqueTogetherValidator + UniqueForDateValidator, UniqueForMonthValidator, UniqueForYearValidator, + UniqueTogetherValidator ) import copy import inspect @@ -601,6 +602,22 @@ class ModelSerializer(Serializer): ) validators.append(validator) + 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) + + 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) + return validators def _get_base_fields(self): From 702f47700de2c10f26f06b23099740c408ffe797 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 24 Oct 2014 12:12:01 +0100 Subject: [PATCH 167/249] Updated requirements --- README.md | 2 +- docs/index.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 63513f758..e71fe7bf1 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ There is a live example API for testing purposes, [available here][sandbox]. # Requirements * Python (2.6.5+, 2.7, 3.2, 3.3) -* Django (1.4.2+, 1.5, 1.6, 1.7) +* Django (1.4.11+, 1.5.5+, 1.6, 1.7) # Installation diff --git a/docs/index.md b/docs/index.md index e4c971f95..9d436ad5a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -50,7 +50,7 @@ Some reasons you might want to use REST framework: REST framework requires the following: * Python (2.6.5+, 2.7, 3.2, 3.3) -* Django (1.4.2+, 1.5, 1.6, 1.7) +* Django (1.4.11+, 1.5.5+, 1.6, 1.7) The following packages are optional: From 9ebaabd6eb31e18cf0bb1c70893f719f18ecb0f9 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Tue, 28 Oct 2014 16:21:49 +0000 Subject: [PATCH 168/249] unique_for_date/unique_for_month/unique_for_year --- rest_framework/fields.py | 54 +++++++++++++++++++++-- rest_framework/serializers.py | 82 +++++++++++++++++++++++++++++++++-- tests/test_fields.py | 27 ++++++++++++ tests/test_validators.py | 39 ++++++++++++++++- 4 files changed, 194 insertions(+), 8 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index e939b2f29..82b7eb374 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -92,13 +92,35 @@ def set_value(dictionary, keys, value): dictionary[keys[-1]] = value +class CreateOnlyDefault: + """ + This class may be used to provide default values that are only used + for create operations, but that do not return any value for update + operations. + """ + def __init__(self, default): + self.default = default + + def set_context(self, serializer_field): + self.is_update = serializer_field.parent.instance is not None + + def __call__(self): + if self.is_update: + raise SkipField() + if callable(self.default): + return self.default() + return self.default + + def __repr__(self): + return '%s(%s)' % (self.__class__.__name__, repr(self.default)) + + class SkipField(Exception): pass NOT_READ_ONLY_WRITE_ONLY = 'May not set both `read_only` and `write_only`' NOT_READ_ONLY_REQUIRED = 'May not set both `read_only` and `required`' -NOT_READ_ONLY_DEFAULT = 'May not set both `read_only` and `default`' NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`' USE_READONLYFIELD = 'Field(read_only=True) should be ReadOnlyField' MISSING_ERROR_MESSAGE = ( @@ -132,7 +154,6 @@ class Field(object): # Some combinations of keyword arguments do not make sense. assert not (read_only and write_only), NOT_READ_ONLY_WRITE_ONLY assert not (read_only and required), NOT_READ_ONLY_REQUIRED - assert not (read_only and default is not empty), NOT_READ_ONLY_DEFAULT assert not (required and default is not empty), NOT_REQUIRED_DEFAULT assert not (read_only and self.__class__ == Field), USE_READONLYFIELD @@ -230,7 +251,9 @@ class Field(object): """ if self.default is empty: raise SkipField() - if is_simple_callable(self.default): + if callable(self.default): + if hasattr(self.default, 'set_context'): + self.default.set_context(self) return self.default() return self.default @@ -244,6 +267,9 @@ class Field(object): May raise `SkipField` if the field should not be included in the validated data. """ + if self.read_only: + return self.get_default() + if data is empty: if getattr(self.root, 'partial', False): raise SkipField() @@ -1033,6 +1059,28 @@ class ReadOnlyField(Field): return value +class HiddenField(Field): + """ + A hidden field does not take input from the user, or present any output, + but it does populate a field in `validated_data`, based on its default + value. This is particularly useful when we have a `unique_for_date` + constrain on a pair of fields, as we need some way to include the date in + the validated data. + """ + def __init__(self, **kwargs): + assert 'default' in kwargs, 'default is a required argument.' + kwargs['write_only'] = True + super(HiddenField, self).__init__(**kwargs) + + def get_value(self, dictionary): + # We always use the default value for `HiddenField`. + # User input is never provided or accepted. + return empty + + def to_internal_value(self, data): + return data + + class SerializerMethodField(Field): """ A read-only field that get its representation from calling a method on the diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index b45f343a4..6aab020ef 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -12,6 +12,7 @@ response content is handled by parsers and renderers. """ from django.core.exceptions import ImproperlyConfigured from django.db import models +from django.db.models.fields import FieldDoesNotExist from django.utils import six from django.utils.datastructures import SortedDict from rest_framework.exceptions import ValidationError @@ -368,7 +369,10 @@ class Serializer(BaseSerializer): """ ret = {} errors = ReturnDict(serializer=self) - fields = [field for field in self.fields.values() if not field.read_only] + fields = [ + field for field in self.fields.values() + if (not field.read_only) or (field.default is not empty) + ] for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) @@ -517,7 +521,7 @@ class ModelSerializer(Serializer): def __init__(self, *args, **kwargs): super(ModelSerializer, self).__init__(*args, **kwargs) if 'validators' not in kwargs: - validators = self.get_unique_together_validators() + validators = self.get_default_validators() if validators: self.validators.extend(validators) self._kwargs['validators'] = validators @@ -572,7 +576,7 @@ class ModelSerializer(Serializer): instance.save() return instance - def get_unique_together_validators(self): + def get_default_validators(self): field_names = set([ field.source for field in self.fields.values() if (field.source != '*') and ('.' not in field.source) @@ -592,6 +596,7 @@ class ModelSerializer(Serializer): ) validators.append(validator) + # 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: @@ -637,7 +642,7 @@ class ModelSerializer(Serializer): # Retrieve metadata about fields & relationships on the model class. info = model_meta.get_field_info(model) - # Use the default set of fields if none is supplied explicitly. + # 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) @@ -645,6 +650,72 @@ class ModelSerializer(Serializer): for field_name in exclude: fields.remove(field_name) + # 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 + 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 + + # 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_fields = {} + for model_field_name, field_name in model_field_mapping.items(): + try: + model_field = model._meta.get_field(model_field_name) + except FieldDoesNotExist: + continue + + # Deal with each of the `unique_for_*` cases. + for date_field_name in ( + model_field.unique_for_date, + model_field.unique_for_month, + model_field.unique_for_year + ): + if date_field_name is None: + continue + + # Get the model field that is refered too. + date_field = model._meta.get_field(date_field_name) + + if date_field.auto_now_add: + default = CreateOnlyDefault(timezone.now) + elif date_field.auto_now: + default = timezone.now + elif date_field.has_default(): + default = model_field.default + else: + default = empty + + if date_field_name in model_field_mapping: + # The corresponding date field is present in the serializer + if date_field_name not in extra_kwargs: + extra_kwargs[date_field_name] = {} + if default is empty: + if 'required' not in extra_kwargs[date_field_name]: + extra_kwargs[date_field_name]['required'] = True + else: + if 'default' not in extra_kwargs[date_field_name]: + extra_kwargs[date_field_name]['default'] = default + else: + # The corresponding date field is not present in the, + # serializer. We have a default to use for the date, so + # add in a hidden field that populates it. + unique_fields[date_field_name] = HiddenField(default=default) + + # 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. @@ -723,6 +794,9 @@ class ModelSerializer(Serializer): # Create the serializer field. ret[field_name] = field_cls(**kwargs) + for field_name, field in unique_fields.items(): + ret[field_name] = field + return ret def _include_additional_options(self, extra_kwargs): diff --git a/tests/test_fields.py b/tests/test_fields.py index 6dc5f87d2..3e102ab5a 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -215,6 +215,33 @@ class TestBooleanHTMLInput: assert serializer.validated_data == {'archived': False} +class TestCreateOnlyDefault: + def setup(self): + default = serializers.CreateOnlyDefault('2001-01-01') + + class TestSerializer(serializers.Serializer): + published = serializers.HiddenField(default=default) + text = serializers.CharField() + self.Serializer = TestSerializer + + def test_create_only_default_is_provided(self): + serializer = self.Serializer(data={'text': 'example'}) + assert serializer.is_valid() + assert serializer.validated_data == { + 'text': 'example', 'published': '2001-01-01' + } + + def test_create_only_default_is_not_provided_on_update(self): + instance = { + 'text': 'example', 'published': '2001-01-01' + } + serializer = self.Serializer(instance, data={'text': 'example'}) + assert serializer.is_valid() + assert serializer.validated_data == { + 'text': 'example', + } + + # Tests for field input and output values. # ---------------------------------------- diff --git a/tests/test_validators.py b/tests/test_validators.py index 5adb76783..6cc52c837 100644 --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -176,7 +176,7 @@ class TestUniquenessForDateValidation(TestCase): UniqueForDateSerializer(validators=[<UniqueForDateValidator(queryset=UniqueForDateModel.objects.all(), field='slug', date_field='published')>]): id = IntegerField(label='ID', read_only=True) slug = CharField(max_length=100) - published = DateField() + published = DateField(required=True) """) assert repr(serializer) == expected @@ -215,3 +215,40 @@ class TestUniquenessForDateValidation(TestCase): 'slug': 'existing', 'published': datetime.date(2000, 1, 1) } + + +class HiddenFieldUniqueForDateModel(models.Model): + slug = models.CharField(max_length=100, unique_for_date='published') + published = models.DateTimeField(auto_now_add=True) + + +class TestHiddenFieldUniquenessForDateValidation(TestCase): + def test_repr_date_field_not_included(self): + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = HiddenFieldUniqueForDateModel + fields = ('id', 'slug') + + serializer = TestSerializer() + expected = dedent(""" + TestSerializer(validators=[<UniqueForDateValidator(queryset=HiddenFieldUniqueForDateModel.objects.all(), field='slug', date_field='published')>]): + id = IntegerField(label='ID', read_only=True) + slug = CharField(max_length=100) + published = HiddenField(default=CreateOnlyDefault(<function now>)) + """) + assert repr(serializer) == expected + + def test_repr_date_field_included(self): + class TestSerializer(serializers.ModelSerializer): + class Meta: + model = HiddenFieldUniqueForDateModel + fields = ('id', 'slug', 'published') + + serializer = TestSerializer() + expected = dedent(""" + TestSerializer(validators=[<UniqueForDateValidator(queryset=HiddenFieldUniqueForDateModel.objects.all(), field='slug', date_field='published')>]): + id = IntegerField(label='ID', read_only=True) + slug = CharField(max_length=100) + published = DateTimeField(default=CreateOnlyDefault(<function now>), read_only=True) + """) + assert repr(serializer) == expected From 8af3d5db492c7468a1f2e4befdcd78b59216241d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Padilla?= <jpadilla@webapplicate.com> Date: Tue, 28 Oct 2014 16:58:25 -0400 Subject: [PATCH 169/249] Use PYTHONDONTWRITEBYTECODE=1 on tox environment This fixes bad marshal data errors after running tests with tox and later running tests manually via runtests.py. Fixes #1957 --- tox.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tox.ini b/tox.ini index d40a70799..b3f53cce2 100644 --- a/tox.ini +++ b/tox.ini @@ -9,6 +9,8 @@ envlist = [testenv] commands = ./runtests.py --fast +setenv = + PYTHONDONTWRITEBYTECODE=1 [testenv:flake8] basepython = python2.7 From f25f05dde58908ca6885c88499e4d5984f0f3502 Mon Sep 17 00:00:00 2001 From: Andrew Conti <agc11d@gmail.com> Date: Wed, 29 Oct 2014 16:31:36 -0400 Subject: [PATCH 170/249] Update authentication.md Based on the [new documentation](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.get_user_model) for Django 1.7 we should now use: ```python @receiver(post_save, sender=settings.AUTH_USER_MODEL) ``` instead of: ```python @receiver(post_save, sender=get_user_model()) ``` because `get_user_model()` only works once Django has imported all models. Otherwise you'll get: ```python django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. ``` When trying to start your sever after adding token authentication. From the Docs, ( linked above as well ) : >New in Django 1.7: >When connecting to signals sent by the User model, you should specify the custom model using the AUTH_USER_MODEL setting. --- docs/api-guide/authentication.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index b355012e1..3a5156fd1 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -168,12 +168,13 @@ The `curl` command line tool may be useful for testing token authenticated APIs. If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal. + from django.conf import settings from django.contrib.auth import get_user_model from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token - @receiver(post_save, sender=get_user_model()) + @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) From 0dea509dc9847206d830a0e48b91fa1c5b8ac52e Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 30 Oct 2014 15:59:16 +0000 Subject: [PATCH 171/249] Nested serializer tests --- tests/test_serializer_nested.py | 41 +++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/tests/test_serializer_nested.py b/tests/test_serializer_nested.py index b0f64ca77..5e2074490 100644 --- a/tests/test_serializer_nested.py +++ b/tests/test_serializer_nested.py @@ -1,3 +1,44 @@ +from rest_framework import serializers + + +class TestNestedSerializer: + def setup(self): + class NestedSerializer(serializers.Serializer): + one = serializers.IntegerField(max_value=10) + two = serializers.IntegerField(max_value=10) + + class TestSerializer(serializers.Serializer): + nested = NestedSerializer() + + self.Serializer = TestSerializer + + def test_nested_validate(self): + input_data = { + 'nested': { + 'one': '1', + 'two': '2', + } + } + expected_data = { + 'nested': { + 'one': 1, + 'two': 2, + } + } + serializer = self.Serializer(data=input_data) + assert serializer.is_valid() + assert serializer.validated_data == expected_data + + def test_nested_serialize_empty(self): + expected_data = { + 'nested': { + 'one': None, + 'two': None + } + } + serializer = self.Serializer() + assert serializer.data == expected_data + # """ # Tests to cover nested serializers. From cd40dcb06500424ef9016913a1a89db0deed8a1f Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 30 Oct 2014 16:53:12 +0000 Subject: [PATCH 172/249] Ensure json.dumps(separators=...) works on both 2.x and 3.x --- rest_framework/compat.py | 9 +++++++++ rest_framework/renderers.py | 6 ++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/rest_framework/compat.py b/rest_framework/compat.py index 4ab23a4da..0201bd830 100644 --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -291,6 +291,15 @@ except ImportError: oauth2_constants = None provider_now = None +# `seperators` argument to `json.dumps()` differs between 2.x and 3.x +# See: http://bugs.python.org/issue22767 +if six.PY3: + SHORT_SEPARATORS = (',', ':') + LONG_SEPARATORS = (', ', ': ') +else: + SHORT_SEPARATORS = (b',', b':') + LONG_SEPARATORS = (b', ', b': ') + # Handle lazy strings across Py2/Py3 from django.utils.functional import Promise diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 4dfd0f498..c950b4981 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -18,7 +18,9 @@ from django.test.client import encode_multipart from django.utils import six from django.utils.xmlutils import SimplerXMLGenerator from rest_framework import exceptions, serializers, status, VERSION -from rest_framework.compat import StringIO, smart_text, yaml +from rest_framework.compat import ( + SHORT_SEPARATORS, LONG_SEPARATORS, StringIO, smart_text, yaml +) from rest_framework.exceptions import ParseError from rest_framework.settings import api_settings from rest_framework.request import is_form_media_type, override_method @@ -87,7 +89,7 @@ class JSONRenderer(BaseRenderer): renderer_context = renderer_context or {} indent = self.get_indent(accepted_media_type, renderer_context) - separators = (',', ':') if (indent is None and self.compact) else (', ', ': ') + separators = SHORT_SEPARATORS if (indent is None and self.compact) else LONG_SEPARATORS ret = json.dumps( data, cls=self.encoder_class, From 27622058872c00e357deb7d7e86619a793ef4b41 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 31 Oct 2014 13:47:36 +0000 Subject: [PATCH 173/249] Validator documentation and tweaks --- docs/api-guide/validators.md | 183 ++++++++++++++++++++++++++++++++++ docs/index.md | 2 + docs/template.html | 1 + mkdocs.py | 1 + rest_framework/serializers.py | 2 + rest_framework/validators.py | 9 +- 6 files changed, 195 insertions(+), 3 deletions(-) diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index e69de29bb..52c9e0822 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -0,0 +1,183 @@ +<a class="github" href="validators.py"></a> + +# Validators + +> Validators can be useful for re-using validation logic between different types of fields. +> +> — [Django documentation][cite] + +Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes. + +Sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes. + +## Validation in REST framework + +Validation in Django REST framework serializers is handled a little differently to how validation works in Django's `ModelForm` class. + +With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons: + +* It introduces a proper separation of concerns, making your code behaviour more obvious. +* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behaviour being used for `ModelSerializer` is simple to replicate. +* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behaviour being called on the model instance. + +When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using a `Serializer` classes instead, then you need to define the validation rules explicitly. + +#### Example + +As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint. + + class CustomerReportRecord(models.Model): + time_raised = models.DateTimeField(default=timezone.now, editable=False) + reference = models.CharField(unique=True, max_length=20) + description = models.TextField() + +Here's a basic `ModelSerializer` that we can use for creating or updating instances of `CustomerReportRecord`: + + class CustomerReportSerializer(serializers.ModelSerializer): + class Meta: + model = CustomerReportRecord + +If we open up the Django shell using `manage.py shell` we can now + + >>> from project.example.serializers import CustomerReportSerializer + >>> serializer = CustomerReportSerializer() + >>> print(repr(serializer)) + CustomerReportSerializer(): + id = IntegerField(label='ID', read_only=True) + time_raised = DateTimeField(read_only=True) + reference = CharField(max_length=20, validators=[<UniqueValidator(queryset=CustomerReportRecord.objects.all())>]) + description = CharField(style={'type': 'textarea'}) + +The interesting bit here is the `reference` field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field. + +Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below. + +--- + +## UniqueValidator + +This validator can be used to enforce the `unique=True` constraint on model fields. +It takes a single required argument, and an optional `messages` argument: + +* `queryset` *required* - This is the queryset against which uniqueness should be enforced. +* `message` - The error message that should be used when validation fails. + +This validator should be applied to *serializer fields*, like so: + + slug = SlugField( + max_length=100, + validators=[UniqueValidator(queryset=BlogPost.objects.all())] + ) + +## UniqueTogetherValidator + +This validator can be used to enforce `unique_together` constraints on model instances. +It has two required arguments, and a single optional `messages` argument: + +* `queryset` *required* - This is the queryset against which uniqueness should be enforced. +* `fields` *required* - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class. +* `message` - The error message that should be used when validation fails. + +The validator should be applied to *serializer classes*, like so: + + class ExampleSerializer(serializers.Serializer): + # ... + class Meta: + # ToDo items belong to a parent list, and have an ordering defined + # by the 'position' field. No two items in a given list may share + # the same position. + validators = [ + UniqueTogetherValidator( + queryset=ToDoItem.objects.all(), + fields=('list', 'position') + ) + ] + +## UniqueForDateValidator + +## UniqueForMonthValidator + +## UniqueForYearValidator + +These validators can be used to enforce the `unique_for_date`, `unique_for_month` and `unique_for_year` constraints on model instances. They take the following arguments: + +* `queryset` *required* - This is the queryset against which uniqueness should be enforced. +* `field` *required* - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class. +* `date_field` *required* - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class. +* `message` - The error message that should be used when validation fails. + +The validator should be applied to *serializer classes*, like so: + + class ExampleSerializer(serializers.Serializer): + # ... + class Meta: + # Blog posts should have a slug that is unique for the current year. + validators = [ + UniqueForYearValidator( + queryset=BlogPostItem.objects.all(), + field='slug', + date_field='published' + ) + ] + +The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class `default=...`, because the value being used for the default wouldn't be generated until after the validation has run. + +There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using `ModelSerializer` you'll probably simply rely on the defaults that REST framework generates for you, but if you are using `Serializer` or simply want more explicit control, use on of the styles demonstrated below. + +#### Using with a writable date field. + +If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a `default` argument, or by setting `required=True`. + + published = serializers.DateTimeField(required=True) + +#### Using with a read-only date field. + +If you want the date field to be visible, but not editable by the user, then set `read_only=True` and additionally set a `default=...` argument. + + published = serializers.DateTimeField(read_only=True, default=timezone.now) + +The field will not be writable to the user, but the default value will still be passed through to the `validated_data`. + +#### Using with a hidden date field. + +If you want the date field to be entirely hidden from the user, then use `HiddenField`. This field type does not accept user input, but instead always returns it's default value to the `validated_data` in the serializer. + + published = serializers.HiddenField(default=timezone.now) + +--- + +# Writing custom validators + +You can use any of Django's existing validators, or write your own custom validators. + +## Function based + +A validator may be any callable that raises a `serializers.ValidationError` on failure. + + def even_number(value): + if value % 2 != 0: + raise serializers.ValidationError('This field must be an even number.') + +## Class based + +To write a class based validator, use the `__call__` method. Class based validators are useful as they allow you to parameterize and reuse behavior. + + class MultipleOf: + def __init__(self, base): + self.base = base + + def __call__(self, value): + if value % self.base != 0 + message = 'This field must be a multiple of %d.' % self.base + raise serializers.ValidationError(message) + +#### Using `set_context()` + +In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a `set_context` method on a class based validator. + + def set_context(self, serializer_field): + # Determine if this is an update or a create operation. + # In `__call__` we can then use that information to modify the validation behavior. + self.is_update = serializer_field.parent.instance is not None + +[cite]: https://docs.djangoproject.com/en/dev/ref/validators/ diff --git a/docs/index.md b/docs/index.md index 9d436ad5a..cff7b8351 100644 --- a/docs/index.md +++ b/docs/index.md @@ -173,6 +173,7 @@ The API guide is your complete reference manual to all the functionality provide * [Serializers][serializers] * [Serializer fields][fields] * [Serializer relations][relations] +* [Validation][validation] * [Authentication][authentication] * [Permissions][permissions] * [Throttling][throttling] @@ -294,6 +295,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [serializers]: api-guide/serializers.md [fields]: api-guide/fields.md [relations]: api-guide/relations.md +[validation]: api-guide/validation.md [authentication]: api-guide/authentication.md [permissions]: api-guide/permissions.md [throttling]: api-guide/throttling.md diff --git a/docs/template.html b/docs/template.html index bb3ae221a..0d2fb16eb 100644 --- a/docs/template.html +++ b/docs/template.html @@ -95,6 +95,7 @@ a.fusion-poweredby { <li><a href="{{ base_url }}/api-guide/serializers{{ suffix }}">Serializers</a></li> <li><a href="{{ base_url }}/api-guide/fields{{ suffix }}">Serializer fields</a></li> <li><a href="{{ base_url }}/api-guide/relations{{ suffix }}">Serializer relations</a></li> + <li><a href="{{ base_url }}/api-guide/validation{{ suffix }}">Validation</a></li> <li><a href="{{ base_url }}/api-guide/authentication{{ suffix }}">Authentication</a></li> <li><a href="{{ base_url }}/api-guide/permissions{{ suffix }}">Permissions</a></li> <li><a href="{{ base_url }}/api-guide/throttling{{ suffix }}">Throttling</a></li> diff --git a/mkdocs.py b/mkdocs.py index 25cb55e21..acd11b633 100755 --- a/mkdocs.py +++ b/mkdocs.py @@ -59,6 +59,7 @@ path_list = [ 'api-guide/serializers.md', 'api-guide/fields.md', 'api-guide/relations.md', + 'api-guide/validation.md', 'api-guide/authentication.md', 'api-guide/permissions.md', 'api-guide/throttling.md', diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 6aab020ef..c9f70f2da 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -292,6 +292,8 @@ class Serializer(BaseSerializer): for key, value in self._get_base_fields().items(): self.fields[key] = value + self.validators = getattr(getattr(self, 'Meta', None), 'validators', []) + def _get_base_fields(self): return copy.deepcopy(self._declared_fields) diff --git a/rest_framework/validators.py b/rest_framework/validators.py index e302a0e41..f3773f176 100644 --- a/rest_framework/validators.py +++ b/rest_framework/validators.py @@ -19,9 +19,10 @@ class UniqueValidator: """ message = _('This field must be unique.') - def __init__(self, queryset): + def __init__(self, queryset, message=None): self.queryset = queryset self.serializer_field = None + self.message = message or self.message def set_context(self, serializer_field): # Determine the underlying model field name. This may not be the @@ -54,10 +55,11 @@ class UniqueTogetherValidator: """ message = _('The fields {field_names} must make a unique set.') - def __init__(self, queryset, fields): + def __init__(self, queryset, fields, message=None): self.queryset = queryset self.fields = fields self.serializer_field = None + self.message = message or self.message def set_context(self, serializer): # Determine the existing instance, if this is an update operation. @@ -86,10 +88,11 @@ class UniqueTogetherValidator: class BaseUniqueForValidator: message = None - def __init__(self, queryset, field, date_field): + def __init__(self, queryset, field, date_field, message=None): self.queryset = queryset self.field = field self.date_field = date_field + self.message = message or self.message def set_context(self, serializer): # Determine the underlying model field names. These may not be the From 254701230d85612cf0210d4549c2d74f410a181d Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 31 Oct 2014 13:58:40 +0000 Subject: [PATCH 174/249] Fix up validators docs --- docs/api-guide/validators.md | 2 +- docs/index.md | 2 +- docs/template.html | 2 +- mkdocs.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index 52c9e0822..6a0ef4ff4 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -8,7 +8,7 @@ Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes. -Sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes. +However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes. ## Validation in REST framework diff --git a/docs/index.md b/docs/index.md index cff7b8351..161886a4e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -173,7 +173,7 @@ The API guide is your complete reference manual to all the functionality provide * [Serializers][serializers] * [Serializer fields][fields] * [Serializer relations][relations] -* [Validation][validation] +* [Validators][validators] * [Authentication][authentication] * [Permissions][permissions] * [Throttling][throttling] diff --git a/docs/template.html b/docs/template.html index 0d2fb16eb..f36cffc6d 100644 --- a/docs/template.html +++ b/docs/template.html @@ -95,7 +95,7 @@ a.fusion-poweredby { <li><a href="{{ base_url }}/api-guide/serializers{{ suffix }}">Serializers</a></li> <li><a href="{{ base_url }}/api-guide/fields{{ suffix }}">Serializer fields</a></li> <li><a href="{{ base_url }}/api-guide/relations{{ suffix }}">Serializer relations</a></li> - <li><a href="{{ base_url }}/api-guide/validation{{ suffix }}">Validation</a></li> + <li><a href="{{ base_url }}/api-guide/validators{{ suffix }}">Validators</a></li> <li><a href="{{ base_url }}/api-guide/authentication{{ suffix }}">Authentication</a></li> <li><a href="{{ base_url }}/api-guide/permissions{{ suffix }}">Permissions</a></li> <li><a href="{{ base_url }}/api-guide/throttling{{ suffix }}">Throttling</a></li> diff --git a/mkdocs.py b/mkdocs.py index acd11b633..3787d7920 100755 --- a/mkdocs.py +++ b/mkdocs.py @@ -59,7 +59,7 @@ path_list = [ 'api-guide/serializers.md', 'api-guide/fields.md', 'api-guide/relations.md', - 'api-guide/validation.md', + 'api-guide/validators.md', 'api-guide/authentication.md', 'api-guide/permissions.md', 'api-guide/throttling.md', From 45b5f23f3142c1b63258c8ad092887538eee5517 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 31 Oct 2014 14:56:41 +0000 Subject: [PATCH 175/249] Update to bootstrap 3. Closes #1085 --- .../rest_framework/css/bootstrap.min.css | 844 +----------------- .../static/rest_framework/js/bootstrap.min.js | 13 +- .../templates/rest_framework/base.html | 3 +- 3 files changed, 11 insertions(+), 849 deletions(-) diff --git a/rest_framework/static/rest_framework/css/bootstrap.min.css b/rest_framework/static/rest_framework/css/bootstrap.min.css index 373f4b430..a9f35ceed 100644 --- a/rest_framework/static/rest_framework/css/bootstrap.min.css +++ b/rest_framework/static/rest_framework/css/bootstrap.min.css @@ -1,841 +1,5 @@ /*! - * Bootstrap v2.1.1 - * - * Copyright 2012 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Designed and built with all the love in the world @twitter by @mdo and @fat. - */ -.clearfix{*zoom:1;}.clearfix:before,.clearfix:after{display:table;content:"";line-height:0;} -.clearfix:after{clear:both;} -.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0;} -.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} -article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block;} -audio,canvas,video{display:inline-block;*display:inline;*zoom:1;} -audio:not([controls]){display:none;} -html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;} -a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px;} -a:hover,a:active{outline:0;} -sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline;} -sup{top:-0.5em;} -sub{bottom:-0.25em;} -img{max-width:100%;width:auto\9;height:auto;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic;} -#map_canvas img{max-width:none;} -button,input,select,textarea{margin:0;font-size:100%;vertical-align:middle;} -button,input{*overflow:visible;line-height:normal;} -button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0;} -button,input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button;} -input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield;} -input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none;} -textarea{overflow:auto;vertical-align:top;} -body{margin:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:20px;color:#333333;background-color:#ffffff;} -a{color:#0088cc;text-decoration:none;} -a:hover{color:#005580;text-decoration:underline;} -.img-rounded{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;} -.img-polaroid{padding:4px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.2);-webkit-box-shadow:0 1px 3px rgba(0, 0, 0, 0.1);-moz-box-shadow:0 1px 3px rgba(0, 0, 0, 0.1);box-shadow:0 1px 3px rgba(0, 0, 0, 0.1);} -.img-circle{-webkit-border-radius:500px;-moz-border-radius:500px;border-radius:500px;} -.row{margin-left:-20px;*zoom:1;}.row:before,.row:after{display:table;content:"";line-height:0;} -.row:after{clear:both;} -[class*="span"]{float:left;min-height:1px;margin-left:20px;} -.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px;} -.span12{width:940px;} -.span11{width:860px;} -.span10{width:780px;} -.span9{width:700px;} -.span8{width:620px;} -.span7{width:540px;} -.span6{width:460px;} -.span5{width:380px;} -.span4{width:300px;} -.span3{width:220px;} -.span2{width:140px;} -.span1{width:60px;} -.offset12{margin-left:980px;} -.offset11{margin-left:900px;} -.offset10{margin-left:820px;} -.offset9{margin-left:740px;} -.offset8{margin-left:660px;} -.offset7{margin-left:580px;} -.offset6{margin-left:500px;} -.offset5{margin-left:420px;} -.offset4{margin-left:340px;} -.offset3{margin-left:260px;} -.offset2{margin-left:180px;} -.offset1{margin-left:100px;} -.row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";line-height:0;} -.row-fluid:after{clear:both;} -.row-fluid [class*="span"]{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;float:left;margin-left:2.127659574468085%;*margin-left:2.074468085106383%;} -.row-fluid [class*="span"]:first-child{margin-left:0;} -.row-fluid .span12{width:100%;*width:99.94680851063829%;} -.row-fluid .span11{width:91.48936170212765%;*width:91.43617021276594%;} -.row-fluid .span10{width:82.97872340425532%;*width:82.92553191489361%;} -.row-fluid .span9{width:74.46808510638297%;*width:74.41489361702126%;} -.row-fluid .span8{width:65.95744680851064%;*width:65.90425531914893%;} -.row-fluid .span7{width:57.44680851063829%;*width:57.39361702127659%;} -.row-fluid .span6{width:48.93617021276595%;*width:48.88297872340425%;} -.row-fluid .span5{width:40.42553191489362%;*width:40.37234042553192%;} -.row-fluid .span4{width:31.914893617021278%;*width:31.861702127659576%;} -.row-fluid .span3{width:23.404255319148934%;*width:23.351063829787233%;} -.row-fluid .span2{width:14.893617021276595%;*width:14.840425531914894%;} -.row-fluid .span1{width:6.382978723404255%;*width:6.329787234042553%;} -.row-fluid .offset12{margin-left:104.25531914893617%;*margin-left:104.14893617021275%;} -.row-fluid .offset12:first-child{margin-left:102.12765957446808%;*margin-left:102.02127659574467%;} -.row-fluid .offset11{margin-left:95.74468085106382%;*margin-left:95.6382978723404%;} -.row-fluid .offset11:first-child{margin-left:93.61702127659574%;*margin-left:93.51063829787232%;} -.row-fluid .offset10{margin-left:87.23404255319149%;*margin-left:87.12765957446807%;} -.row-fluid .offset10:first-child{margin-left:85.1063829787234%;*margin-left:84.99999999999999%;} -.row-fluid .offset9{margin-left:78.72340425531914%;*margin-left:78.61702127659572%;} -.row-fluid .offset9:first-child{margin-left:76.59574468085106%;*margin-left:76.48936170212764%;} -.row-fluid .offset8{margin-left:70.2127659574468%;*margin-left:70.10638297872339%;} -.row-fluid .offset8:first-child{margin-left:68.08510638297872%;*margin-left:67.9787234042553%;} -.row-fluid .offset7{margin-left:61.70212765957446%;*margin-left:61.59574468085106%;} -.row-fluid .offset7:first-child{margin-left:59.574468085106375%;*margin-left:59.46808510638297%;} -.row-fluid .offset6{margin-left:53.191489361702125%;*margin-left:53.085106382978715%;} -.row-fluid .offset6:first-child{margin-left:51.063829787234035%;*margin-left:50.95744680851063%;} -.row-fluid .offset5{margin-left:44.68085106382979%;*margin-left:44.57446808510638%;} -.row-fluid .offset5:first-child{margin-left:42.5531914893617%;*margin-left:42.4468085106383%;} -.row-fluid .offset4{margin-left:36.170212765957444%;*margin-left:36.06382978723405%;} -.row-fluid .offset4:first-child{margin-left:34.04255319148936%;*margin-left:33.93617021276596%;} -.row-fluid .offset3{margin-left:27.659574468085104%;*margin-left:27.5531914893617%;} -.row-fluid .offset3:first-child{margin-left:25.53191489361702%;*margin-left:25.425531914893618%;} -.row-fluid .offset2{margin-left:19.148936170212764%;*margin-left:19.04255319148936%;} -.row-fluid .offset2:first-child{margin-left:17.02127659574468%;*margin-left:16.914893617021278%;} -.row-fluid .offset1{margin-left:10.638297872340425%;*margin-left:10.53191489361702%;} -.row-fluid .offset1:first-child{margin-left:8.51063829787234%;*margin-left:8.404255319148938%;} -[class*="span"].hide,.row-fluid [class*="span"].hide{display:none;} -[class*="span"].pull-right,.row-fluid [class*="span"].pull-right{float:right;} -.container{margin-right:auto;margin-left:auto;*zoom:1;}.container:before,.container:after{display:table;content:"";line-height:0;} -.container:after{clear:both;} -.container-fluid{padding-right:20px;padding-left:20px;*zoom:1;}.container-fluid:before,.container-fluid:after{display:table;content:"";line-height:0;} -.container-fluid:after{clear:both;} -p{margin:0 0 10px;} -.lead{margin-bottom:20px;font-size:21px;font-weight:200;line-height:30px;} -small{font-size:85%;} -strong{font-weight:bold;} -em{font-style:italic;} -cite{font-style:normal;} -.muted{color:#999999;} -.text-warning{color:#c09853;} -.text-error{color:#b94a48;} -.text-info{color:#3a87ad;} -.text-success{color:#468847;} -h1,h2,h3,h4,h5,h6{margin:10px 0;font-family:inherit;font-weight:bold;line-height:1;color:inherit;text-rendering:optimizelegibility;}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{font-weight:normal;line-height:1;color:#999999;} -h1{font-size:36px;line-height:40px;} -h2{font-size:30px;line-height:40px;} -h3{font-size:24px;line-height:40px;} -h4{font-size:18px;line-height:20px;} -h5{font-size:14px;line-height:20px;} -h6{font-size:12px;line-height:20px;} -h1 small{font-size:24px;} -h2 small{font-size:18px;} -h3 small{font-size:14px;} -h4 small{font-size:14px;} -.page-header{padding-bottom:9px;margin:20px 0 30px;border-bottom:1px solid #eeeeee;} -ul,ol{padding:0;margin:0 0 10px 25px;} -ul ul,ul ol,ol ol,ol ul{margin-bottom:0;} -li{line-height:20px;} -ul.unstyled,ol.unstyled{margin-left:0;list-style:none;} -dl{margin-bottom:20px;} -dt,dd{line-height:20px;} -dt{font-weight:bold;} -dd{margin-left:10px;} -.dl-horizontal{*zoom:1;}.dl-horizontal:before,.dl-horizontal:after{display:table;content:"";line-height:0;} -.dl-horizontal:after{clear:both;} -.dl-horizontal dt{float:left;width:160px;clear:left;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;} -.dl-horizontal dd{margin-left:180px;} -hr{margin:20px 0;border:0;border-top:1px solid #eeeeee;border-bottom:1px solid #ffffff;} -abbr[title]{cursor:help;border-bottom:1px dotted #999999;} -abbr.initialism{font-size:90%;text-transform:uppercase;} -blockquote{padding:0 0 0 15px;margin:0 0 20px;border-left:5px solid #eeeeee;}blockquote p{margin-bottom:0;font-size:16px;font-weight:300;line-height:25px;} -blockquote small{display:block;line-height:20px;color:#999999;}blockquote small:before{content:'\2014 \00A0';} -blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eeeeee;border-left:0;}blockquote.pull-right p,blockquote.pull-right small{text-align:right;} -blockquote.pull-right small:before{content:'';} -blockquote.pull-right small:after{content:'\00A0 \2014';} -q:before,q:after,blockquote:before,blockquote:after{content:"";} -address{display:block;margin-bottom:20px;font-style:normal;line-height:20px;} -code,pre{padding:0 3px 2px;font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;color:#333333;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} -code{padding:2px 4px;color:#d14;background-color:#f7f7f9;border:1px solid #e1e1e8;} -pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:20px;word-break:break-all;word-wrap:break-word;white-space:pre;white-space:pre-wrap;background-color:#f5f5f5;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}pre.prettyprint{margin-bottom:20px;} -pre code{padding:0;color:inherit;background-color:transparent;border:0;} -.pre-scrollable{max-height:340px;overflow-y:scroll;} -.label,.badge{font-size:11.844px;font-weight:bold;line-height:14px;color:#ffffff;vertical-align:baseline;white-space:nowrap;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#999999;} -.label{padding:1px 4px 2px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} -.badge{padding:1px 9px 2px;-webkit-border-radius:9px;-moz-border-radius:9px;border-radius:9px;} -a.label:hover,a.badge:hover{color:#ffffff;text-decoration:none;cursor:pointer;} -.label-important,.badge-important{background-color:#b94a48;} -.label-important[href],.badge-important[href]{background-color:#953b39;} -.label-warning,.badge-warning{background-color:#f89406;} -.label-warning[href],.badge-warning[href]{background-color:#c67605;} -.label-success,.badge-success{background-color:#468847;} -.label-success[href],.badge-success[href]{background-color:#356635;} -.label-info,.badge-info{background-color:#3a87ad;} -.label-info[href],.badge-info[href]{background-color:#2d6987;} -.label-inverse,.badge-inverse{background-color:#333333;} -.label-inverse[href],.badge-inverse[href]{background-color:#1a1a1a;} -.btn .label,.btn .badge{position:relative;top:-1px;} -.btn-mini .label,.btn-mini .badge{top:0;} -table{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0;} -.table{width:100%;margin-bottom:20px;}.table th,.table td{padding:8px;line-height:20px;text-align:left;vertical-align:top;border-top:1px solid #dddddd;} -.table th{font-weight:bold;} -.table thead th{vertical-align:bottom;} -.table caption+thead tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child th,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child th,.table thead:first-child tr:first-child td{border-top:0;} -.table tbody+tbody{border-top:2px solid #dddddd;} -.table-condensed th,.table-condensed td{padding:4px 5px;} -.table-bordered{border:1px solid #dddddd;border-collapse:separate;*border-collapse:collapse;border-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}.table-bordered th,.table-bordered td{border-left:1px solid #dddddd;} -.table-bordered caption+thead tr:first-child th,.table-bordered caption+tbody tr:first-child th,.table-bordered caption+tbody tr:first-child td,.table-bordered colgroup+thead tr:first-child th,.table-bordered colgroup+tbody tr:first-child th,.table-bordered colgroup+tbody tr:first-child td,.table-bordered thead:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child td{border-top:0;} -.table-bordered thead:first-child tr:first-child th:first-child,.table-bordered tbody:first-child tr:first-child td:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px;} -.table-bordered thead:first-child tr:first-child th:last-child,.table-bordered tbody:first-child tr:first-child td:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px;} -.table-bordered thead:last-child tr:last-child th:first-child,.table-bordered tbody:last-child tr:last-child td:first-child,.table-bordered tfoot:last-child tr:last-child td:first-child{-webkit-border-radius:0 0 0 4px;-moz-border-radius:0 0 0 4px;border-radius:0 0 0 4px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;} -.table-bordered thead:last-child tr:last-child th:last-child,.table-bordered tbody:last-child tr:last-child td:last-child,.table-bordered tfoot:last-child tr:last-child td:last-child{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;} -.table-bordered caption+thead tr:first-child th:first-child,.table-bordered caption+tbody tr:first-child td:first-child,.table-bordered colgroup+thead tr:first-child th:first-child,.table-bordered colgroup+tbody tr:first-child td:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px;} -.table-bordered caption+thead tr:first-child th:last-child,.table-bordered caption+tbody tr:first-child td:last-child,.table-bordered colgroup+thead tr:first-child th:last-child,.table-bordered colgroup+tbody tr:first-child td:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topleft:4px;} -.table-striped tbody tr:nth-child(odd) td,.table-striped tbody tr:nth-child(odd) th{background-color:#f9f9f9;} -.table-hover tbody tr:hover td,.table-hover tbody tr:hover th{background-color:#f5f5f5;} -table [class*=span],.row-fluid table [class*=span]{display:table-cell;float:none;margin-left:0;} -.table .span1{float:none;width:44px;margin-left:0;} -.table .span2{float:none;width:124px;margin-left:0;} -.table .span3{float:none;width:204px;margin-left:0;} -.table .span4{float:none;width:284px;margin-left:0;} -.table .span5{float:none;width:364px;margin-left:0;} -.table .span6{float:none;width:444px;margin-left:0;} -.table .span7{float:none;width:524px;margin-left:0;} -.table .span8{float:none;width:604px;margin-left:0;} -.table .span9{float:none;width:684px;margin-left:0;} -.table .span10{float:none;width:764px;margin-left:0;} -.table .span11{float:none;width:844px;margin-left:0;} -.table .span12{float:none;width:924px;margin-left:0;} -.table .span13{float:none;width:1004px;margin-left:0;} -.table .span14{float:none;width:1084px;margin-left:0;} -.table .span15{float:none;width:1164px;margin-left:0;} -.table .span16{float:none;width:1244px;margin-left:0;} -.table .span17{float:none;width:1324px;margin-left:0;} -.table .span18{float:none;width:1404px;margin-left:0;} -.table .span19{float:none;width:1484px;margin-left:0;} -.table .span20{float:none;width:1564px;margin-left:0;} -.table .span21{float:none;width:1644px;margin-left:0;} -.table .span22{float:none;width:1724px;margin-left:0;} -.table .span23{float:none;width:1804px;margin-left:0;} -.table .span24{float:none;width:1884px;margin-left:0;} -.table tbody tr.success td{background-color:#dff0d8;} -.table tbody tr.error td{background-color:#f2dede;} -.table tbody tr.warning td{background-color:#fcf8e3;} -.table tbody tr.info td{background-color:#d9edf7;} -.table-hover tbody tr.success:hover td{background-color:#d0e9c6;} -.table-hover tbody tr.error:hover td{background-color:#ebcccc;} -.table-hover tbody tr.warning:hover td{background-color:#faf2cc;} -.table-hover tbody tr.info:hover td{background-color:#c4e3f3;} -form{margin:0 0 20px;} -fieldset{padding:0;margin:0;border:0;} -legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333333;border:0;border-bottom:1px solid #e5e5e5;}legend small{font-size:15px;color:#999999;} -label,input,button,select,textarea{font-size:14px;font-weight:normal;line-height:20px;} -input,button,select,textarea{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;} -label{display:block;margin-bottom:5px;} -select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px 6px;margin-bottom:9px;font-size:14px;line-height:20px;color:#555555;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} -input,textarea,.uneditable-input{width:206px;} -textarea{height:auto;} -textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear .2s, box-shadow linear .2s;-moz-transition:border linear .2s, box-shadow linear .2s;-o-transition:border linear .2s, box-shadow linear .2s;transition:border linear .2s, box-shadow linear .2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);} -input[type="radio"],input[type="checkbox"]{margin:4px 0 0;*margin-top:0;margin-top:1px \9;line-height:normal;cursor:pointer;} -input[type="file"],input[type="image"],input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;} -select,input[type="file"]{height:30px;*margin-top:4px;line-height:30px;} -select{width:220px;border:1px solid #cccccc;background-color:#ffffff;} -select[multiple],select[size]{height:auto;} -select:focus,input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px;} -.uneditable-input,.uneditable-textarea{color:#999999;background-color:#fcfcfc;border-color:#cccccc;-webkit-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.025);-moz-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.025);box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.025);cursor:not-allowed;} -.uneditable-input{overflow:hidden;white-space:nowrap;} -.uneditable-textarea{width:auto;height:auto;} -input:-moz-placeholder,textarea:-moz-placeholder{color:#999999;} -input:-ms-input-placeholder,textarea:-ms-input-placeholder{color:#999999;} -input::-webkit-input-placeholder,textarea::-webkit-input-placeholder{color:#999999;} -.radio,.checkbox{min-height:18px;padding-left:18px;} -.radio input[type="radio"],.checkbox input[type="checkbox"]{float:left;margin-left:-18px;} -.controls>.radio:first-child,.controls>.checkbox:first-child{padding-top:5px;} -.radio.inline,.checkbox.inline{display:inline-block;padding-top:5px;margin-bottom:0;vertical-align:middle;} -.radio.inline+.radio.inline,.checkbox.inline+.checkbox.inline{margin-left:10px;} -.input-mini{width:60px;} -.input-small{width:90px;} -.input-medium{width:150px;} -.input-large{width:210px;} -.input-xlarge{width:270px;} -.input-xxlarge{width:530px;} -input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"]{float:none;margin-left:0;} -.input-append input[class*="span"],.input-append .uneditable-input[class*="span"],.input-prepend input[class*="span"],.input-prepend .uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"],.row-fluid .input-prepend [class*="span"],.row-fluid .input-append [class*="span"]{display:inline-block;} -input,textarea,.uneditable-input{margin-left:0;} -.controls-row [class*="span"]+[class*="span"]{margin-left:20px;} -input.span12, textarea.span12, .uneditable-input.span12{width:926px;} -input.span11, textarea.span11, .uneditable-input.span11{width:846px;} -input.span10, textarea.span10, .uneditable-input.span10{width:766px;} -input.span9, textarea.span9, .uneditable-input.span9{width:686px;} -input.span8, textarea.span8, .uneditable-input.span8{width:606px;} -input.span7, textarea.span7, .uneditable-input.span7{width:526px;} -input.span6, textarea.span6, .uneditable-input.span6{width:446px;} -input.span5, textarea.span5, .uneditable-input.span5{width:366px;} -input.span4, textarea.span4, .uneditable-input.span4{width:286px;} -input.span3, textarea.span3, .uneditable-input.span3{width:206px;} -input.span2, textarea.span2, .uneditable-input.span2{width:126px;} -input.span1, textarea.span1, .uneditable-input.span1{width:46px;} -.controls-row{*zoom:1;}.controls-row:before,.controls-row:after{display:table;content:"";line-height:0;} -.controls-row:after{clear:both;} -.controls-row [class*="span"]{float:left;} -input[disabled],select[disabled],textarea[disabled],input[readonly],select[readonly],textarea[readonly]{cursor:not-allowed;background-color:#eeeeee;} -input[type="radio"][disabled],input[type="checkbox"][disabled],input[type="radio"][readonly],input[type="checkbox"][readonly]{background-color:transparent;} -.control-group.warning>label,.control-group.warning .help-block,.control-group.warning .help-inline{color:#c09853;} -.control-group.warning .checkbox,.control-group.warning .radio,.control-group.warning input,.control-group.warning select,.control-group.warning textarea{color:#c09853;} -.control-group.warning input,.control-group.warning select,.control-group.warning textarea{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.warning input:focus,.control-group.warning select:focus,.control-group.warning textarea:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e;} -.control-group.warning .input-prepend .add-on,.control-group.warning .input-append .add-on{color:#c09853;background-color:#fcf8e3;border-color:#c09853;} -.control-group.error>label,.control-group.error .help-block,.control-group.error .help-inline{color:#b94a48;} -.control-group.error .checkbox,.control-group.error .radio,.control-group.error input,.control-group.error select,.control-group.error textarea{color:#b94a48;} -.control-group.error input,.control-group.error select,.control-group.error textarea{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.error input:focus,.control-group.error select:focus,.control-group.error textarea:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392;} -.control-group.error .input-prepend .add-on,.control-group.error .input-append .add-on{color:#b94a48;background-color:#f2dede;border-color:#b94a48;} -.control-group.success>label,.control-group.success .help-block,.control-group.success .help-inline{color:#468847;} -.control-group.success .checkbox,.control-group.success .radio,.control-group.success input,.control-group.success select,.control-group.success textarea{color:#468847;} -.control-group.success input,.control-group.success select,.control-group.success textarea{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.success input:focus,.control-group.success select:focus,.control-group.success textarea:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b;} -.control-group.success .input-prepend .add-on,.control-group.success .input-append .add-on{color:#468847;background-color:#dff0d8;border-color:#468847;} -.control-group.info>label,.control-group.info .help-block,.control-group.info .help-inline{color:#3a87ad;} -.control-group.info .checkbox,.control-group.info .radio,.control-group.info input,.control-group.info select,.control-group.info textarea{color:#3a87ad;} -.control-group.info input,.control-group.info select,.control-group.info textarea{border-color:#3a87ad;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.info input:focus,.control-group.info select:focus,.control-group.info textarea:focus{border-color:#2d6987;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3;} -.control-group.info .input-prepend .add-on,.control-group.info .input-append .add-on{color:#3a87ad;background-color:#d9edf7;border-color:#3a87ad;} -input:focus:required:invalid,textarea:focus:required:invalid,select:focus:required:invalid{color:#b94a48;border-color:#ee5f5b;}input:focus:required:invalid:focus,textarea:focus:required:invalid:focus,select:focus:required:invalid:focus{border-color:#e9322d;-webkit-box-shadow:0 0 6px #f8b9b7;-moz-box-shadow:0 0 6px #f8b9b7;box-shadow:0 0 6px #f8b9b7;} -.form-actions{padding:19px 20px 20px;margin-top:20px;margin-bottom:20px;background-color:#f5f5f5;border-top:1px solid #e5e5e5;*zoom:1;}.form-actions:before,.form-actions:after{display:table;content:"";line-height:0;} -.form-actions:after{clear:both;} -.help-block,.help-inline{color:#595959;} -.help-block{display:block;margin-bottom:10px;} -.help-inline{display:inline-block;*display:inline;*zoom:1;vertical-align:middle;padding-left:5px;} -.input-append,.input-prepend{margin-bottom:5px;font-size:0;white-space:nowrap;}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input{position:relative;margin-bottom:0;*margin-left:0;font-size:14px;vertical-align:top;-webkit-border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;border-radius:0 3px 3px 0;}.input-append input:focus,.input-prepend input:focus,.input-append select:focus,.input-prepend select:focus,.input-append .uneditable-input:focus,.input-prepend .uneditable-input:focus{z-index:2;} -.input-append .add-on,.input-prepend .add-on{display:inline-block;width:auto;height:20px;min-width:16px;padding:4px 5px;font-size:14px;font-weight:normal;line-height:20px;text-align:center;text-shadow:0 1px 0 #ffffff;background-color:#eeeeee;border:1px solid #ccc;} -.input-append .add-on,.input-prepend .add-on,.input-append .btn,.input-prepend .btn{vertical-align:top;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.input-append .active,.input-prepend .active{background-color:#a9dba9;border-color:#46a546;} -.input-prepend .add-on,.input-prepend .btn{margin-right:-1px;} -.input-prepend .add-on:first-child,.input-prepend .btn:first-child{-webkit-border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;border-radius:3px 0 0 3px;} -.input-append input,.input-append select,.input-append .uneditable-input{-webkit-border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;border-radius:3px 0 0 3px;} -.input-append .add-on,.input-append .btn{margin-left:-1px;} -.input-append .add-on:last-child,.input-append .btn:last-child{-webkit-border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;border-radius:0 3px 3px 0;} -.input-prepend.input-append input,.input-prepend.input-append select,.input-prepend.input-append .uneditable-input{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.input-prepend.input-append .add-on:first-child,.input-prepend.input-append .btn:first-child{margin-right:-1px;-webkit-border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;border-radius:3px 0 0 3px;} -.input-prepend.input-append .add-on:last-child,.input-prepend.input-append .btn:last-child{margin-left:-1px;-webkit-border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;border-radius:0 3px 3px 0;} -input.search-query{padding-right:14px;padding-right:4px \9;padding-left:14px;padding-left:4px \9;margin-bottom:0;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px;} -.form-search .input-append .search-query,.form-search .input-prepend .search-query{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.form-search .input-append .search-query{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px;} -.form-search .input-append .btn{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0;} -.form-search .input-prepend .search-query{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0;} -.form-search .input-prepend .btn{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px;} -.form-search input,.form-inline input,.form-horizontal input,.form-search textarea,.form-inline textarea,.form-horizontal textarea,.form-search select,.form-inline select,.form-horizontal select,.form-search .help-inline,.form-inline .help-inline,.form-horizontal .help-inline,.form-search .uneditable-input,.form-inline .uneditable-input,.form-horizontal .uneditable-input,.form-search .input-prepend,.form-inline .input-prepend,.form-horizontal .input-prepend,.form-search .input-append,.form-inline .input-append,.form-horizontal .input-append{display:inline-block;*display:inline;*zoom:1;margin-bottom:0;vertical-align:middle;} -.form-search .hide,.form-inline .hide,.form-horizontal .hide{display:none;} -.form-search label,.form-inline label,.form-search .btn-group,.form-inline .btn-group{display:inline-block;} -.form-search .input-append,.form-inline .input-append,.form-search .input-prepend,.form-inline .input-prepend{margin-bottom:0;} -.form-search .radio,.form-search .checkbox,.form-inline .radio,.form-inline .checkbox{padding-left:0;margin-bottom:0;vertical-align:middle;} -.form-search .radio input[type="radio"],.form-search .checkbox input[type="checkbox"],.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:left;margin-right:3px;margin-left:0;} -.control-group{margin-bottom:10px;} -legend+.control-group{margin-top:20px;-webkit-margin-top-collapse:separate;} -.form-horizontal .control-group{margin-bottom:20px;*zoom:1;}.form-horizontal .control-group:before,.form-horizontal .control-group:after{display:table;content:"";line-height:0;} -.form-horizontal .control-group:after{clear:both;} -.form-horizontal .control-label{float:left;width:160px;padding-top:5px;text-align:right;} -.form-horizontal .controls{*display:inline-block;*padding-left:20px;margin-left:180px;*margin-left:0;}.form-horizontal .controls:first-child{*padding-left:180px;} -.form-horizontal .help-block{margin-bottom:0;} -.form-horizontal input+.help-block,.form-horizontal select+.help-block,.form-horizontal textarea+.help-block{margin-top:10px;} -.form-horizontal .form-actions{padding-left:180px;} -.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 14px;margin-bottom:0;font-size:14px;line-height:20px;*line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333333;text-shadow:0 1px 1px rgba(255, 255, 255, 0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top, #ffffff, #e6e6e6);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6));background-image:-webkit-linear-gradient(top, #ffffff, #e6e6e6);background-image:-o-linear-gradient(top, #ffffff, #e6e6e6);background-image:linear-gradient(to bottom, #ffffff, #e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #bbbbbb;*border:0;border-bottom-color:#a2a2a2;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);-moz-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);}.btn:hover,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333333;background-color:#e6e6e6;*background-color:#d9d9d9;} -.btn:active,.btn.active{background-color:#cccccc \9;} -.btn:first-child{*margin-left:0;} -.btn:hover{color:#333333;text-decoration:none;background-color:#e6e6e6;*background-color:#d9d9d9;background-position:0 -15px;-webkit-transition:background-position 0.1s linear;-moz-transition:background-position 0.1s linear;-o-transition:background-position 0.1s linear;transition:background-position 0.1s linear;} -.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px;} -.btn.active,.btn:active{background-color:#e6e6e6;background-color:#d9d9d9 \9;background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);-moz-box-shadow:inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);box-shadow:inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);} -.btn.disabled,.btn[disabled]{cursor:default;background-color:#e6e6e6;background-image:none;opacity:0.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;} -.btn-large{padding:9px 14px;font-size:16px;line-height:normal;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;} -.btn-large [class^="icon-"]{margin-top:2px;} -.btn-small{padding:3px 9px;font-size:12px;line-height:18px;} -.btn-small [class^="icon-"]{margin-top:0;} -.btn-mini{padding:2px 6px;font-size:11px;line-height:17px;} -.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} -.btn-block+.btn-block{margin-top:5px;} -input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%;} -.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255, 255, 255, 0.75);} -.btn{border-color:#c5c5c5;border-color:rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.25);} -.btn-primary{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top, #0088cc, #0044cc);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc));background-image:-webkit-linear-gradient(top, #0088cc, #0044cc);background-image:-o-linear-gradient(top, #0088cc, #0044cc);background-image:linear-gradient(to bottom, #0088cc, #0044cc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#0044cc #0044cc #002a80;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#0044cc;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-primary:hover,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#ffffff;background-color:#0044cc;*background-color:#003bb3;} -.btn-primary:active,.btn-primary.active{background-color:#003399 \9;} -.btn-warning{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-warning:hover,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#ffffff;background-color:#f89406;*background-color:#df8505;} -.btn-warning:active,.btn-warning.active{background-color:#c67605 \9;} -.btn-danger{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#da4f49;background-image:-moz-linear-gradient(top, #ee5f5b, #bd362f);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f));background-image:-webkit-linear-gradient(top, #ee5f5b, #bd362f);background-image:-o-linear-gradient(top, #ee5f5b, #bd362f);background-image:linear-gradient(to bottom, #ee5f5b, #bd362f);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffbd362f', GradientType=0);border-color:#bd362f #bd362f #802420;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#bd362f;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-danger:hover,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#ffffff;background-color:#bd362f;*background-color:#a9302a;} -.btn-danger:active,.btn-danger.active{background-color:#942a25 \9;} -.btn-success{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#5bb75b;background-image:-moz-linear-gradient(top, #62c462, #51a351);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351));background-image:-webkit-linear-gradient(top, #62c462, #51a351);background-image:-o-linear-gradient(top, #62c462, #51a351);background-image:linear-gradient(to bottom, #62c462, #51a351);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff51a351', GradientType=0);border-color:#51a351 #51a351 #387038;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#51a351;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-success:hover,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#ffffff;background-color:#51a351;*background-color:#499249;} -.btn-success:active,.btn-success.active{background-color:#408140 \9;} -.btn-info{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#49afcd;background-image:-moz-linear-gradient(top, #5bc0de, #2f96b4);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4));background-image:-webkit-linear-gradient(top, #5bc0de, #2f96b4);background-image:-o-linear-gradient(top, #5bc0de, #2f96b4);background-image:linear-gradient(to bottom, #5bc0de, #2f96b4);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0);border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#2f96b4;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-info:hover,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#ffffff;background-color:#2f96b4;*background-color:#2a85a0;} -.btn-info:active,.btn-info.active{background-color:#24748c \9;} -.btn-inverse{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#363636;background-image:-moz-linear-gradient(top, #444444, #222222);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#444444), to(#222222));background-image:-webkit-linear-gradient(top, #444444, #222222);background-image:-o-linear-gradient(top, #444444, #222222);background-image:linear-gradient(to bottom, #444444, #222222);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444', endColorstr='#ff222222', GradientType=0);border-color:#222222 #222222 #000000;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#222222;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-inverse:hover,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#ffffff;background-color:#222222;*background-color:#151515;} -.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9;} -button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px;}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0;} -button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px;} -button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px;} -button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px;} -.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;} -.btn-link{border-color:transparent;cursor:pointer;color:#0088cc;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.btn-link:hover{color:#005580;text-decoration:underline;background-color:transparent;} -.btn-link[disabled]:hover{color:#333333;text-decoration:none;} -[class^="icon-"],[class*=" icon-"]{display:inline-block;width:14px;height:14px;*margin-right:.3em;line-height:14px;vertical-align:text-top;background-image:url("../img/glyphicons-halflings.png");background-position:14px 14px;background-repeat:no-repeat;margin-top:1px;} -.icon-white,.nav-tabs>.active>a>[class^="icon-"],.nav-tabs>.active>a>[class*=" icon-"],.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"]{background-image:url("../img/glyphicons-halflings-white.png");} -.icon-glass{background-position:0 0;} -.icon-music{background-position:-24px 0;} -.icon-search{background-position:-48px 0;} -.icon-envelope{background-position:-72px 0;} -.icon-heart{background-position:-96px 0;} -.icon-star{background-position:-120px 0;} -.icon-star-empty{background-position:-144px 0;} -.icon-user{background-position:-168px 0;} -.icon-film{background-position:-192px 0;} -.icon-th-large{background-position:-216px 0;} -.icon-th{background-position:-240px 0;} -.icon-th-list{background-position:-264px 0;} -.icon-ok{background-position:-288px 0;} -.icon-remove{background-position:-312px 0;} -.icon-zoom-in{background-position:-336px 0;} -.icon-zoom-out{background-position:-360px 0;} -.icon-off{background-position:-384px 0;} -.icon-signal{background-position:-408px 0;} -.icon-cog{background-position:-432px 0;} -.icon-trash{background-position:-456px 0;} -.icon-home{background-position:0 -24px;} -.icon-file{background-position:-24px -24px;} -.icon-time{background-position:-48px -24px;} -.icon-road{background-position:-72px -24px;} -.icon-download-alt{background-position:-96px -24px;} -.icon-download{background-position:-120px -24px;} -.icon-upload{background-position:-144px -24px;} -.icon-inbox{background-position:-168px -24px;} -.icon-play-circle{background-position:-192px -24px;} -.icon-repeat{background-position:-216px -24px;} -.icon-refresh{background-position:-240px -24px;} -.icon-list-alt{background-position:-264px -24px;} -.icon-lock{background-position:-287px -24px;} -.icon-flag{background-position:-312px -24px;} -.icon-headphones{background-position:-336px -24px;} -.icon-volume-off{background-position:-360px -24px;} -.icon-volume-down{background-position:-384px -24px;} -.icon-volume-up{background-position:-408px -24px;} -.icon-qrcode{background-position:-432px -24px;} -.icon-barcode{background-position:-456px -24px;} -.icon-tag{background-position:0 -48px;} -.icon-tags{background-position:-25px -48px;} -.icon-book{background-position:-48px -48px;} -.icon-bookmark{background-position:-72px -48px;} -.icon-print{background-position:-96px -48px;} -.icon-camera{background-position:-120px -48px;} -.icon-font{background-position:-144px -48px;} -.icon-bold{background-position:-167px -48px;} -.icon-italic{background-position:-192px -48px;} -.icon-text-height{background-position:-216px -48px;} -.icon-text-width{background-position:-240px -48px;} -.icon-align-left{background-position:-264px -48px;} -.icon-align-center{background-position:-288px -48px;} -.icon-align-right{background-position:-312px -48px;} -.icon-align-justify{background-position:-336px -48px;} -.icon-list{background-position:-360px -48px;} -.icon-indent-left{background-position:-384px -48px;} -.icon-indent-right{background-position:-408px -48px;} -.icon-facetime-video{background-position:-432px -48px;} -.icon-picture{background-position:-456px -48px;} -.icon-pencil{background-position:0 -72px;} -.icon-map-marker{background-position:-24px -72px;} -.icon-adjust{background-position:-48px -72px;} -.icon-tint{background-position:-72px -72px;} -.icon-edit{background-position:-96px -72px;} -.icon-share{background-position:-120px -72px;} -.icon-check{background-position:-144px -72px;} -.icon-move{background-position:-168px -72px;} -.icon-step-backward{background-position:-192px -72px;} -.icon-fast-backward{background-position:-216px -72px;} -.icon-backward{background-position:-240px -72px;} -.icon-play{background-position:-264px -72px;} -.icon-pause{background-position:-288px -72px;} -.icon-stop{background-position:-312px -72px;} -.icon-forward{background-position:-336px -72px;} -.icon-fast-forward{background-position:-360px -72px;} -.icon-step-forward{background-position:-384px -72px;} -.icon-eject{background-position:-408px -72px;} -.icon-chevron-left{background-position:-432px -72px;} -.icon-chevron-right{background-position:-456px -72px;} -.icon-plus-sign{background-position:0 -96px;} -.icon-minus-sign{background-position:-24px -96px;} -.icon-remove-sign{background-position:-48px -96px;} -.icon-ok-sign{background-position:-72px -96px;} -.icon-question-sign{background-position:-96px -96px;} -.icon-info-sign{background-position:-120px -96px;} -.icon-screenshot{background-position:-144px -96px;} -.icon-remove-circle{background-position:-168px -96px;} -.icon-ok-circle{background-position:-192px -96px;} -.icon-ban-circle{background-position:-216px -96px;} -.icon-arrow-left{background-position:-240px -96px;} -.icon-arrow-right{background-position:-264px -96px;} -.icon-arrow-up{background-position:-289px -96px;} -.icon-arrow-down{background-position:-312px -96px;} -.icon-share-alt{background-position:-336px -96px;} -.icon-resize-full{background-position:-360px -96px;} -.icon-resize-small{background-position:-384px -96px;} -.icon-plus{background-position:-408px -96px;} -.icon-minus{background-position:-433px -96px;} -.icon-asterisk{background-position:-456px -96px;} -.icon-exclamation-sign{background-position:0 -120px;} -.icon-gift{background-position:-24px -120px;} -.icon-leaf{background-position:-48px -120px;} -.icon-fire{background-position:-72px -120px;} -.icon-eye-open{background-position:-96px -120px;} -.icon-eye-close{background-position:-120px -120px;} -.icon-warning-sign{background-position:-144px -120px;} -.icon-plane{background-position:-168px -120px;} -.icon-calendar{background-position:-192px -120px;} -.icon-random{background-position:-216px -120px;width:16px;} -.icon-comment{background-position:-240px -120px;} -.icon-magnet{background-position:-264px -120px;} -.icon-chevron-up{background-position:-288px -120px;} -.icon-chevron-down{background-position:-313px -119px;} -.icon-retweet{background-position:-336px -120px;} -.icon-shopping-cart{background-position:-360px -120px;} -.icon-folder-close{background-position:-384px -120px;} -.icon-folder-open{background-position:-408px -120px;width:16px;} -.icon-resize-vertical{background-position:-432px -119px;} -.icon-resize-horizontal{background-position:-456px -118px;} -.icon-hdd{background-position:0 -144px;} -.icon-bullhorn{background-position:-24px -144px;} -.icon-bell{background-position:-48px -144px;} -.icon-certificate{background-position:-72px -144px;} -.icon-thumbs-up{background-position:-96px -144px;} -.icon-thumbs-down{background-position:-120px -144px;} -.icon-hand-right{background-position:-144px -144px;} -.icon-hand-left{background-position:-168px -144px;} -.icon-hand-up{background-position:-192px -144px;} -.icon-hand-down{background-position:-216px -144px;} -.icon-circle-arrow-right{background-position:-240px -144px;} -.icon-circle-arrow-left{background-position:-264px -144px;} -.icon-circle-arrow-up{background-position:-288px -144px;} -.icon-circle-arrow-down{background-position:-312px -144px;} -.icon-globe{background-position:-336px -144px;} -.icon-wrench{background-position:-360px -144px;} -.icon-tasks{background-position:-384px -144px;} -.icon-filter{background-position:-408px -144px;} -.icon-briefcase{background-position:-432px -144px;} -.icon-fullscreen{background-position:-456px -144px;} -.btn-group{position:relative;font-size:0;vertical-align:middle;white-space:nowrap;*margin-left:.3em;}.btn-group:first-child{*margin-left:0;} -.btn-group+.btn-group{margin-left:5px;} -.btn-toolbar{font-size:0;margin-top:10px;margin-bottom:10px;}.btn-toolbar .btn-group{display:inline-block;*display:inline;*zoom:1;} -.btn-toolbar .btn+.btn,.btn-toolbar .btn-group+.btn,.btn-toolbar .btn+.btn-group{margin-left:5px;} -.btn-group>.btn{position:relative;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.btn-group>.btn+.btn{margin-left:-1px;} -.btn-group>.btn,.btn-group>.dropdown-menu{font-size:14px;} -.btn-group>.btn-mini{font-size:11px;} -.btn-group>.btn-small{font-size:12px;} -.btn-group>.btn-large{font-size:16px;} -.btn-group>.btn:first-child{margin-left:0;-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px;} -.btn-group>.btn:last-child,.btn-group>.dropdown-toggle{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;} -.btn-group>.btn.large:first-child{margin-left:0;-webkit-border-top-left-radius:6px;-moz-border-radius-topleft:6px;border-top-left-radius:6px;-webkit-border-bottom-left-radius:6px;-moz-border-radius-bottomleft:6px;border-bottom-left-radius:6px;} -.btn-group>.btn.large:last-child,.btn-group>.large.dropdown-toggle{-webkit-border-top-right-radius:6px;-moz-border-radius-topright:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;-moz-border-radius-bottomright:6px;border-bottom-right-radius:6px;} -.btn-group>.btn:hover,.btn-group>.btn:focus,.btn-group>.btn:active,.btn-group>.btn.active{z-index:2;} -.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0;} -.btn-group>.btn+.dropdown-toggle{padding-left:8px;padding-right:8px;-webkit-box-shadow:inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);-moz-box-shadow:inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);box-shadow:inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);*padding-top:5px;*padding-bottom:5px;} -.btn-group>.btn-mini+.dropdown-toggle{padding-left:5px;padding-right:5px;*padding-top:2px;*padding-bottom:2px;} -.btn-group>.btn-small+.dropdown-toggle{*padding-top:5px;*padding-bottom:4px;} -.btn-group>.btn-large+.dropdown-toggle{padding-left:12px;padding-right:12px;*padding-top:7px;*padding-bottom:7px;} -.btn-group.open .dropdown-toggle{background-image:none;-webkit-box-shadow:inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);-moz-box-shadow:inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);box-shadow:inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);} -.btn-group.open .btn.dropdown-toggle{background-color:#e6e6e6;} -.btn-group.open .btn-primary.dropdown-toggle{background-color:#0044cc;} -.btn-group.open .btn-warning.dropdown-toggle{background-color:#f89406;} -.btn-group.open .btn-danger.dropdown-toggle{background-color:#bd362f;} -.btn-group.open .btn-success.dropdown-toggle{background-color:#51a351;} -.btn-group.open .btn-info.dropdown-toggle{background-color:#2f96b4;} -.btn-group.open .btn-inverse.dropdown-toggle{background-color:#222222;} -.btn .caret{margin-top:8px;margin-left:0;} -.btn-mini .caret,.btn-small .caret,.btn-large .caret{margin-top:6px;} -.btn-large .caret{border-left-width:5px;border-right-width:5px;border-top-width:5px;} -.dropup .btn-large .caret{border-bottom:5px solid #000000;border-top:0;} -.btn-primary .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret,.btn-success .caret,.btn-inverse .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;} -.btn-group-vertical{display:inline-block;*display:inline;*zoom:1;} -.btn-group-vertical .btn{display:block;float:none;width:100%;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.btn-group-vertical .btn+.btn{margin-left:0;margin-top:-1px;} -.btn-group-vertical .btn:first-child{-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0;} -.btn-group-vertical .btn:last-child{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px;} -.btn-group-vertical .btn-large:first-child{-webkit-border-radius:6px 6px 0 0;-moz-border-radius:6px 6px 0 0;border-radius:6px 6px 0 0;} -.btn-group-vertical .btn-large:last-child{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;} -.nav{margin-left:0;margin-bottom:20px;list-style:none;} -.nav>li>a{display:block;} -.nav>li>a:hover{text-decoration:none;background-color:#eeeeee;} -.nav>.pull-right{float:right;} -.nav-header{display:block;padding:3px 15px;font-size:11px;font-weight:bold;line-height:20px;color:#999999;text-shadow:0 1px 0 rgba(255, 255, 255, 0.5);text-transform:uppercase;} -.nav li+.nav-header{margin-top:9px;} -.nav-list{padding-left:15px;padding-right:15px;margin-bottom:0;} -.nav-list>li>a,.nav-list .nav-header{margin-left:-15px;margin-right:-15px;text-shadow:0 1px 0 rgba(255, 255, 255, 0.5);} -.nav-list>li>a{padding:3px 15px;} -.nav-list>.active>a,.nav-list>.active>a:hover{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.2);background-color:#0088cc;} -.nav-list [class^="icon-"]{margin-right:2px;} -.nav-list .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #ffffff;} -.nav-tabs,.nav-pills{*zoom:1;}.nav-tabs:before,.nav-pills:before,.nav-tabs:after,.nav-pills:after{display:table;content:"";line-height:0;} -.nav-tabs:after,.nav-pills:after{clear:both;} -.nav-tabs>li,.nav-pills>li{float:left;} -.nav-tabs>li>a,.nav-pills>li>a{padding-right:12px;padding-left:12px;margin-right:2px;line-height:14px;} -.nav-tabs{border-bottom:1px solid #ddd;} -.nav-tabs>li{margin-bottom:-1px;} -.nav-tabs>li>a{padding-top:8px;padding-bottom:8px;line-height:20px;border:1px solid transparent;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0;}.nav-tabs>li>a:hover{border-color:#eeeeee #eeeeee #dddddd;} -.nav-tabs>.active>a,.nav-tabs>.active>a:hover{color:#555555;background-color:#ffffff;border:1px solid #ddd;border-bottom-color:transparent;cursor:default;} -.nav-pills>li>a{padding-top:8px;padding-bottom:8px;margin-top:2px;margin-bottom:2px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;} -.nav-pills>.active>a,.nav-pills>.active>a:hover{color:#ffffff;background-color:#0088cc;} -.nav-stacked>li{float:none;} -.nav-stacked>li>a{margin-right:0;} -.nav-tabs.nav-stacked{border-bottom:0;} -.nav-tabs.nav-stacked>li>a{border:1px solid #ddd;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.nav-tabs.nav-stacked>li:first-child>a{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;} -.nav-tabs.nav-stacked>li:last-child>a{-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px;} -.nav-tabs.nav-stacked>li>a:hover{border-color:#ddd;z-index:2;} -.nav-pills.nav-stacked>li>a{margin-bottom:3px;} -.nav-pills.nav-stacked>li:last-child>a{margin-bottom:1px;} -.nav-tabs .dropdown-menu{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;} -.nav-pills .dropdown-menu{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;} -.nav .dropdown-toggle .caret{border-top-color:#0088cc;border-bottom-color:#0088cc;margin-top:6px;} -.nav .dropdown-toggle:hover .caret{border-top-color:#005580;border-bottom-color:#005580;} -.nav-tabs .dropdown-toggle .caret{margin-top:8px;} -.nav .active .dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff;} -.nav-tabs .active .dropdown-toggle .caret{border-top-color:#555555;border-bottom-color:#555555;} -.nav>.dropdown.active>a:hover{cursor:pointer;} -.nav-tabs .open .dropdown-toggle,.nav-pills .open .dropdown-toggle,.nav>li.dropdown.open.active>a:hover{color:#ffffff;background-color:#999999;border-color:#999999;} -.nav li.dropdown.open .caret,.nav li.dropdown.open.active .caret,.nav li.dropdown.open a:hover .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;opacity:1;filter:alpha(opacity=100);} -.tabs-stacked .open>a:hover{border-color:#999999;} -.tabbable{*zoom:1;}.tabbable:before,.tabbable:after{display:table;content:"";line-height:0;} -.tabbable:after{clear:both;} -.tab-content{overflow:auto;} -.tabs-below>.nav-tabs,.tabs-right>.nav-tabs,.tabs-left>.nav-tabs{border-bottom:0;} -.tab-content>.tab-pane,.pill-content>.pill-pane{display:none;} -.tab-content>.active,.pill-content>.active{display:block;} -.tabs-below>.nav-tabs{border-top:1px solid #ddd;} -.tabs-below>.nav-tabs>li{margin-top:-1px;margin-bottom:0;} -.tabs-below>.nav-tabs>li>a{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px;}.tabs-below>.nav-tabs>li>a:hover{border-bottom-color:transparent;border-top-color:#ddd;} -.tabs-below>.nav-tabs>.active>a,.tabs-below>.nav-tabs>.active>a:hover{border-color:transparent #ddd #ddd #ddd;} -.tabs-left>.nav-tabs>li,.tabs-right>.nav-tabs>li{float:none;} -.tabs-left>.nav-tabs>li>a,.tabs-right>.nav-tabs>li>a{min-width:74px;margin-right:0;margin-bottom:3px;} -.tabs-left>.nav-tabs{float:left;margin-right:19px;border-right:1px solid #ddd;} -.tabs-left>.nav-tabs>li>a{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px;} -.tabs-left>.nav-tabs>li>a:hover{border-color:#eeeeee #dddddd #eeeeee #eeeeee;} -.tabs-left>.nav-tabs .active>a,.tabs-left>.nav-tabs .active>a:hover{border-color:#ddd transparent #ddd #ddd;*border-right-color:#ffffff;} -.tabs-right>.nav-tabs{float:right;margin-left:19px;border-left:1px solid #ddd;} -.tabs-right>.nav-tabs>li>a{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;} -.tabs-right>.nav-tabs>li>a:hover{border-color:#eeeeee #eeeeee #eeeeee #dddddd;} -.tabs-right>.nav-tabs .active>a,.tabs-right>.nav-tabs .active>a:hover{border-color:#ddd #ddd #ddd transparent;*border-left-color:#ffffff;} -.nav>.disabled>a{color:#999999;} -.nav>.disabled>a:hover{text-decoration:none;background-color:transparent;cursor:default;} -.navbar{overflow:visible;margin-bottom:20px;color:#777777;*position:relative;*z-index:2;} -.navbar-inner{min-height:40px;padding-left:20px;padding-right:20px;background-color:#fafafa;background-image:-moz-linear-gradient(top, #ffffff, #f2f2f2);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f2f2f2));background-image:-webkit-linear-gradient(top, #ffffff, #f2f2f2);background-image:-o-linear-gradient(top, #ffffff, #f2f2f2);background-image:linear-gradient(to bottom, #ffffff, #f2f2f2);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff2f2f2', GradientType=0);border:1px solid #d4d4d4;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.065);-moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.065);box-shadow:0 1px 4px rgba(0, 0, 0, 0.065);*zoom:1;}.navbar-inner:before,.navbar-inner:after{display:table;content:"";line-height:0;} -.navbar-inner:after{clear:both;} -.navbar .container{width:auto;} -.nav-collapse.collapse{height:auto;} -.navbar .brand{float:left;display:block;padding:10px 20px 10px;margin-left:-20px;font-size:20px;font-weight:200;color:#777777;text-shadow:0 1px 0 #ffffff;}.navbar .brand:hover{text-decoration:none;} -.navbar-text{margin-bottom:0;line-height:40px;} -.navbar-link{color:#777777;}.navbar-link:hover{color:#333333;} -.navbar .divider-vertical{height:40px;margin:0 9px;border-left:1px solid #f2f2f2;border-right:1px solid #ffffff;} -.navbar .btn,.navbar .btn-group{margin-top:5px;} -.navbar .btn-group .btn,.navbar .input-prepend .btn,.navbar .input-append .btn{margin-top:0;} -.navbar-form{margin-bottom:0;*zoom:1;}.navbar-form:before,.navbar-form:after{display:table;content:"";line-height:0;} -.navbar-form:after{clear:both;} -.navbar-form input,.navbar-form select,.navbar-form .radio,.navbar-form .checkbox{margin-top:5px;} -.navbar-form input,.navbar-form select,.navbar-form .btn{display:inline-block;margin-bottom:0;} -.navbar-form input[type="image"],.navbar-form input[type="checkbox"],.navbar-form input[type="radio"]{margin-top:3px;} -.navbar-form .input-append,.navbar-form .input-prepend{margin-top:6px;white-space:nowrap;}.navbar-form .input-append input,.navbar-form .input-prepend input{margin-top:0;} -.navbar-search{position:relative;float:left;margin-top:5px;margin-bottom:0;}.navbar-search .search-query{margin-bottom:0;padding:4px 14px;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;font-weight:normal;line-height:1;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px;} -.navbar-static-top{position:static;width:100%;margin-bottom:0;}.navbar-static-top .navbar-inner{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;margin-bottom:0;} -.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{border-width:0 0 1px;} -.navbar-fixed-bottom .navbar-inner{border-width:1px 0 0;} -.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding-left:0;padding-right:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px;} -.navbar-fixed-top{top:0;} -.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{-webkit-box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.1), 0 1px 10px rgba(0, 0, 0, 0.1);-moz-box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.1), 0 1px 10px rgba(0, 0, 0, 0.1);box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.1), 0 1px 10px rgba(0, 0, 0, 0.1);} -.navbar-fixed-bottom{bottom:0;}.navbar-fixed-bottom .navbar-inner{-webkit-box-shadow:inset 0 1px 0 rgba(0, 0, 0, 0.1), 0 -1px 10px rgba(0, 0, 0, 0.1);-moz-box-shadow:inset 0 1px 0 rgba(0, 0, 0, 0.1), 0 -1px 10px rgba(0, 0, 0, 0.1);box-shadow:inset 0 1px 0 rgba(0, 0, 0, 0.1), 0 -1px 10px rgba(0, 0, 0, 0.1);} -.navbar .nav{position:relative;left:0;display:block;float:left;margin:0 10px 0 0;} -.navbar .nav.pull-right{float:right;margin-right:0;} -.navbar .nav>li{float:left;} -.navbar .nav>li>a{float:none;padding:10px 15px 10px;color:#777777;text-decoration:none;text-shadow:0 1px 0 #ffffff;} -.navbar .nav .dropdown-toggle .caret{margin-top:8px;} -.navbar .nav>li>a:focus,.navbar .nav>li>a:hover{background-color:transparent;color:#333333;text-decoration:none;} -.navbar .nav>.active>a,.navbar .nav>.active>a:hover,.navbar .nav>.active>a:focus{color:#555555;text-decoration:none;background-color:#e5e5e5;-webkit-box-shadow:inset 0 3px 8px rgba(0, 0, 0, 0.125);-moz-box-shadow:inset 0 3px 8px rgba(0, 0, 0, 0.125);box-shadow:inset 0 3px 8px rgba(0, 0, 0, 0.125);} -.navbar .btn-navbar{display:none;float:right;padding:7px 10px;margin-left:5px;margin-right:5px;color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#ededed;background-image:-moz-linear-gradient(top, #f2f2f2, #e5e5e5);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#f2f2f2), to(#e5e5e5));background-image:-webkit-linear-gradient(top, #f2f2f2, #e5e5e5);background-image:-o-linear-gradient(top, #f2f2f2, #e5e5e5);background-image:linear-gradient(to bottom, #f2f2f2, #e5e5e5);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2', endColorstr='#ffe5e5e5', GradientType=0);border-color:#e5e5e5 #e5e5e5 #bfbfbf;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#e5e5e5;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);-webkit-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075);-moz-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075);box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075);}.navbar .btn-navbar:hover,.navbar .btn-navbar:active,.navbar .btn-navbar.active,.navbar .btn-navbar.disabled,.navbar .btn-navbar[disabled]{color:#ffffff;background-color:#e5e5e5;*background-color:#d9d9d9;} -.navbar .btn-navbar:active,.navbar .btn-navbar.active{background-color:#cccccc \9;} -.navbar .btn-navbar .icon-bar{display:block;width:18px;height:2px;background-color:#f5f5f5;-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px;-webkit-box-shadow:0 1px 0 rgba(0, 0, 0, 0.25);-moz-box-shadow:0 1px 0 rgba(0, 0, 0, 0.25);box-shadow:0 1px 0 rgba(0, 0, 0, 0.25);} -.btn-navbar .icon-bar+.icon-bar{margin-top:3px;} -.navbar .nav>li>.dropdown-menu:before{content:'';display:inline-block;border-left:7px solid transparent;border-right:7px solid transparent;border-bottom:7px solid #ccc;border-bottom-color:rgba(0, 0, 0, 0.2);position:absolute;top:-7px;left:9px;} -.navbar .nav>li>.dropdown-menu:after{content:'';display:inline-block;border-left:6px solid transparent;border-right:6px solid transparent;border-bottom:6px solid #ffffff;position:absolute;top:-6px;left:10px;} -.navbar-fixed-bottom .nav>li>.dropdown-menu:before{border-top:7px solid #ccc;border-top-color:rgba(0, 0, 0, 0.2);border-bottom:0;bottom:-7px;top:auto;} -.navbar-fixed-bottom .nav>li>.dropdown-menu:after{border-top:6px solid #ffffff;border-bottom:0;bottom:-6px;top:auto;} -.navbar .nav li.dropdown.open>.dropdown-toggle,.navbar .nav li.dropdown.active>.dropdown-toggle,.navbar .nav li.dropdown.open.active>.dropdown-toggle{background-color:#e5e5e5;color:#555555;} -.navbar .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#777777;border-bottom-color:#777777;} -.navbar .nav li.dropdown.open>.dropdown-toggle .caret,.navbar .nav li.dropdown.active>.dropdown-toggle .caret,.navbar .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#555555;border-bottom-color:#555555;} -.navbar .pull-right>li>.dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right{left:auto;right:0;}.navbar .pull-right>li>.dropdown-menu:before,.navbar .nav>li>.dropdown-menu.pull-right:before{left:auto;right:12px;} -.navbar .pull-right>li>.dropdown-menu:after,.navbar .nav>li>.dropdown-menu.pull-right:after{left:auto;right:13px;} -.navbar .pull-right>li>.dropdown-menu .dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right .dropdown-menu{left:auto;right:100%;margin-left:0;margin-right:-1px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px;} -.navbar-inverse{color:#999999;}.navbar-inverse .navbar-inner{background-color:#1b1b1b;background-image:-moz-linear-gradient(top, #222222, #111111);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#222222), to(#111111));background-image:-webkit-linear-gradient(top, #222222, #111111);background-image:-o-linear-gradient(top, #222222, #111111);background-image:linear-gradient(to bottom, #222222, #111111);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff111111', GradientType=0);border-color:#252525;} -.navbar-inverse .brand,.navbar-inverse .nav>li>a{color:#999999;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);}.navbar-inverse .brand:hover,.navbar-inverse .nav>li>a:hover{color:#ffffff;} -.navbar-inverse .nav>li>a:focus,.navbar-inverse .nav>li>a:hover{background-color:transparent;color:#ffffff;} -.navbar-inverse .nav .active>a,.navbar-inverse .nav .active>a:hover,.navbar-inverse .nav .active>a:focus{color:#ffffff;background-color:#111111;} -.navbar-inverse .navbar-link{color:#999999;}.navbar-inverse .navbar-link:hover{color:#ffffff;} -.navbar-inverse .divider-vertical{border-left-color:#111111;border-right-color:#222222;} -.navbar-inverse .nav li.dropdown.open>.dropdown-toggle,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle{background-color:#111111;color:#ffffff;} -.navbar-inverse .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#999999;border-bottom-color:#999999;} -.navbar-inverse .nav li.dropdown.open>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;} -.navbar-inverse .navbar-search .search-query{color:#ffffff;background-color:#515151;border-color:#111111;-webkit-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15);-moz-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15);box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15);-webkit-transition:none;-moz-transition:none;-o-transition:none;transition:none;}.navbar-inverse .navbar-search .search-query:-moz-placeholder{color:#cccccc;} -.navbar-inverse .navbar-search .search-query:-ms-input-placeholder{color:#cccccc;} -.navbar-inverse .navbar-search .search-query::-webkit-input-placeholder{color:#cccccc;} -.navbar-inverse .navbar-search .search-query:focus,.navbar-inverse .navbar-search .search-query.focused{padding:5px 15px;color:#333333;text-shadow:0 1px 0 #ffffff;background-color:#ffffff;border:0;-webkit-box-shadow:0 0 3px rgba(0, 0, 0, 0.15);-moz-box-shadow:0 0 3px rgba(0, 0, 0, 0.15);box-shadow:0 0 3px rgba(0, 0, 0, 0.15);outline:0;} -.navbar-inverse .btn-navbar{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#0e0e0e;background-image:-moz-linear-gradient(top, #151515, #040404);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#151515), to(#040404));background-image:-webkit-linear-gradient(top, #151515, #040404);background-image:-o-linear-gradient(top, #151515, #040404);background-image:linear-gradient(to bottom, #151515, #040404);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515', endColorstr='#ff040404', GradientType=0);border-color:#040404 #040404 #000000;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#040404;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.navbar-inverse .btn-navbar:hover,.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active,.navbar-inverse .btn-navbar.disabled,.navbar-inverse .btn-navbar[disabled]{color:#ffffff;background-color:#040404;*background-color:#000000;} -.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active{background-color:#000000 \9;} -.breadcrumb{padding:8px 15px;margin:0 0 20px;list-style:none;background-color:#f5f5f5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}.breadcrumb li{display:inline-block;*display:inline;*zoom:1;text-shadow:0 1px 0 #ffffff;} -.breadcrumb .divider{padding:0 5px;color:#ccc;} -.breadcrumb .active{color:#999999;} -.pagination{height:40px;margin:20px 0;} -.pagination ul{display:inline-block;*display:inline;*zoom:1;margin-left:0;margin-bottom:0;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 2px rgba(0, 0, 0, 0.05);-moz-box-shadow:0 1px 2px rgba(0, 0, 0, 0.05);box-shadow:0 1px 2px rgba(0, 0, 0, 0.05);} -.pagination ul>li{display:inline;} -.pagination ul>li>a,.pagination ul>li>span{float:left;padding:0 14px;line-height:38px;text-decoration:none;background-color:#ffffff;border:1px solid #dddddd;border-left-width:0;} -.pagination ul>li>a:hover,.pagination ul>.active>a,.pagination ul>.active>span{background-color:#f5f5f5;} -.pagination ul>.active>a,.pagination ul>.active>span{color:#999999;cursor:default;} -.pagination ul>.disabled>span,.pagination ul>.disabled>a,.pagination ul>.disabled>a:hover{color:#999999;background-color:transparent;cursor:default;} -.pagination ul>li:first-child>a,.pagination ul>li:first-child>span{border-left-width:1px;-webkit-border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;border-radius:3px 0 0 3px;} -.pagination ul>li:last-child>a,.pagination ul>li:last-child>span{-webkit-border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;border-radius:0 3px 3px 0;} -.pagination-centered{text-align:center;} -.pagination-right{text-align:right;} -.pager{margin:20px 0;list-style:none;text-align:center;*zoom:1;}.pager:before,.pager:after{display:table;content:"";line-height:0;} -.pager:after{clear:both;} -.pager li{display:inline;} -.pager a,.pager span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px;} -.pager a:hover{text-decoration:none;background-color:#f5f5f5;} -.pager .next a,.pager .next span{float:right;} -.pager .previous a{float:left;} -.pager .disabled a,.pager .disabled a:hover,.pager .disabled span{color:#999999;background-color:#fff;cursor:default;} -.thumbnails{margin-left:-20px;list-style:none;*zoom:1;}.thumbnails:before,.thumbnails:after{display:table;content:"";line-height:0;} -.thumbnails:after{clear:both;} -.row-fluid .thumbnails{margin-left:0;} -.thumbnails>li{float:left;margin-bottom:20px;margin-left:20px;} -.thumbnail{display:block;padding:4px;line-height:20px;border:1px solid #ddd;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 3px rgba(0, 0, 0, 0.055);-moz-box-shadow:0 1px 3px rgba(0, 0, 0, 0.055);box-shadow:0 1px 3px rgba(0, 0, 0, 0.055);-webkit-transition:all 0.2s ease-in-out;-moz-transition:all 0.2s ease-in-out;-o-transition:all 0.2s ease-in-out;transition:all 0.2s ease-in-out;} -a.thumbnail:hover{border-color:#0088cc;-webkit-box-shadow:0 1px 4px rgba(0, 105, 214, 0.25);-moz-box-shadow:0 1px 4px rgba(0, 105, 214, 0.25);box-shadow:0 1px 4px rgba(0, 105, 214, 0.25);} -.thumbnail>img{display:block;max-width:100%;margin-left:auto;margin-right:auto;} -.thumbnail .caption{padding:9px;color:#555555;} -.alert{padding:8px 35px 8px 14px;margin-bottom:20px;text-shadow:0 1px 0 rgba(255, 255, 255, 0.5);background-color:#fcf8e3;border:1px solid #fbeed5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;color:#c09853;} -.alert h4{margin:0;} -.alert .close{position:relative;top:-2px;right:-21px;line-height:20px;} -.alert-success{background-color:#dff0d8;border-color:#d6e9c6;color:#468847;} -.alert-danger,.alert-error{background-color:#f2dede;border-color:#eed3d7;color:#b94a48;} -.alert-info{background-color:#d9edf7;border-color:#bce8f1;color:#3a87ad;} -.alert-block{padding-top:14px;padding-bottom:14px;} -.alert-block>p,.alert-block>ul{margin-bottom:0;} -.alert-block p+p{margin-top:5px;} -@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}@-o-keyframes progress-bar-stripes{from{background-position:0 0;} to{background-position:40px 0;}}@keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}.progress{overflow:hidden;height:20px;margin-bottom:20px;background-color:#f7f7f7;background-image:-moz-linear-gradient(top, #f5f5f5, #f9f9f9);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9));background-image:-webkit-linear-gradient(top, #f5f5f5, #f9f9f9);background-image:-o-linear-gradient(top, #f5f5f5, #f9f9f9);background-image:linear-gradient(to bottom, #f5f5f5, #f9f9f9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0);-webkit-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1);-moz-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1);box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} -.progress .bar{width:0%;height:100%;color:#ffffff;float:left;font-size:12px;text-align:center;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#0e90d2;background-image:-moz-linear-gradient(top, #149bdf, #0480be);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be));background-image:-webkit-linear-gradient(top, #149bdf, #0480be);background-image:-o-linear-gradient(top, #149bdf, #0480be);background-image:linear-gradient(to bottom, #149bdf, #0480be);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0);-webkit-box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.15);-moz-box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.15);box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.15);-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-transition:width 0.6s ease;-moz-transition:width 0.6s ease;-o-transition:width 0.6s ease;transition:width 0.6s ease;} -.progress .bar+.bar{-webkit-box-shadow:inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15);-moz-box-shadow:inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15);box-shadow:inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15);} -.progress-striped .bar{background-color:#149bdf;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);-webkit-background-size:40px 40px;-moz-background-size:40px 40px;-o-background-size:40px 40px;background-size:40px 40px;} -.progress.active .bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite;} -.progress-danger .bar,.progress .bar-danger{background-color:#dd514c;background-image:-moz-linear-gradient(top, #ee5f5b, #c43c35);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35));background-image:-webkit-linear-gradient(top, #ee5f5b, #c43c35);background-image:-o-linear-gradient(top, #ee5f5b, #c43c35);background-image:linear-gradient(to bottom, #ee5f5b, #c43c35);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffc43c35', GradientType=0);} -.progress-danger.progress-striped .bar,.progress-striped .bar-danger{background-color:#ee5f5b;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);} -.progress-success .bar,.progress .bar-success{background-color:#5eb95e;background-image:-moz-linear-gradient(top, #62c462, #57a957);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#57a957));background-image:-webkit-linear-gradient(top, #62c462, #57a957);background-image:-o-linear-gradient(top, #62c462, #57a957);background-image:linear-gradient(to bottom, #62c462, #57a957);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff57a957', GradientType=0);} -.progress-success.progress-striped .bar,.progress-striped .bar-success{background-color:#62c462;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);} -.progress-info .bar,.progress .bar-info{background-color:#4bb1cf;background-image:-moz-linear-gradient(top, #5bc0de, #339bb9);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#339bb9));background-image:-webkit-linear-gradient(top, #5bc0de, #339bb9);background-image:-o-linear-gradient(top, #5bc0de, #339bb9);background-image:linear-gradient(to bottom, #5bc0de, #339bb9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff339bb9', GradientType=0);} -.progress-info.progress-striped .bar,.progress-striped .bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);} -.progress-warning .bar,.progress .bar-warning{background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);} -.progress-warning.progress-striped .bar,.progress-striped .bar-warning{background-color:#fbb450;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);} -.hero-unit{padding:60px;margin-bottom:30px;background-color:#eeeeee;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;}.hero-unit h1{margin-bottom:0;font-size:60px;line-height:1;color:inherit;letter-spacing:-1px;} -.hero-unit p{font-size:18px;font-weight:200;line-height:30px;color:inherit;} -.tooltip{position:absolute;z-index:1030;display:block;visibility:visible;padding:5px;font-size:11px;opacity:0;filter:alpha(opacity=0);}.tooltip.in{opacity:0.8;filter:alpha(opacity=80);} -.tooltip.top{margin-top:-3px;} -.tooltip.right{margin-left:3px;} -.tooltip.bottom{margin-top:3px;} -.tooltip.left{margin-left:-3px;} -.tooltip-inner{max-width:200px;padding:3px 8px;color:#ffffff;text-align:center;text-decoration:none;background-color:#000000;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} -.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid;} -.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000000;} -.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000000;} -.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000000;} -.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000000;} -.popover{position:absolute;top:0;left:0;z-index:1010;display:none;width:236px;padding:1px;background-color:#ffffff;-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.2);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);-moz-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);}.popover.top{margin-bottom:10px;} -.popover.right{margin-left:10px;} -.popover.bottom{margin-top:10px;} -.popover.left{margin-right:10px;} -.popover-title{margin:0;padding:8px 14px;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;-webkit-border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0;} -.popover-content{padding:9px 14px;}.popover-content p,.popover-content ul,.popover-content ol{margin-bottom:0;} -.popover .arrow,.popover .arrow:after{position:absolute;display:inline-block;width:0;height:0;border-color:transparent;border-style:solid;} -.popover .arrow:after{content:"";z-index:-1;} -.popover.top .arrow{bottom:-10px;left:50%;margin-left:-10px;border-width:10px 10px 0;border-top-color:#ffffff;}.popover.top .arrow:after{border-width:11px 11px 0;border-top-color:rgba(0, 0, 0, 0.25);bottom:-1px;left:-11px;} -.popover.right .arrow{top:50%;left:-10px;margin-top:-10px;border-width:10px 10px 10px 0;border-right-color:#ffffff;}.popover.right .arrow:after{border-width:11px 11px 11px 0;border-right-color:rgba(0, 0, 0, 0.25);bottom:-11px;left:-1px;} -.popover.bottom .arrow{top:-10px;left:50%;margin-left:-10px;border-width:0 10px 10px;border-bottom-color:#ffffff;}.popover.bottom .arrow:after{border-width:0 11px 11px;border-bottom-color:rgba(0, 0, 0, 0.25);top:-1px;left:-11px;} -.popover.left .arrow{top:50%;right:-10px;margin-top:-10px;border-width:10px 0 10px 10px;border-left-color:#ffffff;}.popover.left .arrow:after{border-width:11px 0 11px 11px;border-left-color:rgba(0, 0, 0, 0.25);bottom:-11px;right:-1px;} -.modal-open .modal .dropdown-menu{z-index:2050;} -.modal-open .modal .dropdown.open{*z-index:2050;} -.modal-open .modal .popover{z-index:2060;} -.modal-open .modal .tooltip{z-index:2080;} -.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000000;}.modal-backdrop.fade{opacity:0;} -.modal-backdrop,.modal-backdrop.fade.in{opacity:0.8;filter:alpha(opacity=80);} -.modal{position:fixed;top:50%;left:50%;z-index:1050;overflow:auto;width:560px;margin:-250px 0 0 -280px;background-color:#ffffff;border:1px solid #999;border:1px solid rgba(0, 0, 0, 0.3);*border:1px solid #999;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);-moz-box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);-webkit-background-clip:padding-box;-moz-background-clip:padding-box;background-clip:padding-box;}.modal.fade{-webkit-transition:opacity .3s linear, top .3s ease-out;-moz-transition:opacity .3s linear, top .3s ease-out;-o-transition:opacity .3s linear, top .3s ease-out;transition:opacity .3s linear, top .3s ease-out;top:-25%;} -.modal.fade.in{top:50%;} -.modal-header{padding:9px 15px;border-bottom:1px solid #eee;}.modal-header .close{margin-top:2px;} -.modal-header h3{margin:0;line-height:30px;} -.modal-body{overflow-y:auto;max-height:400px;padding:15px;} -.modal-form{margin-bottom:0;} -.modal-footer{padding:14px 15px 15px;margin-bottom:0;text-align:right;background-color:#f5f5f5;border-top:1px solid #ddd;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;-webkit-box-shadow:inset 0 1px 0 #ffffff;-moz-box-shadow:inset 0 1px 0 #ffffff;box-shadow:inset 0 1px 0 #ffffff;*zoom:1;}.modal-footer:before,.modal-footer:after{display:table;content:"";line-height:0;} -.modal-footer:after{clear:both;} -.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0;} -.modal-footer .btn-group .btn+.btn{margin-left:-1px;} -.dropup,.dropdown{position:relative;} -.dropdown-toggle{*margin-bottom:-3px;} -.dropdown-toggle:active,.open .dropdown-toggle{outline:0;} -.caret{display:inline-block;width:0;height:0;vertical-align:top;border-top:4px solid #000000;border-right:4px solid transparent;border-left:4px solid transparent;content:"";} -.dropdown .caret{margin-top:8px;margin-left:2px;} -.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#ffffff;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.2);*border-right-width:2px;*border-bottom-width:2px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);-moz-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box;}.dropdown-menu.pull-right{right:0;left:auto;} -.dropdown-menu .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #ffffff;} -.dropdown-menu a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:20px;color:#333333;white-space:nowrap;} -.dropdown-menu li>a:hover,.dropdown-menu li>a:focus,.dropdown-submenu:hover>a{text-decoration:none;color:#ffffff;background-color:#0088cc;background-color:#0081c2;background-image:-moz-linear-gradient(top, #0088cc, #0077b3);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3));background-image:-webkit-linear-gradient(top, #0088cc, #0077b3);background-image:-o-linear-gradient(top, #0088cc, #0077b3);background-image:linear-gradient(to bottom, #0088cc, #0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0);} -.dropdown-menu .active>a,.dropdown-menu .active>a:hover{color:#ffffff;text-decoration:none;outline:0;background-color:#0088cc;background-color:#0081c2;background-image:-moz-linear-gradient(top, #0088cc, #0077b3);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3));background-image:-webkit-linear-gradient(top, #0088cc, #0077b3);background-image:-o-linear-gradient(top, #0088cc, #0077b3);background-image:linear-gradient(to bottom, #0088cc, #0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0);} -.dropdown-menu .disabled>a,.dropdown-menu .disabled>a:hover{color:#999999;} -.dropdown-menu .disabled>a:hover{text-decoration:none;background-color:transparent;cursor:default;} -.open{*z-index:1000;}.open >.dropdown-menu{display:block;} -.pull-right>.dropdown-menu{right:0;left:auto;} -.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000000;content:"";} -.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px;} -.dropdown-submenu{position:relative;} -.dropdown-submenu>.dropdown-menu{top:0;left:100%;margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px;} -.dropdown-submenu:hover>.dropdown-menu{display:block;} -.dropdown-submenu>a:after{display:block;content:" ";float:right;width:0;height:0;border-color:transparent;border-style:solid;border-width:5px 0 5px 5px;border-left-color:#cccccc;margin-top:5px;margin-right:-10px;} -.dropdown-submenu:hover>a:after{border-left-color:#ffffff;} -.dropdown .dropdown-menu .nav-header{padding-left:20px;padding-right:20px;} -.typeahead{margin-top:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} -.accordion{margin-bottom:20px;} -.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} -.accordion-heading{border-bottom:0;} -.accordion-heading .accordion-toggle{display:block;padding:8px 15px;} -.accordion-toggle{cursor:pointer;} -.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5;} -.carousel{position:relative;margin-bottom:20px;line-height:1;} -.carousel-inner{overflow:hidden;width:100%;position:relative;} -.carousel .item{display:none;position:relative;-webkit-transition:0.6s ease-in-out left;-moz-transition:0.6s ease-in-out left;-o-transition:0.6s ease-in-out left;transition:0.6s ease-in-out left;} -.carousel .item>img{display:block;line-height:1;} -.carousel .active,.carousel .next,.carousel .prev{display:block;} -.carousel .active{left:0;} -.carousel .next,.carousel .prev{position:absolute;top:0;width:100%;} -.carousel .next{left:100%;} -.carousel .prev{left:-100%;} -.carousel .next.left,.carousel .prev.right{left:0;} -.carousel .active.left{left:-100%;} -.carousel .active.right{left:100%;} -.carousel-control{position:absolute;top:40%;left:15px;width:40px;height:40px;margin-top:-20px;font-size:60px;font-weight:100;line-height:30px;color:#ffffff;text-align:center;background:#222222;border:3px solid #ffffff;-webkit-border-radius:23px;-moz-border-radius:23px;border-radius:23px;opacity:0.5;filter:alpha(opacity=50);}.carousel-control.right{left:auto;right:15px;} -.carousel-control:hover{color:#ffffff;text-decoration:none;opacity:0.9;filter:alpha(opacity=90);} -.carousel-caption{position:absolute;left:0;right:0;bottom:0;padding:15px;background:#333333;background:rgba(0, 0, 0, 0.75);} -.carousel-caption h4,.carousel-caption p{color:#ffffff;line-height:20px;} -.carousel-caption h4{margin:0 0 5px;} -.carousel-caption p{margin-bottom:0;} -.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);}.well blockquote{border-color:#ddd;border-color:rgba(0, 0, 0, 0.15);} -.well-large{padding:24px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;} -.well-small{padding:9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} -.close{float:right;font-size:20px;font-weight:bold;line-height:20px;color:#000000;text-shadow:0 1px 0 #ffffff;opacity:0.2;filter:alpha(opacity=20);}.close:hover{color:#000000;text-decoration:none;cursor:pointer;opacity:0.4;filter:alpha(opacity=40);} -button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none;} -.pull-right{float:right;} -.pull-left{float:left;} -.hide{display:none;} -.show{display:block;} -.invisible{visibility:hidden;} -.affix{position:fixed;} -.fade{opacity:0;-webkit-transition:opacity 0.15s linear;-moz-transition:opacity 0.15s linear;-o-transition:opacity 0.15s linear;transition:opacity 0.15s linear;}.fade.in{opacity:1;} -.collapse{position:relative;height:0;overflow:hidden;-webkit-transition:height 0.35s ease;-moz-transition:height 0.35s ease;-o-transition:height 0.35s ease;transition:height 0.35s ease;}.collapse.in{height:auto;} -.hidden{display:none;visibility:hidden;} -.visible-phone{display:none !important;} -.visible-tablet{display:none !important;} -.hidden-desktop{display:none !important;} -.visible-desktop{display:inherit !important;} -@media (min-width:768px) and (max-width:979px){.hidden-desktop{display:inherit !important;} .visible-desktop{display:none !important ;} .visible-tablet{display:inherit !important;} .hidden-tablet{display:none !important;}}@media (max-width:767px){.hidden-desktop{display:inherit !important;} .visible-desktop{display:none !important;} .visible-phone{display:inherit !important;} .hidden-phone{display:none !important;}}@media (max-width:767px){body{padding-left:20px;padding-right:20px;} .navbar-fixed-top,.navbar-fixed-bottom,.navbar-static-top{margin-left:-20px;margin-right:-20px;} .container-fluid{padding:0;} .dl-horizontal dt{float:none;clear:none;width:auto;text-align:left;} .dl-horizontal dd{margin-left:0;} .container{width:auto;} .row-fluid{width:100%;} .row,.thumbnails{margin-left:0;} .thumbnails>li{float:none;margin-left:0;} [class*="span"],.row-fluid [class*="span"]{float:none;display:block;width:100%;margin-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} .span12,.row-fluid .span12{width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} .input-large,.input-xlarge,.input-xxlarge,input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} .input-prepend input,.input-append input,.input-prepend input[class*="span"],.input-append input[class*="span"]{display:inline-block;width:auto;} .controls-row [class*="span"]+[class*="span"]{margin-left:0;} .modal{position:fixed;top:20px;left:20px;right:20px;width:auto;margin:0;}.modal.fade.in{top:auto;}}@media (max-width:480px){.nav-collapse{-webkit-transform:translate3d(0, 0, 0);} .page-header h1 small{display:block;line-height:20px;} input[type="checkbox"],input[type="radio"]{border:1px solid #ccc;} .form-horizontal .control-label{float:none;width:auto;padding-top:0;text-align:left;} .form-horizontal .controls{margin-left:0;} .form-horizontal .control-list{padding-top:0;} .form-horizontal .form-actions{padding-left:10px;padding-right:10px;} .modal{top:10px;left:10px;right:10px;} .modal-header .close{padding:10px;margin:-10px;} .carousel-caption{position:static;}}@media (min-width:768px) and (max-width:979px){.row{margin-left:-20px;*zoom:1;}.row:before,.row:after{display:table;content:"";line-height:0;} .row:after{clear:both;} [class*="span"]{float:left;min-height:1px;margin-left:20px;} .container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:724px;} .span12{width:724px;} .span11{width:662px;} .span10{width:600px;} .span9{width:538px;} .span8{width:476px;} .span7{width:414px;} .span6{width:352px;} .span5{width:290px;} .span4{width:228px;} .span3{width:166px;} .span2{width:104px;} .span1{width:42px;} .offset12{margin-left:764px;} .offset11{margin-left:702px;} .offset10{margin-left:640px;} .offset9{margin-left:578px;} .offset8{margin-left:516px;} .offset7{margin-left:454px;} .offset6{margin-left:392px;} .offset5{margin-left:330px;} .offset4{margin-left:268px;} .offset3{margin-left:206px;} .offset2{margin-left:144px;} .offset1{margin-left:82px;} .row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";line-height:0;} .row-fluid:after{clear:both;} .row-fluid [class*="span"]{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;float:left;margin-left:2.7624309392265194%;*margin-left:2.709239449864817%;} .row-fluid [class*="span"]:first-child{margin-left:0;} .row-fluid .span12{width:100%;*width:99.94680851063829%;} .row-fluid .span11{width:91.43646408839778%;*width:91.38327259903608%;} .row-fluid .span10{width:82.87292817679558%;*width:82.81973668743387%;} .row-fluid .span9{width:74.30939226519337%;*width:74.25620077583166%;} .row-fluid .span8{width:65.74585635359117%;*width:65.69266486422946%;} .row-fluid .span7{width:57.18232044198895%;*width:57.12912895262725%;} .row-fluid .span6{width:48.61878453038674%;*width:48.56559304102504%;} .row-fluid .span5{width:40.05524861878453%;*width:40.00205712942283%;} .row-fluid .span4{width:31.491712707182323%;*width:31.43852121782062%;} .row-fluid .span3{width:22.92817679558011%;*width:22.87498530621841%;} .row-fluid .span2{width:14.3646408839779%;*width:14.311449394616199%;} .row-fluid .span1{width:5.801104972375691%;*width:5.747913483013988%;} .row-fluid .offset12{margin-left:105.52486187845304%;*margin-left:105.41847889972962%;} .row-fluid .offset12:first-child{margin-left:102.76243093922652%;*margin-left:102.6560479605031%;} .row-fluid .offset11{margin-left:96.96132596685082%;*margin-left:96.8549429881274%;} .row-fluid .offset11:first-child{margin-left:94.1988950276243%;*margin-left:94.09251204890089%;} .row-fluid .offset10{margin-left:88.39779005524862%;*margin-left:88.2914070765252%;} .row-fluid .offset10:first-child{margin-left:85.6353591160221%;*margin-left:85.52897613729868%;} .row-fluid .offset9{margin-left:79.8342541436464%;*margin-left:79.72787116492299%;} .row-fluid .offset9:first-child{margin-left:77.07182320441989%;*margin-left:76.96544022569647%;} .row-fluid .offset8{margin-left:71.2707182320442%;*margin-left:71.16433525332079%;} .row-fluid .offset8:first-child{margin-left:68.50828729281768%;*margin-left:68.40190431409427%;} .row-fluid .offset7{margin-left:62.70718232044199%;*margin-left:62.600799341718584%;} .row-fluid .offset7:first-child{margin-left:59.94475138121547%;*margin-left:59.838368402492065%;} .row-fluid .offset6{margin-left:54.14364640883978%;*margin-left:54.037263430116376%;} .row-fluid .offset6:first-child{margin-left:51.38121546961326%;*margin-left:51.27483249088986%;} .row-fluid .offset5{margin-left:45.58011049723757%;*margin-left:45.47372751851417%;} .row-fluid .offset5:first-child{margin-left:42.81767955801105%;*margin-left:42.71129657928765%;} .row-fluid .offset4{margin-left:37.01657458563536%;*margin-left:36.91019160691196%;} .row-fluid .offset4:first-child{margin-left:34.25414364640884%;*margin-left:34.14776066768544%;} .row-fluid .offset3{margin-left:28.45303867403315%;*margin-left:28.346655695309746%;} .row-fluid .offset3:first-child{margin-left:25.69060773480663%;*margin-left:25.584224756083227%;} .row-fluid .offset2{margin-left:19.88950276243094%;*margin-left:19.783119783707537%;} .row-fluid .offset2:first-child{margin-left:17.12707182320442%;*margin-left:17.02068884448102%;} .row-fluid .offset1{margin-left:11.32596685082873%;*margin-left:11.219583872105325%;} .row-fluid .offset1:first-child{margin-left:8.56353591160221%;*margin-left:8.457152932878806%;} input,textarea,.uneditable-input{margin-left:0;} .controls-row [class*="span"]+[class*="span"]{margin-left:20px;} input.span12, textarea.span12, .uneditable-input.span12{width:710px;} input.span11, textarea.span11, .uneditable-input.span11{width:648px;} input.span10, textarea.span10, .uneditable-input.span10{width:586px;} input.span9, textarea.span9, .uneditable-input.span9{width:524px;} input.span8, textarea.span8, .uneditable-input.span8{width:462px;} input.span7, textarea.span7, .uneditable-input.span7{width:400px;} input.span6, textarea.span6, .uneditable-input.span6{width:338px;} input.span5, textarea.span5, .uneditable-input.span5{width:276px;} input.span4, textarea.span4, .uneditable-input.span4{width:214px;} input.span3, textarea.span3, .uneditable-input.span3{width:152px;} input.span2, textarea.span2, .uneditable-input.span2{width:90px;} input.span1, textarea.span1, .uneditable-input.span1{width:28px;}}@media (min-width:1200px){.row{margin-left:-30px;*zoom:1;}.row:before,.row:after{display:table;content:"";line-height:0;} .row:after{clear:both;} [class*="span"]{float:left;min-height:1px;margin-left:30px;} .container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:1170px;} .span12{width:1170px;} .span11{width:1070px;} .span10{width:970px;} .span9{width:870px;} .span8{width:770px;} .span7{width:670px;} .span6{width:570px;} .span5{width:470px;} .span4{width:370px;} .span3{width:270px;} .span2{width:170px;} .span1{width:70px;} .offset12{margin-left:1230px;} .offset11{margin-left:1130px;} .offset10{margin-left:1030px;} .offset9{margin-left:930px;} .offset8{margin-left:830px;} .offset7{margin-left:730px;} .offset6{margin-left:630px;} .offset5{margin-left:530px;} .offset4{margin-left:430px;} .offset3{margin-left:330px;} .offset2{margin-left:230px;} .offset1{margin-left:130px;} .row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";line-height:0;} .row-fluid:after{clear:both;} .row-fluid [class*="span"]{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;float:left;margin-left:2.564102564102564%;*margin-left:2.5109110747408616%;} .row-fluid [class*="span"]:first-child{margin-left:0;} .row-fluid .span12{width:100%;*width:99.94680851063829%;} .row-fluid .span11{width:91.45299145299145%;*width:91.39979996362975%;} .row-fluid .span10{width:82.90598290598291%;*width:82.8527914166212%;} .row-fluid .span9{width:74.35897435897436%;*width:74.30578286961266%;} .row-fluid .span8{width:65.81196581196582%;*width:65.75877432260411%;} .row-fluid .span7{width:57.26495726495726%;*width:57.21176577559556%;} .row-fluid .span6{width:48.717948717948715%;*width:48.664757228587014%;} .row-fluid .span5{width:40.17094017094017%;*width:40.11774868157847%;} .row-fluid .span4{width:31.623931623931625%;*width:31.570740134569924%;} .row-fluid .span3{width:23.076923076923077%;*width:23.023731587561375%;} .row-fluid .span2{width:14.52991452991453%;*width:14.476723040552828%;} .row-fluid .span1{width:5.982905982905983%;*width:5.929714493544281%;} .row-fluid .offset12{margin-left:105.12820512820512%;*margin-left:105.02182214948171%;} .row-fluid .offset12:first-child{margin-left:102.56410256410257%;*margin-left:102.45771958537915%;} .row-fluid .offset11{margin-left:96.58119658119658%;*margin-left:96.47481360247316%;} .row-fluid .offset11:first-child{margin-left:94.01709401709402%;*margin-left:93.91071103837061%;} .row-fluid .offset10{margin-left:88.03418803418803%;*margin-left:87.92780505546462%;} .row-fluid .offset10:first-child{margin-left:85.47008547008548%;*margin-left:85.36370249136206%;} .row-fluid .offset9{margin-left:79.48717948717949%;*margin-left:79.38079650845607%;} .row-fluid .offset9:first-child{margin-left:76.92307692307693%;*margin-left:76.81669394435352%;} .row-fluid .offset8{margin-left:70.94017094017094%;*margin-left:70.83378796144753%;} .row-fluid .offset8:first-child{margin-left:68.37606837606839%;*margin-left:68.26968539734497%;} .row-fluid .offset7{margin-left:62.393162393162385%;*margin-left:62.28677941443899%;} .row-fluid .offset7:first-child{margin-left:59.82905982905982%;*margin-left:59.72267685033642%;} .row-fluid .offset6{margin-left:53.84615384615384%;*margin-left:53.739770867430444%;} .row-fluid .offset6:first-child{margin-left:51.28205128205128%;*margin-left:51.175668303327875%;} .row-fluid .offset5{margin-left:45.299145299145295%;*margin-left:45.1927623204219%;} .row-fluid .offset5:first-child{margin-left:42.73504273504273%;*margin-left:42.62865975631933%;} .row-fluid .offset4{margin-left:36.75213675213675%;*margin-left:36.645753773413354%;} .row-fluid .offset4:first-child{margin-left:34.18803418803419%;*margin-left:34.081651209310785%;} .row-fluid .offset3{margin-left:28.205128205128204%;*margin-left:28.0987452264048%;} .row-fluid .offset3:first-child{margin-left:25.641025641025642%;*margin-left:25.53464266230224%;} .row-fluid .offset2{margin-left:19.65811965811966%;*margin-left:19.551736679396257%;} .row-fluid .offset2:first-child{margin-left:17.094017094017094%;*margin-left:16.98763411529369%;} .row-fluid .offset1{margin-left:11.11111111111111%;*margin-left:11.004728132387708%;} .row-fluid .offset1:first-child{margin-left:8.547008547008547%;*margin-left:8.440625568285142%;} input,textarea,.uneditable-input{margin-left:0;} .controls-row [class*="span"]+[class*="span"]{margin-left:30px;} input.span12, textarea.span12, .uneditable-input.span12{width:1156px;} input.span11, textarea.span11, .uneditable-input.span11{width:1056px;} input.span10, textarea.span10, .uneditable-input.span10{width:956px;} input.span9, textarea.span9, .uneditable-input.span9{width:856px;} input.span8, textarea.span8, .uneditable-input.span8{width:756px;} input.span7, textarea.span7, .uneditable-input.span7{width:656px;} input.span6, textarea.span6, .uneditable-input.span6{width:556px;} input.span5, textarea.span5, .uneditable-input.span5{width:456px;} input.span4, textarea.span4, .uneditable-input.span4{width:356px;} input.span3, textarea.span3, .uneditable-input.span3{width:256px;} input.span2, textarea.span2, .uneditable-input.span2{width:156px;} input.span1, textarea.span1, .uneditable-input.span1{width:56px;} .thumbnails{margin-left:-30px;} .thumbnails>li{margin-left:30px;} .row-fluid .thumbnails{margin-left:0;}}@media (max-width:979px){body{padding-top:0;} .navbar-fixed-top,.navbar-fixed-bottom{position:static;} .navbar-fixed-top{margin-bottom:20px;} .navbar-fixed-bottom{margin-top:20px;} .navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding:5px;} .navbar .container{width:auto;padding:0;} .navbar .brand{padding-left:10px;padding-right:10px;margin:0 0 0 -5px;} .nav-collapse{clear:both;} .nav-collapse .nav{float:none;margin:0 0 10px;} .nav-collapse .nav>li{float:none;} .nav-collapse .nav>li>a{margin-bottom:2px;} .nav-collapse .nav>.divider-vertical{display:none;} .nav-collapse .nav .nav-header{color:#777777;text-shadow:none;} .nav-collapse .nav>li>a,.nav-collapse .dropdown-menu a{padding:9px 15px;font-weight:bold;color:#777777;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} .nav-collapse .btn{padding:4px 10px 4px;font-weight:normal;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} .nav-collapse .dropdown-menu li+li a{margin-bottom:2px;} .nav-collapse .nav>li>a:hover,.nav-collapse .dropdown-menu a:hover{background-color:#f2f2f2;} .navbar-inverse .nav-collapse .nav>li>a:hover,.navbar-inverse .nav-collapse .dropdown-menu a:hover{background-color:#111111;} .nav-collapse.in .btn-group{margin-top:5px;padding:0;} .nav-collapse .dropdown-menu{position:static;top:auto;left:auto;float:none;display:block;max-width:none;margin:0 15px;padding:0;background-color:transparent;border:none;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;} .nav-collapse .dropdown-menu:before,.nav-collapse .dropdown-menu:after{display:none;} .nav-collapse .dropdown-menu .divider{display:none;} .nav-collapse .nav>li>.dropdown-menu:before,.nav-collapse .nav>li>.dropdown-menu:after{display:none;} .nav-collapse .navbar-form,.nav-collapse .navbar-search{float:none;padding:10px 15px;margin:10px 0;border-top:1px solid #f2f2f2;border-bottom:1px solid #f2f2f2;-webkit-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);-moz-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);} .navbar-inverse .nav-collapse .navbar-form,.navbar-inverse .nav-collapse .navbar-search{border-top-color:#111111;border-bottom-color:#111111;} .navbar .nav-collapse .nav.pull-right{float:none;margin-left:0;} .nav-collapse,.nav-collapse.collapse{overflow:hidden;height:0;} .navbar .btn-navbar{display:block;} .navbar-static .navbar-inner{padding-left:10px;padding-right:10px;}}@media (min-width:980px){.nav-collapse.collapse{height:auto !important;overflow:visible !important;}} + * Bootstrap v3.2.0 (http://getbootstrap.com) + * Copyright 2011-2014 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + *//*! normalize.css v3.0.1 | MIT License | git.io/normalize */html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background:0 0}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0;font-size:2em}mark{color:#000;background:#ff0}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{height:0;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{margin:0;font:inherit;color:inherit}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}input{line-height:normal}input[type=checkbox],input[type=radio]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid silver}legend{padding:0;border:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-spacing:0;border-collapse:collapse}td,th{padding:0}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;-webkit-box-shadow:none!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}select{background:#fff!important}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}@font-face{font-family:'Glyphicons Halflings';src:url(../fonts/glyphicons-halflings-regular.eot);src:url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(../fonts/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/glyphicons-halflings-regular.ttf) format('truetype'),url(../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"\2a"}.glyphicon-plus:before{content:"\2b"}.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-lock:before{content:"\e033"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-bookmark:before{content:"\e044"}.glyphicon-print:before{content:"\e045"}.glyphicon-camera:before{content:"\e046"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-fire:before{content:"\e104"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-calendar:before{content:"\e109"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-bell:before{content:"\e123"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-wrench:before{content:"\e136"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-briefcase:before{content:"\e139"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-paperclip:before{content:"\e142"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-pushpin:before{content:"\e146"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}:before,:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.img-responsive,.thumbnail>img,.thumbnail a>img,.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;width:100% \9;max-width:100%;height:auto}.img-rounded{border-radius:6px}.img-thumbnail{display:inline-block;width:100% \9;max-width:100%;height:auto;padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small,h1 .small,h2 .small,h3 .small,h4 .small,h5 .small,h6 .small,.h1 .small,.h2 .small,.h3 .small,.h4 .small,.h5 .small,.h6 .small{font-weight:400;line-height:1;color:#777}h1,.h1,h2,.h2,h3,.h3{margin-top:20px;margin-bottom:10px}h1 small,.h1 small,h2 small,.h2 small,h3 small,.h3 small,h1 .small,.h1 .small,h2 .small,.h2 .small,h3 .small,.h3 .small{font-size:65%}h4,.h4,h5,.h5,h6,.h6{margin-top:10px;margin-bottom:10px}h4 small,.h4 small,h5 small,.h5 small,h6 small,.h6 small,h4 .small,.h4 .small,h5 .small,.h5 .small,h6 .small,.h6 .small{font-size:75%}h1,.h1{font-size:36px}h2,.h2{font-size:30px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16px;font-weight:300;line-height:1.4}@media (min-width:768px){.lead{font-size:21px}}small,.small{font-size:85%}cite{font-style:normal}mark,.mark{padding:.2em;background-color:#fcf8e3}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-nowrap{white-space:nowrap}.text-lowercase{text-transform:lowercase}.text-uppercase{text-transform:uppercase}.text-capitalize{text-transform:capitalize}.text-muted{color:#777}.text-primary{color:#428bca}a.text-primary:hover{color:#3071a9}.text-success{color:#3c763d}a.text-success:hover{color:#2b542c}.text-info{color:#31708f}a.text-info:hover{color:#245269}.text-warning{color:#8a6d3b}a.text-warning:hover{color:#66512c}.text-danger{color:#a94442}a.text-danger:hover{color:#843534}.bg-primary{color:#fff;background-color:#428bca}a.bg-primary:hover{background-color:#3071a9}.bg-success{background-color:#dff0d8}a.bg-success:hover{background-color:#c1e2b3}.bg-info{background-color:#d9edf7}a.bg-info:hover{background-color:#afd9ee}.bg-warning{background-color:#fcf8e3}a.bg-warning:hover{background-color:#f7ecb5}.bg-danger{background-color:#f2dede}a.bg-danger:hover{background-color:#e4b9b9}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;margin-left:-5px;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-top:0;margin-bottom:20px}dt,dd{line-height:1.42857143}dt{font-weight:700}dd{margin-left:0}@media (min-width:768px){.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #777}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}blockquote p:last-child,blockquote ul:last-child,blockquote ol:last-child{margin-bottom:0}blockquote footer,blockquote small,blockquote .small{display:block;font-size:80%;line-height:1.42857143;color:#777}blockquote footer:before,blockquote small:before,blockquote .small:before{content:'\2014 \00A0'}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;text-align:right;border-right:5px solid #eee;border-left:0}.blockquote-reverse footer:before,blockquote.pull-right footer:before,.blockquote-reverse small:before,blockquote.pull-right small:before,.blockquote-reverse .small:before,blockquote.pull-right .small:before{content:''}.blockquote-reverse footer:after,blockquote.pull-right footer:after,.blockquote-reverse small:after,blockquote.pull-right small:after,.blockquote-reverse .small:after,blockquote.pull-right .small:after{content:'\00A0 \2014'}blockquote:before,blockquote:after{content:""}address{margin-bottom:20px;font-style:normal;line-height:1.42857143}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;border-radius:4px}kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.25);box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;-webkit-box-shadow:none;box-shadow:none}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{margin-right:-15px;margin-left:-15px}.col-xs-1,.col-sm-1,.col-md-1,.col-lg-1,.col-xs-2,.col-sm-2,.col-md-2,.col-lg-2,.col-xs-3,.col-sm-3,.col-md-3,.col-lg-3,.col-xs-4,.col-sm-4,.col-md-4,.col-lg-4,.col-xs-5,.col-sm-5,.col-md-5,.col-lg-5,.col-xs-6,.col-sm-6,.col-md-6,.col-lg-6,.col-xs-7,.col-sm-7,.col-md-7,.col-lg-7,.col-xs-8,.col-sm-8,.col-md-8,.col-lg-8,.col-xs-9,.col-sm-9,.col-md-9,.col-lg-9,.col-xs-10,.col-sm-10,.col-md-10,.col-lg-10,.col-xs-11,.col-sm-11,.col-md-11,.col-lg-11,.col-xs-12,.col-sm-12,.col-md-12,.col-lg-12{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:auto}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-0{left:auto}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}.col-sm-pull-0{right:auto}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666667%}.col-sm-push-10{left:83.33333333%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666667%}.col-sm-push-7{left:58.33333333%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666667%}.col-sm-push-4{left:33.33333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.66666667%}.col-sm-push-1{left:8.33333333%}.col-sm-push-0{left:auto}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666667%}.col-sm-offset-10{margin-left:83.33333333%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666667%}.col-sm-offset-7{margin-left:58.33333333%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666667%}.col-sm-offset-4{margin-left:33.33333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.66666667%}.col-sm-offset-1{margin-left:8.33333333%}.col-sm-offset-0{margin-left:0}}@media (min-width:992px){.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666667%}.col-md-pull-10{right:83.33333333%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666667%}.col-md-pull-7{right:58.33333333%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666667%}.col-md-pull-4{right:33.33333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.66666667%}.col-md-pull-1{right:8.33333333%}.col-md-pull-0{right:auto}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666667%}.col-md-push-10{left:83.33333333%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666667%}.col-md-push-7{left:58.33333333%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666667%}.col-md-push-4{left:33.33333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.66666667%}.col-md-push-1{left:8.33333333%}.col-md-push-0{left:auto}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666667%}.col-md-offset-10{margin-left:83.33333333%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666667%}.col-md-offset-7{margin-left:58.33333333%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666667%}.col-md-offset-4{margin-left:33.33333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.66666667%}.col-md-offset-1{margin-left:8.33333333%}.col-md-offset-0{margin-left:0}}@media (min-width:1200px){.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666667%}.col-lg-pull-10{right:83.33333333%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666667%}.col-lg-pull-7{right:58.33333333%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666667%}.col-lg-pull-4{right:33.33333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.66666667%}.col-lg-pull-1{right:8.33333333%}.col-lg-pull-0{right:auto}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666667%}.col-lg-push-10{left:83.33333333%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666667%}.col-lg-push-7{left:58.33333333%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666667%}.col-lg-push-4{left:33.33333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.66666667%}.col-lg-push-1{left:8.33333333%}.col-lg-push-0{left:auto}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666667%}.col-lg-offset-10{margin-left:83.33333333%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666667%}.col-lg-offset-7{margin-left:58.33333333%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666667%}.col-lg-offset-4{margin-left:33.33333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.66666667%}.col-lg-offset-1{margin-left:8.33333333%}.col-lg-offset-0{margin-left:0}}table{background-color:transparent}th{text-align:left}.table{width:100%;max-width:100%;margin-bottom:20px}.table>thead>tr>th,.table>tbody>tr>th,.table>tfoot>tr>th,.table>thead>tr>td,.table>tbody>tr>td,.table>tfoot>tr>td{padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>th,.table>caption+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>td,.table>thead:first-child>tr:first-child>td{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>thead>tr>th,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>tbody>tr>td,.table-condensed>tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>thead>tr>td{border-bottom-width:2px}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class*=col-]{position:static;display:table-column;float:none}table td[class*=col-],table th[class*=col-]{position:static;display:table-cell;float:none}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover,.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr:hover>.active,.table-hover>tbody>tr.active:hover>th{background-color:#e8e8e8}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr:hover>.success,.table-hover>tbody>tr.success:hover>th{background-color:#d0e9c6}.table>thead>tr>td.info,.table>tbody>tr>td.info,.table>tfoot>tr>td.info,.table>thead>tr>th.info,.table>tbody>tr>th.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>tbody>tr.info>td,.table>tfoot>tr.info>td,.table>thead>tr.info>th,.table>tbody>tr.info>th,.table>tfoot>tr.info>th{background-color:#d9edf7}.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover,.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr:hover>.info,.table-hover>tbody>tr.info:hover>th{background-color:#c4e3f3}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr:hover>.warning,.table-hover>tbody>tr.warning:hover>th{background-color:#faf2cc}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr:hover>.danger,.table-hover>tbody>tr.danger:hover>th{background-color:#ebcccc}@media screen and (max-width:767px){.table-responsive{width:100%;margin-bottom:15px;overflow-x:auto;overflow-y:hidden;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>thead>tr>th,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tfoot>tr>td{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>thead>tr>th:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.table-responsive>.table-bordered>thead>tr>th:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>th,.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>td{border-bottom:0}}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=radio],input[type=checkbox]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=file]:focus,input[type=radio]:focus,input[type=checkbox]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{display:block;padding-top:7px;font-size:14px;line-height:1.42857143;color:#555}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#777;opacity:1}.form-control:-ms-input-placeholder{color:#777}.form-control::-webkit-input-placeholder{color:#777}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee;opacity:1}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}input[type=date],input[type=time],input[type=datetime-local],input[type=month]{line-height:34px;line-height:1.42857143 \0}input[type=date].input-sm,input[type=time].input-sm,input[type=datetime-local].input-sm,input[type=month].input-sm{line-height:30px}input[type=date].input-lg,input[type=time].input-lg,input[type=datetime-local].input-lg,input[type=month].input-lg{line-height:46px}.form-group{margin-bottom:15px}.radio,.checkbox{position:relative;display:block;min-height:20px;margin-top:10px;margin-bottom:10px}.radio label,.checkbox label{padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.radio input[type=radio],.radio-inline input[type=radio],.checkbox input[type=checkbox],.checkbox-inline input[type=checkbox]{position:absolute;margin-top:4px \9;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;font-weight:400;vertical-align:middle;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type=radio][disabled],input[type=checkbox][disabled],input[type=radio].disabled,input[type=checkbox].disabled,fieldset[disabled] input[type=radio],fieldset[disabled] input[type=checkbox]{cursor:not-allowed}.radio-inline.disabled,.checkbox-inline.disabled,fieldset[disabled] .radio-inline,fieldset[disabled] .checkbox-inline{cursor:not-allowed}.radio.disabled label,.checkbox.disabled label,fieldset[disabled] .radio label,fieldset[disabled] .checkbox label{cursor:not-allowed}.form-control-static{padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-control-static.input-sm{padding-right:0;padding-left:0}.input-sm,.form-horizontal .form-group-sm .form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}textarea.input-sm,select[multiple].input-sm{height:auto}.input-lg,.form-horizontal .form-group-lg .form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-lg{height:46px;line-height:46px}textarea.input-lg,select[multiple].input-lg{height:auto}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:25px;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center}.input-lg+.form-control-feedback{width:46px;height:46px;line-height:46px}.input-sm+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .help-block,.has-success .control-label,.has-success .radio,.has-success .checkbox,.has-success .radio-inline,.has-success .checkbox-inline{color:#3c763d}.has-success .form-control{border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;background-color:#dff0d8;border-color:#3c763d}.has-success .form-control-feedback{color:#3c763d}.has-warning .help-block,.has-warning .control-label,.has-warning .radio,.has-warning .checkbox,.has-warning .radio-inline,.has-warning .checkbox-inline{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;background-color:#fcf8e3;border-color:#8a6d3b}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .help-block,.has-error .control-label,.has-error .radio,.has-error .checkbox,.has-error .radio-inline,.has-error .checkbox-inline{color:#a94442}.has-error .form-control{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;background-color:#f2dede;border-color:#a94442}.has-error .form-control-feedback{color:#a94442}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn,.form-inline .input-group .form-control{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .radio,.form-inline .checkbox{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .radio label,.form-inline .checkbox label{padding-left:0}.form-inline .radio input[type=radio],.form-inline .checkbox input[type=checkbox]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{padding-top:7px;margin-top:0;margin-bottom:0}.form-horizontal .radio,.form-horizontal .checkbox{min-height:27px}.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.form-horizontal .control-label{padding-top:7px;margin-bottom:0;text-align:right}}.form-horizontal .has-feedback .form-control-feedback{top:0;right:15px}@media (min-width:768px){.form-horizontal .form-group-lg .control-label{padding-top:14.3px}}@media (min-width:768px){.form-horizontal .form-group-sm .control-label{padding-top:6px}}.btn{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-image:none;border:1px solid transparent;border-radius:4px}.btn:focus,.btn:active:focus,.btn.active:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#333;text-decoration:none}.btn:active,.btn.active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:not-allowed;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none;opacity:.65}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open>.dropdown-toggle.btn-default{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default:active,.btn-default.active,.open>.dropdown-toggle.btn-default{background-image:none}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open>.dropdown-toggle.btn-primary{color:#fff;background-color:#3071a9;border-color:#285e8e}.btn-primary:active,.btn-primary.active,.open>.dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#357ebd}.btn-primary .badge{color:#428bca;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open>.dropdown-toggle.btn-success{color:#fff;background-color:#449d44;border-color:#398439}.btn-success:active,.btn-success.active,.open>.dropdown-toggle.btn-success{background-image:none}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open>.dropdown-toggle.btn-info{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info:active,.btn-info.active,.open>.dropdown-toggle.btn-info{background-image:none}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open>.dropdown-toggle.btn-warning{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning:active,.btn-warning.active,.open>.dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open>.dropdown-toggle.btn-danger{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger:active,.btn-danger.active,.open>.dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{font-weight:400;color:#428bca;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#777;text-decoration:none}.btn-lg,.btn-group-lg>.btn{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-sm,.btn-group-sm>.btn{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-xs,.btn-group-xs>.btn{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;-o-transition:height .35s ease;transition:height .35s ease}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;text-align:left;list-style:none;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175)}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#262626;text-decoration:none;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#428bca;outline:0}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#777}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{right:0;left:auto}.dropdown-menu-left{right:auto;left:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.42857143;color:#777;white-space:nowrap}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{content:"";border-top:0;border-bottom:4px solid}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}@media (min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}.navbar-right .dropdown-menu-left{right:auto;left:0}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:focus,.btn-group-vertical>.btn:focus,.btn-group>.btn:active,.btn-group-vertical>.btn:active,.btn-group>.btn.active,.btn-group-vertical>.btn.active{z-index:2}.btn-group>.btn:focus,.btn-group-vertical>.btn:focus{outline:0}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-top-left-radius:0;border-bottom-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-left-radius:0;border-top-right-radius:0;border-bottom-left-radius:4px}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-top-right-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{display:table-cell;float:none;width:1%}.btn-group-justified>.btn-group .btn{width:100%}.btn-group-justified>.btn-group .dropdown-menu{left:auto}[data-toggle=buttons]>.btn>input[type=radio],[data-toggle=buttons]>.btn>input[type=checkbox]{position:absolute;z-index:-1;filter:alpha(opacity=0);opacity:0}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-right:0;padding-left:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:46px;line-height:46px}textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn,select[multiple].input-group-lg>.form-control,select[multiple].input-group-lg>.input-group-addon,select[multiple].input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn,select[multiple].input-group-sm>.form-control,select[multiple].input-group-sm>.input-group-addon,select[multiple].input-group-sm>.input-group-btn>.btn{height:auto}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type=radio],.input-group-addon input[type=checkbox]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group-btn:last-child>.btn-group:not(:last-child)>.btn{border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:first-child>.btn-group:not(:first-child)>.btn{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;font-size:0;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:hover,.input-group-btn>.btn:focus,.input-group-btn>.btn:active{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{margin-left:-1px}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#777}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#777;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav .open>a,.nav .open>a:hover,.nav .open>a:focus{background-color:#eee;border-color:#428bca}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.42857143;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}@media (min-width:768px){.navbar{border-radius:4px}}@media (min-width:768px){.navbar-header{float:left}}.navbar-collapse{padding-right:15px;padding-left:15px;overflow-x:visible;-webkit-overflow-scrolling:touch;border-top:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1)}.navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.navbar-collapse{width:auto;border-top:0;-webkit-box-shadow:none;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{padding-right:0;padding-left:0}}.navbar-fixed-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{max-height:340px}@media (max-width:480px) and (orientation:landscape){.navbar-fixed-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{max-height:200px}}.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;-webkit-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}@media (min-width:768px){.navbar-fixed-top,.navbar-fixed-bottom{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;height:50px;padding:15px 15px;font-size:18px;line-height:20px}.navbar-brand:hover,.navbar-brand:focus{text-decoration:none}@media (min-width:768px){.navbar>.container .navbar-brand,.navbar>.container-fluid .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;-webkit-box-shadow:none;box-shadow:none}.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus{background-image:none}}@media (min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}.navbar-nav.navbar-right:last-child{margin-right:-15px}}@media (min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important}}.navbar-form{padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .input-group{display:inline-table;vertical-align:middle}.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn,.navbar-form .input-group .form-control{width:auto}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .radio,.navbar-form .checkbox{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.navbar-form .radio label,.navbar-form .checkbox label{padding-left:0}.navbar-form .radio input[type=radio],.navbar-form .checkbox input[type=checkbox]{position:relative;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.navbar-form .form-group{margin-bottom:5px}}@media (min-width:768px){.navbar-form{width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}.navbar-form.navbar-right:last-child{margin-right:-15px}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-left-radius:0;border-top-right-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.navbar-text{float:left;margin-right:15px;margin-left:15px}.navbar-text.navbar-right:last-child{margin-right:0}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e7e7e7}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus{color:#555;background-color:#e7e7e7}@media (max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-default .btn-link{color:#777}.navbar-default .btn-link:hover,.navbar-default .btn-link:focus{color:#333}.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:hover,.navbar-default .btn-link[disabled]:focus,fieldset[disabled] .navbar-default .btn-link:focus{color:#ccc}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#777}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#777}.navbar-inverse .navbar-nav>li>a{color:#777}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{color:#fff;background-color:#080808}@media (max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#777}.navbar-inverse .navbar-link:hover{color:#fff}.navbar-inverse .btn-link{color:#777}.navbar-inverse .btn-link:hover,.navbar-inverse .btn-link:focus{color:#fff}.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:hover,.navbar-inverse .btn-link[disabled]:focus,fieldset[disabled] .navbar-inverse .btn-link:focus{color:#444}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#777}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;margin-left:-1px;line-height:1.42857143;color:#428bca;text-decoration:none;background-color:#fff;border:1px solid #ddd}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-top-left-radius:4px;border-bottom-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:hover,.pagination>li>span:hover,.pagination>li>a:focus,.pagination>li>span:focus{color:#2a6496;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>span,.pagination>.active>a:hover,.pagination>.active>span:hover,.pagination>.active>a:focus,.pagination>.active>span:focus{z-index:2;color:#fff;cursor:default;background-color:#428bca;border-color:#428bca}.pagination>.disabled>span,.pagination>.disabled>span:hover,.pagination>.disabled>span:focus,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#777;cursor:not-allowed;background-color:#fff;border-color:#ddd}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-top-left-radius:6px;border-bottom-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-top-left-radius:3px;border-bottom-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#777;cursor:not-allowed;background-color:#fff}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}a.label:hover,a.label:focus{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#777}.label-default[href]:hover,.label-default[href]:focus{background-color:#5e5e5e}.label-primary{background-color:#428bca}.label-primary[href]:hover,.label-primary[href]:focus{background-color:#3071a9}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;background-color:#777;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-xs .badge{top:0;padding:1px 5px}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding:30px;margin-bottom:30px;color:inherit;background-color:#eee}.jumbotron h1,.jumbotron .h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.jumbotron>hr{border-top-color:#d5d5d5}.container .jumbotron{border-radius:6px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron{padding-right:60px;padding-left:60px}.jumbotron h1,.jumbotron .h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail>img,.thumbnail a>img{margin-right:auto;margin-left:auto}a.thumbnail:hover,a.thumbnail:focus,a.thumbnail.active{border-color:#428bca}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable,.alert-dismissible{padding-right:35px}.alert-dismissable .close,.alert-dismissible .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#2b542c}.alert-info{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#245269}.alert-warning{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.alert-warning hr{border-top-color:#f7e1b5}.alert-warning .alert-link{color:#66512c}.alert-danger{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.alert-danger hr{border-top-color:#e4b9c0}.alert-danger .alert-link{color:#843534}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar,.progress-bar-striped{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;background-size:40px 40px}.progress.active .progress-bar,.progress-bar.active{-webkit-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar[aria-valuenow="1"],.progress-bar[aria-valuenow="2"]{min-width:30px}.progress-bar[aria-valuenow="0"]{min-width:30px;color:#777;background-color:transparent;background-image:none;-webkit-box-shadow:none;box-shadow:none}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.list-group{padding-left:0;margin-bottom:20px}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-left-radius:4px;border-top-right-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}a.list-group-item{color:#555}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item:hover,a.list-group-item:focus{color:#555;text-decoration:none;background-color:#f5f5f5}.list-group-item.disabled,.list-group-item.disabled:hover,.list-group-item.disabled:focus{color:#777;background-color:#eee}.list-group-item.disabled .list-group-item-heading,.list-group-item.disabled:hover .list-group-item-heading,.list-group-item.disabled:focus .list-group-item-heading{color:inherit}.list-group-item.disabled .list-group-item-text,.list-group-item.disabled:hover .list-group-item-text,.list-group-item.disabled:focus .list-group-item-text{color:#777}.list-group-item.active,.list-group-item.active:hover,.list-group-item.active:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}.list-group-item.active .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading,.list-group-item.active .list-group-item-heading>small,.list-group-item.active:hover .list-group-item-heading>small,.list-group-item.active:focus .list-group-item-heading>small,.list-group-item.active .list-group-item-heading>.small,.list-group-item.active:hover .list-group-item-heading>.small,.list-group-item.active:focus .list-group-item-heading>.small{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:hover .list-group-item-text,.list-group-item.active:focus .list-group-item-text{color:#e1edf7}.list-group-item-success{color:#3c763d;background-color:#dff0d8}a.list-group-item-success{color:#3c763d}a.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:hover,a.list-group-item-success:focus{color:#3c763d;background-color:#d0e9c6}a.list-group-item-success.active,a.list-group-item-success.active:hover,a.list-group-item-success.active:focus{color:#fff;background-color:#3c763d;border-color:#3c763d}.list-group-item-info{color:#31708f;background-color:#d9edf7}a.list-group-item-info{color:#31708f}a.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:hover,a.list-group-item-info:focus{color:#31708f;background-color:#c4e3f3}a.list-group-item-info.active,a.list-group-item-info.active:hover,a.list-group-item-info.active:focus{color:#fff;background-color:#31708f;border-color:#31708f}.list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}a.list-group-item-warning{color:#8a6d3b}a.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:hover,a.list-group-item-warning:focus{color:#8a6d3b;background-color:#faf2cc}a.list-group-item-warning.active,a.list-group-item-warning.active:hover,a.list-group-item-warning.active:focus{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.list-group-item-danger{color:#a94442;background-color:#f2dede}a.list-group-item-danger{color:#a94442}a.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:hover,a.list-group-item-danger:focus{color:#a94442;background-color:#ebcccc}a.list-group-item-danger.active,a.list-group-item-danger.active:hover,a.list-group-item-danger.active:focus{color:#fff;background-color:#a94442;border-color:#a94442}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-left-radius:3px;border-top-right-radius:3px}.panel-heading>.dropdown .dropdown-toggle{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.panel-title>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.list-group{margin-bottom:0}.panel>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-left-radius:3px;border-top-right-radius:3px}.panel>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.list-group+.panel-footer{border-top-width:0}.panel>.table,.panel>.table-responsive>.table,.panel>.panel-collapse>.table{margin-bottom:0}.panel>.table:first-child,.panel>.table-responsive:first-child>.table:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.panel>.table:last-child,.panel>.table-responsive:last-child>.table:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child th,.panel>.table>tbody:first-child>tr:first-child td{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th{border-bottom:0}.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}.panel>.table-responsive{margin-bottom:0;border:0}.panel-group{margin-bottom:20px}.panel-group .panel{margin-bottom:0;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse>.panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ddd}.panel-default>.panel-heading .badge{color:#f5f5f5;background-color:#333}.panel-default>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#428bca}.panel-primary>.panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-primary>.panel-heading+.panel-collapse>.panel-body{border-top-color:#428bca}.panel-primary>.panel-heading .badge{color:#428bca;background-color:#fff}.panel-primary>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d6e9c6}.panel-success>.panel-heading .badge{color:#dff0d8;background-color:#3c763d}.panel-success>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d6e9c6}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse>.panel-body{border-top-color:#bce8f1}.panel-info>.panel-heading .badge{color:#d9edf7;background-color:#31708f}.panel-info>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#bce8f1}.panel-warning{border-color:#faebcc}.panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.panel-warning>.panel-heading+.panel-collapse>.panel-body{border-top-color:#faebcc}.panel-warning>.panel-heading .badge{color:#fcf8e3;background-color:#8a6d3b}.panel-warning>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#faebcc}.panel-danger{border-color:#ebccd1}.panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.panel-danger>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ebccd1}.panel-danger>.panel-heading .badge{color:#f2dede;background-color:#a94442}.panel-danger>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ebccd1}.embed-responsive{position:relative;display:block;height:0;padding:0;overflow:hidden}.embed-responsive .embed-responsive-item,.embed-responsive iframe,.embed-responsive embed,.embed-responsive object{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive.embed-responsive-16by9{padding-bottom:56.25%}.embed-responsive.embed-responsive-4by3{padding-bottom:75%}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;filter:alpha(opacity=20);opacity:.2}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;filter:alpha(opacity=50);opacity:.5}button.close{-webkit-appearance:none;padding:0;cursor:pointer;background:0 0;border:0}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;display:none;overflow:hidden;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transition:-webkit-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out;-webkit-transform:translate3d(0,-25%,0);-o-transform:translate3d(0,-25%,0);transform:translate3d(0,-25%,0)}.modal.in .modal-dialog{-webkit-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5)}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{filter:alpha(opacity=0);opacity:0}.modal-backdrop.in{filter:alpha(opacity=50);opacity:.5}.modal-header{min-height:16.43px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.42857143}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1070;display:block;font-size:12px;line-height:1.4;visibility:visible;filter:alpha(opacity=0);opacity:0}.tooltip.in{filter:alpha(opacity=90);opacity:.9}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{right:5px;bottom:0;border-width:5px 5px 0;border-top-color:#000}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1060;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2)}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:400;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{content:"";border-width:10px}.popover.top>.arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,.25);border-bottom-width:0}.popover.top>.arrow:after{bottom:1px;margin-left:-10px;content:" ";border-top-color:#fff;border-bottom-width:0}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,.25);border-left-width:0}.popover.right>.arrow:after{bottom:-10px;left:1px;content:" ";border-right-color:#fff;border-left-width:0}.popover.bottom>.arrow{top:-11px;left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25)}.popover.bottom>.arrow:after{top:1px;margin-left:-10px;content:" ";border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{right:1px;bottom:-10px;content:" ";border-right-width:0;border-left-color:#fff}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6);filter:alpha(opacity=50);opacity:.5}.carousel-control.left{background-image:-webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.5)),to(rgba(0,0,0,.0001)));background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);background-repeat:repeat-x}.carousel-control.right{right:0;left:auto;background-image:-webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.0001)),to(rgba(0,0,0,.5)));background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);background-repeat:repeat-x}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;filter:alpha(opacity=90);outline:0;opacity:.9}.carousel-control .icon-prev,.carousel-control .icon-next,.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right{position:absolute;top:50%;z-index:5;display:inline-block}.carousel-control .icon-prev,.carousel-control .glyphicon-chevron-left{left:50%;margin-left:-10px}.carousel-control .icon-next,.carousel-control .glyphicon-chevron-right{right:50%;margin-right:-10px}.carousel-control .icon-prev,.carousel-control .icon-next{width:20px;height:20px;margin-top:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;padding-left:0;margin-left:-30%;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;background-color:#000 \9;background-color:rgba(0,0,0,0);border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;font-size:30px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{margin-left:-15px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{margin-right:-15px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.clearfix:before,.clearfix:after,.dl-horizontal dd:before,.dl-horizontal dd:after,.container:before,.container:after,.container-fluid:before,.container-fluid:after,.row:before,.row:after,.form-horizontal .form-group:before,.form-horizontal .form-group:after,.btn-toolbar:before,.btn-toolbar:after,.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after,.nav:before,.nav:after,.navbar:before,.navbar:after,.navbar-header:before,.navbar-header:after,.navbar-collapse:before,.navbar-collapse:after,.pager:before,.pager:after,.panel-body:before,.panel-body:after,.modal-footer:before,.modal-footer:after{display:table;content:" "}.clearfix:after,.dl-horizontal dd:after,.container:after,.container-fluid:after,.row:after,.form-horizontal .form-group:after,.btn-toolbar:after,.btn-group-vertical>.btn-group:after,.nav:after,.navbar:after,.navbar-header:after,.navbar-collapse:after,.pager:after,.panel-body:after,.modal-footer:after{clear:both}.center-block{display:block;margin-right:auto;margin-left:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important;visibility:hidden!important}.affix{position:fixed;-webkit-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}@-ms-viewport{width:device-width}.visible-xs,.visible-sm,.visible-md,.visible-lg{display:none!important}.visible-xs-block,.visible-xs-inline,.visible-xs-inline-block,.visible-sm-block,.visible-sm-inline,.visible-sm-inline-block,.visible-md-block,.visible-md-inline,.visible-md-inline-block,.visible-lg-block,.visible-lg-inline,.visible-lg-inline-block{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table}tr.visible-xs{display:table-row!important}th.visible-xs,td.visible-xs{display:table-cell!important}}@media (max-width:767px){.visible-xs-block{display:block!important}}@media (max-width:767px){.visible-xs-inline{display:inline!important}}@media (max-width:767px){.visible-xs-inline-block{display:inline-block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-block{display:block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline{display:inline!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline-block{display:inline-block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-block{display:block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline{display:inline!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline-block{display:inline-block!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}}@media (min-width:1200px){.visible-lg-block{display:block!important}}@media (min-width:1200px){.visible-lg-inline{display:inline!important}}@media (min-width:1200px){.visible-lg-inline-block{display:inline-block!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}}.visible-print-block{display:none!important}@media print{.visible-print-block{display:block!important}}.visible-print-inline{display:none!important}@media print{.visible-print-inline{display:inline!important}}.visible-print-inline-block{display:none!important}@media print{.visible-print-inline-block{display:inline-block!important}}@media print{.hidden-print{display:none!important}} \ No newline at end of file diff --git a/rest_framework/static/rest_framework/js/bootstrap.min.js b/rest_framework/static/rest_framework/js/bootstrap.min.js index e0b220f40..7c1561a8b 100644 --- a/rest_framework/static/rest_framework/js/bootstrap.min.js +++ b/rest_framework/static/rest_framework/js/bootstrap.min.js @@ -1,7 +1,6 @@ -/** -* Bootstrap.js by @fat & @mdo -* plugins: bootstrap-transition.js, bootstrap-modal.js, bootstrap-dropdown.js, bootstrap-scrollspy.js, bootstrap-tab.js, bootstrap-tooltip.js, bootstrap-popover.js, bootstrap-affix.js, bootstrap-alert.js, bootstrap-button.js, bootstrap-collapse.js, bootstrap-carousel.js, bootstrap-typeahead.js -* Copyright 2012 Twitter, Inc. -* http://www.apache.org/licenses/LICENSE-2.0.txt -*/ -!function(a){a(function(){a.support.transition=function(){var a=function(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},c;for(c in b)if(a.style[c]!==undefined)return b[c]}();return a&&{end:a}}()})}(window.jQuery),!function(a){var b=function(b,c){this.options=c,this.$element=a(b).delegate('[data-dismiss="modal"]',"click.dismiss.modal",a.proxy(this.hide,this)),this.options.remote&&this.$element.find(".modal-body").load(this.options.remote)};b.prototype={constructor:b,toggle:function(){return this[this.isShown?"hide":"show"]()},show:function(){var b=this,c=a.Event("show");this.$element.trigger(c);if(this.isShown||c.isDefaultPrevented())return;a("body").addClass("modal-open"),this.isShown=!0,this.escape(),this.backdrop(function(){var c=a.support.transition&&b.$element.hasClass("fade");b.$element.parent().length||b.$element.appendTo(document.body),b.$element.show(),c&&b.$element[0].offsetWidth,b.$element.addClass("in").attr("aria-hidden",!1).focus(),b.enforceFocus(),c?b.$element.one(a.support.transition.end,function(){b.$element.trigger("shown")}):b.$element.trigger("shown")})},hide:function(b){b&&b.preventDefault();var c=this;b=a.Event("hide"),this.$element.trigger(b);if(!this.isShown||b.isDefaultPrevented())return;this.isShown=!1,a("body").removeClass("modal-open"),this.escape(),a(document).off("focusin.modal"),this.$element.removeClass("in").attr("aria-hidden",!0),a.support.transition&&this.$element.hasClass("fade")?this.hideWithTransition():this.hideModal()},enforceFocus:function(){var b=this;a(document).on("focusin.modal",function(a){b.$element[0]!==a.target&&!b.$element.has(a.target).length&&b.$element.focus()})},escape:function(){var a=this;this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.modal",function(b){b.which==27&&a.hide()}):this.isShown||this.$element.off("keyup.dismiss.modal")},hideWithTransition:function(){var b=this,c=setTimeout(function(){b.$element.off(a.support.transition.end),b.hideModal()},500);this.$element.one(a.support.transition.end,function(){clearTimeout(c),b.hideModal()})},hideModal:function(a){this.$element.hide().trigger("hidden"),this.backdrop()},removeBackdrop:function(){this.$backdrop.remove(),this.$backdrop=null},backdrop:function(b){var c=this,d=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var e=a.support.transition&&d;this.$backdrop=a('<div class="modal-backdrop '+d+'" />').appendTo(document.body),this.options.backdrop!="static"&&this.$backdrop.click(a.proxy(this.hide,this)),e&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),e?this.$backdrop.one(a.support.transition.end,b):b()}else!this.isShown&&this.$backdrop?(this.$backdrop.removeClass("in"),a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one(a.support.transition.end,a.proxy(this.removeBackdrop,this)):this.removeBackdrop()):b&&b()}},a.fn.modal=function(c){return this.each(function(){var d=a(this),e=d.data("modal"),f=a.extend({},a.fn.modal.defaults,d.data(),typeof c=="object"&&c);e||d.data("modal",e=new b(this,f)),typeof c=="string"?e[c]():f.show&&e.show()})},a.fn.modal.defaults={backdrop:!0,keyboard:!0,show:!0},a.fn.modal.Constructor=b,a(function(){a("body").on("click.modal.data-api",'[data-toggle="modal"]',function(b){var c=a(this),d=c.attr("href"),e=a(c.attr("data-target")||d&&d.replace(/.*(?=#[^\s]+$)/,"")),f=e.data("modal")?"toggle":a.extend({remote:!/#/.test(d)&&d},e.data(),c.data());b.preventDefault(),e.modal(f).one("hide",function(){c.focus()})})})}(window.jQuery),!function(a){function d(){e(a(b)).removeClass("open")}function e(b){var c=b.attr("data-target"),d;return c||(c=b.attr("href"),c=c&&/#/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,"")),d=a(c),d.length||(d=b.parent()),d}var b="[data-toggle=dropdown]",c=function(b){var c=a(b).on("click.dropdown.data-api",this.toggle);a("html").on("click.dropdown.data-api",function(){c.parent().removeClass("open")})};c.prototype={constructor:c,toggle:function(b){var c=a(this),f,g;if(c.is(".disabled, :disabled"))return;return f=e(c),g=f.hasClass("open"),d(),g||(f.toggleClass("open"),c.focus()),!1},keydown:function(b){var c,d,f,g,h,i;if(!/(38|40|27)/.test(b.keyCode))return;c=a(this),b.preventDefault(),b.stopPropagation();if(c.is(".disabled, :disabled"))return;g=e(c),h=g.hasClass("open");if(!h||h&&b.keyCode==27)return c.click();d=a("[role=menu] li:not(.divider) a",g);if(!d.length)return;i=d.index(d.filter(":focus")),b.keyCode==38&&i>0&&i--,b.keyCode==40&&i<d.length-1&&i++,~i||(i=0),d.eq(i).focus()}},a.fn.dropdown=function(b){return this.each(function(){var d=a(this),e=d.data("dropdown");e||d.data("dropdown",e=new c(this)),typeof b=="string"&&e[b].call(d)})},a.fn.dropdown.Constructor=c,a(function(){a("html").on("click.dropdown.data-api touchstart.dropdown.data-api",d),a("body").on("click.dropdown touchstart.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.dropdown.data-api touchstart.dropdown.data-api",b,c.prototype.toggle).on("keydown.dropdown.data-api touchstart.dropdown.data-api",b+", [role=menu]",c.prototype.keydown)})}(window.jQuery),!function(a){function b(b,c){var d=a.proxy(this.process,this),e=a(b).is("body")?a(window):a(b),f;this.options=a.extend({},a.fn.scrollspy.defaults,c),this.$scrollElement=e.on("scroll.scroll-spy.data-api",d),this.selector=(this.options.target||(f=a(b).attr("href"))&&f.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.$body=a("body"),this.refresh(),this.process()}b.prototype={constructor:b,refresh:function(){var b=this,c;this.offsets=a([]),this.targets=a([]),c=this.$body.find(this.selector).map(function(){var b=a(this),c=b.data("target")||b.attr("href"),d=/^#\w/.test(c)&&a(c);return d&&d.length&&[[d.position().top,c]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},process:function(){var a=this.$scrollElement.scrollTop()+this.options.offset,b=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,c=b-this.$scrollElement.height(),d=this.offsets,e=this.targets,f=this.activeTarget,g;if(a>=c)return f!=(g=e.last()[0])&&this.activate(g);for(g=d.length;g--;)f!=e[g]&&a>=d[g]&&(!d[g+1]||a<=d[g+1])&&this.activate(e[g])},activate:function(b){var c,d;this.activeTarget=b,a(this.selector).parent(".active").removeClass("active"),d=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',c=a(d).parent("li").addClass("active"),c.parent(".dropdown-menu").length&&(c=c.closest("li.dropdown").addClass("active")),c.trigger("activate")}},a.fn.scrollspy=function(c){return this.each(function(){var d=a(this),e=d.data("scrollspy"),f=typeof c=="object"&&c;e||d.data("scrollspy",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.scrollspy.Constructor=b,a.fn.scrollspy.defaults={offset:10},a(window).on("load",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);b.scrollspy(b.data())})})}(window.jQuery),!function(a){var b=function(b){this.element=a(b)};b.prototype={constructor:b,show:function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.attr("data-target"),e,f,g;d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,""));if(b.parent("li").hasClass("active"))return;e=c.find(".active a").last()[0],g=a.Event("show",{relatedTarget:e}),b.trigger(g);if(g.isDefaultPrevented())return;f=a(d),this.activate(b.parent("li"),c),this.activate(f,f.parent(),function(){b.trigger({type:"shown",relatedTarget:e})})},activate:function(b,c,d){function g(){e.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),f?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var e=c.find("> .active"),f=d&&a.support.transition&&e.hasClass("fade");f?e.one(a.support.transition.end,g):g(),e.removeClass("in")}},a.fn.tab=function(c){return this.each(function(){var d=a(this),e=d.data("tab");e||d.data("tab",e=new b(this)),typeof c=="string"&&e[c]()})},a.fn.tab.Constructor=b,a(function(){a("body").on("click.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(b){b.preventDefault(),a(this).tab("show")})})}(window.jQuery),!function(a){var b=function(a,b){this.init("tooltip",a,b)};b.prototype={constructor:b,init:function(b,c,d){var e,f;this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.enabled=!0,this.options.trigger=="click"?this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this)):this.options.trigger!="manual"&&(e=this.options.trigger=="hover"?"mouseenter":"focus",f=this.options.trigger=="hover"?"mouseleave":"blur",this.$element.on(e+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(f+"."+this.type,this.options.selector,a.proxy(this.leave,this))),this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},getOptions:function(b){return b=a.extend({},a.fn[this.type].defaults,b,this.$element.data()),b.delay&&typeof b.delay=="number"&&(b.delay={show:b.delay,hide:b.delay}),b},enter:function(b){var c=a(b.currentTarget)[this.type](this._options).data(this.type);if(!c.options.delay||!c.options.delay.show)return c.show();clearTimeout(this.timeout),c.hoverState="in",this.timeout=setTimeout(function(){c.hoverState=="in"&&c.show()},c.options.delay.show)},leave:function(b){var c=a(b.currentTarget)[this.type](this._options).data(this.type);this.timeout&&clearTimeout(this.timeout);if(!c.options.delay||!c.options.delay.hide)return c.hide();c.hoverState="out",this.timeout=setTimeout(function(){c.hoverState=="out"&&c.hide()},c.options.delay.hide)},show:function(){var a,b,c,d,e,f,g;if(this.hasContent()&&this.enabled){a=this.tip(),this.setContent(),this.options.animation&&a.addClass("fade"),f=typeof this.options.placement=="function"?this.options.placement.call(this,a[0],this.$element[0]):this.options.placement,b=/in/.test(f),a.remove().css({top:0,left:0,display:"block"}).appendTo(b?this.$element:document.body),c=this.getPosition(b),d=a[0].offsetWidth,e=a[0].offsetHeight;switch(b?f.split(" ")[1]:f){case"bottom":g={top:c.top+c.height,left:c.left+c.width/2-d/2};break;case"top":g={top:c.top-e,left:c.left+c.width/2-d/2};break;case"left":g={top:c.top+c.height/2-e/2,left:c.left-d};break;case"right":g={top:c.top+c.height/2-e/2,left:c.left+c.width}}a.css(g).addClass(f).addClass("in")}},setContent:function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},hide:function(){function d(){var b=setTimeout(function(){c.off(a.support.transition.end).remove()},500);c.one(a.support.transition.end,function(){clearTimeout(b),c.remove()})}var b=this,c=this.tip();return c.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?d():c.remove(),this},fixTitle:function(){var a=this.$element;(a.attr("title")||typeof a.attr("data-original-title")!="string")&&a.attr("data-original-title",a.attr("title")||"").removeAttr("title")},hasContent:function(){return this.getTitle()},getPosition:function(b){return a.extend({},b?{top:0,left:0}:this.$element.offset(),{width:this.$element[0].offsetWidth,height:this.$element[0].offsetHeight})},getTitle:function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||(typeof c.title=="function"?c.title.call(b[0]):c.title),a},tip:function(){return this.$tip=this.$tip||a(this.options.template)},validate:function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},enable:function(){this.enabled=!0},disable:function(){this.enabled=!1},toggleEnabled:function(){this.enabled=!this.enabled},toggle:function(){this[this.tip().hasClass("in")?"hide":"show"]()},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}},a.fn.tooltip=function(c){return this.each(function(){var d=a(this),e=d.data("tooltip"),f=typeof c=="object"&&c;e||d.data("tooltip",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.tooltip.Constructor=b,a.fn.tooltip.defaults={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover",title:"",delay:0,html:!0}}(window.jQuery),!function(a){var b=function(a,b){this.init("popover",a,b)};b.prototype=a.extend({},a.fn.tooltip.Constructor.prototype,{constructor:b,setContent:function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content > *")[this.options.html?"html":"text"](c),a.removeClass("fade top bottom left right in")},hasContent:function(){return this.getTitle()||this.getContent()},getContent:function(){var a,b=this.$element,c=this.options;return a=b.attr("data-content")||(typeof c.content=="function"?c.content.call(b[0]):c.content),a},tip:function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}}),a.fn.popover=function(c){return this.each(function(){var d=a(this),e=d.data("popover"),f=typeof c=="object"&&c;e||d.data("popover",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.popover.Constructor=b,a.fn.popover.defaults=a.extend({},a.fn.tooltip.defaults,{placement:"right",trigger:"click",content:"",template:'<div class="popover"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'})}(window.jQuery),!function(a){var b=function(b,c){this.options=a.extend({},a.fn.affix.defaults,c),this.$window=a(window).on("scroll.affix.data-api",a.proxy(this.checkPosition,this)),this.$element=a(b),this.checkPosition()};b.prototype.checkPosition=function(){if(!this.$element.is(":visible"))return;var b=a(document).height(),c=this.$window.scrollTop(),d=this.$element.offset(),e=this.options.offset,f=e.bottom,g=e.top,h="affix affix-top affix-bottom",i;typeof e!="object"&&(f=g=e),typeof g=="function"&&(g=e.top()),typeof f=="function"&&(f=e.bottom()),i=this.unpin!=null&&c+this.unpin<=d.top?!1:f!=null&&d.top+this.$element.height()>=b-f?"bottom":g!=null&&c<=g?"top":!1;if(this.affixed===i)return;this.affixed=i,this.unpin=i=="bottom"?d.top-c:null,this.$element.removeClass(h).addClass("affix"+(i?"-"+i:""))},a.fn.affix=function(c){return this.each(function(){var d=a(this),e=d.data("affix"),f=typeof c=="object"&&c;e||d.data("affix",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.affix.Constructor=b,a.fn.affix.defaults={offset:0},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var b=a(this),c=b.data();c.offset=c.offset||{},c.offsetBottom&&(c.offset.bottom=c.offsetBottom),c.offsetTop&&(c.offset.top=c.offsetTop),b.affix(c)})})}(window.jQuery),!function(a){var b='[data-dismiss="alert"]',c=function(c){a(c).on("click",b,this.close)};c.prototype.close=function(b){function f(){e.trigger("closed").remove()}var c=a(this),d=c.attr("data-target"),e;d||(d=c.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),e=a(d),b&&b.preventDefault(),e.length||(e=c.hasClass("alert")?c:c.parent()),e.trigger(b=a.Event("close"));if(b.isDefaultPrevented())return;e.removeClass("in"),a.support.transition&&e.hasClass("fade")?e.on(a.support.transition.end,f):f()},a.fn.alert=function(b){return this.each(function(){var d=a(this),e=d.data("alert");e||d.data("alert",e=new c(this)),typeof b=="string"&&e[b].call(d)})},a.fn.alert.Constructor=c,a(function(){a("body").on("click.alert.data-api",b,c.prototype.close)})}(window.jQuery),!function(a){var b=function(b,c){this.$element=a(b),this.options=a.extend({},a.fn.button.defaults,c)};b.prototype.setState=function(a){var b="disabled",c=this.$element,d=c.data(),e=c.is("input")?"val":"html";a+="Text",d.resetText||c.data("resetText",c[e]()),c[e](d[a]||this.options[a]),setTimeout(function(){a=="loadingText"?c.addClass(b).attr(b,b):c.removeClass(b).removeAttr(b)},0)},b.prototype.toggle=function(){var a=this.$element.closest('[data-toggle="buttons-radio"]');a&&a.find(".active").removeClass("active"),this.$element.toggleClass("active")},a.fn.button=function(c){return this.each(function(){var d=a(this),e=d.data("button"),f=typeof c=="object"&&c;e||d.data("button",e=new b(this,f)),c=="toggle"?e.toggle():c&&e.setState(c)})},a.fn.button.defaults={loadingText:"loading..."},a.fn.button.Constructor=b,a(function(){a("body").on("click.button.data-api","[data-toggle^=button]",function(b){var c=a(b.target);c.hasClass("btn")||(c=c.closest(".btn")),c.button("toggle")})})}(window.jQuery),!function(a){var b=function(b,c){this.$element=a(b),this.options=a.extend({},a.fn.collapse.defaults,c),this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};b.prototype={constructor:b,dimension:function(){var a=this.$element.hasClass("width");return a?"width":"height"},show:function(){var b,c,d,e;if(this.transitioning)return;b=this.dimension(),c=a.camelCase(["scroll",b].join("-")),d=this.$parent&&this.$parent.find("> .accordion-group > .in");if(d&&d.length){e=d.data("collapse");if(e&&e.transitioning)return;d.collapse("hide"),e||d.data("collapse",null)}this.$element[b](0),this.transition("addClass",a.Event("show"),"shown"),a.support.transition&&this.$element[b](this.$element[0][c])},hide:function(){var b;if(this.transitioning)return;b=this.dimension(),this.reset(this.$element[b]()),this.transition("removeClass",a.Event("hide"),"hidden"),this.$element[b](0)},reset:function(a){var b=this.dimension();return this.$element.removeClass("collapse")[b](a||"auto")[0].offsetWidth,this.$element[a!==null?"addClass":"removeClass"]("collapse"),this},transition:function(b,c,d){var e=this,f=function(){c.type=="show"&&e.reset(),e.transitioning=0,e.$element.trigger(d)};this.$element.trigger(c);if(c.isDefaultPrevented())return;this.transitioning=1,this.$element[b]("in"),a.support.transition&&this.$element.hasClass("collapse")?this.$element.one(a.support.transition.end,f):f()},toggle:function(){this[this.$element.hasClass("in")?"hide":"show"]()}},a.fn.collapse=function(c){return this.each(function(){var d=a(this),e=d.data("collapse"),f=typeof c=="object"&&c;e||d.data("collapse",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.collapse.defaults={toggle:!0},a.fn.collapse.Constructor=b,a(function(){a("body").on("click.collapse.data-api","[data-toggle=collapse]",function(b){var c=a(this),d,e=c.attr("data-target")||b.preventDefault()||(d=c.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""),f=a(e).data("collapse")?"toggle":c.data();c[a(e).hasClass("in")?"addClass":"removeClass"]("collapsed"),a(e).collapse(f)})})}(window.jQuery),!function(a){var b=function(b,c){this.$element=a(b),this.options=c,this.options.slide&&this.slide(this.options.slide),this.options.pause=="hover"&&this.$element.on("mouseenter",a.proxy(this.pause,this)).on("mouseleave",a.proxy(this.cycle,this))};b.prototype={cycle:function(b){return b||(this.paused=!1),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},to:function(b){var c=this.$element.find(".item.active"),d=c.parent().children(),e=d.index(c),f=this;if(b>d.length-1||b<0)return;return this.sliding?this.$element.one("slid",function(){f.to(b)}):e==b?this.pause().cycle():this.slide(b>e?"next":"prev",a(d[b]))},pause:function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition.end&&(this.$element.trigger(a.support.transition.end),this.cycle()),clearInterval(this.interval),this.interval=null,this},next:function(){if(this.sliding)return;return this.slide("next")},prev:function(){if(this.sliding)return;return this.slide("prev")},slide:function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g=b=="next"?"left":"right",h=b=="next"?"first":"last",i=this,j=a.Event("slide",{relatedTarget:e[0]});this.sliding=!0,f&&this.pause(),e=e.length?e:this.$element.find(".item")[h]();if(e.hasClass("active"))return;if(a.support.transition&&this.$element.hasClass("slide")){this.$element.trigger(j);if(j.isDefaultPrevented())return;e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),this.$element.one(a.support.transition.end,function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger("slid")},0)})}else{this.$element.trigger(j);if(j.isDefaultPrevented())return;d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return f&&this.cycle(),this}},a.fn.carousel=function(c){return this.each(function(){var d=a(this),e=d.data("carousel"),f=a.extend({},a.fn.carousel.defaults,typeof c=="object"&&c),g=typeof c=="string"?c:f.slide;e||d.data("carousel",e=new b(this,f)),typeof c=="number"?e.to(c):g?e[g]():f.interval&&e.cycle()})},a.fn.carousel.defaults={interval:5e3,pause:"hover"},a.fn.carousel.Constructor=b,a(function(){a("body").on("click.carousel.data-api","[data-slide]",function(b){var c=a(this),d,e=a(c.attr("data-target")||(d=c.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,"")),f=!e.data("modal")&&a.extend({},e.data(),c.data());e.carousel(f),b.preventDefault()})})}(window.jQuery),!function(a){var b=function(b,c){this.$element=a(b),this.options=a.extend({},a.fn.typeahead.defaults,c),this.matcher=this.options.matcher||this.matcher,this.sorter=this.options.sorter||this.sorter,this.highlighter=this.options.highlighter||this.highlighter,this.updater=this.options.updater||this.updater,this.$menu=a(this.options.menu).appendTo("body"),this.source=this.options.source,this.shown=!1,this.listen()};b.prototype={constructor:b,select:function(){var a=this.$menu.find(".active").attr("data-value");return this.$element.val(this.updater(a)).change(),this.hide()},updater:function(a){return a},show:function(){var b=a.extend({},this.$element.offset(),{height:this.$element[0].offsetHeight});return this.$menu.css({top:b.top+b.height,left:b.left}),this.$menu.show(),this.shown=!0,this},hide:function(){return this.$menu.hide(),this.shown=!1,this},lookup:function(b){var c;return this.query=this.$element.val(),!this.query||this.query.length<this.options.minLength?this.shown?this.hide():this:(c=a.isFunction(this.source)?this.source(this.query,a.proxy(this.process,this)):this.source,c?this.process(c):this)},process:function(b){var c=this;return b=a.grep(b,function(a){return c.matcher(a)}),b=this.sorter(b),b.length?this.render(b.slice(0,this.options.items)).show():this.shown?this.hide():this},matcher:function(a){return~a.toLowerCase().indexOf(this.query.toLowerCase())},sorter:function(a){var b=[],c=[],d=[],e;while(e=a.shift())e.toLowerCase().indexOf(this.query.toLowerCase())?~e.indexOf(this.query)?c.push(e):d.push(e):b.push(e);return b.concat(c,d)},highlighter:function(a){var b=this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&");return a.replace(new RegExp("("+b+")","ig"),function(a,b){return"<strong>"+b+"</strong>"})},render:function(b){var c=this;return b=a(b).map(function(b,d){return b=a(c.options.item).attr("data-value",d),b.find("a").html(c.highlighter(d)),b[0]}),b.first().addClass("active"),this.$menu.html(b),this},next:function(b){var c=this.$menu.find(".active").removeClass("active"),d=c.next();d.length||(d=a(this.$menu.find("li")[0])),d.addClass("active")},prev:function(a){var b=this.$menu.find(".active").removeClass("active"),c=b.prev();c.length||(c=this.$menu.find("li").last()),c.addClass("active")},listen:function(){this.$element.on("blur",a.proxy(this.blur,this)).on("keypress",a.proxy(this.keypress,this)).on("keyup",a.proxy(this.keyup,this)),(a.browser.chrome||a.browser.webkit||a.browser.msie)&&this.$element.on("keydown",a.proxy(this.keydown,this)),this.$menu.on("click",a.proxy(this.click,this)).on("mouseenter","li",a.proxy(this.mouseenter,this))},move:function(a){if(!this.shown)return;switch(a.keyCode){case 9:case 13:case 27:a.preventDefault();break;case 38:a.preventDefault(),this.prev();break;case 40:a.preventDefault(),this.next()}a.stopPropagation()},keydown:function(b){this.suppressKeyPressRepeat=!~a.inArray(b.keyCode,[40,38,9,13,27]),this.move(b)},keypress:function(a){if(this.suppressKeyPressRepeat)return;this.move(a)},keyup:function(a){switch(a.keyCode){case 40:case 38:break;case 9:case 13:if(!this.shown)return;this.select();break;case 27:if(!this.shown)return;this.hide();break;default:this.lookup()}a.stopPropagation(),a.preventDefault()},blur:function(a){var b=this;setTimeout(function(){b.hide()},150)},click:function(a){a.stopPropagation(),a.preventDefault(),this.select()},mouseenter:function(b){this.$menu.find(".active").removeClass("active"),a(b.currentTarget).addClass("active")}},a.fn.typeahead=function(c){return this.each(function(){var d=a(this),e=d.data("typeahead"),f=typeof c=="object"&&c;e||d.data("typeahead",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.typeahead.defaults={source:[],items:8,menu:'<ul class="typeahead dropdown-menu"></ul>',item:'<li><a href="#"></a></li>',minLength:1},a.fn.typeahead.Constructor=b,a(function(){a("body").on("focus.typeahead.data-api",'[data-provide="typeahead"]',function(b){var c=a(this);if(c.data("typeahead"))return;b.preventDefault(),c.typeahead(c.data())})})}(window.jQuery) \ No newline at end of file +/*! + * Bootstrap v3.2.0 (http://getbootstrap.com) + * Copyright 2011-2014 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + */ +if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.2.0",d.prototype.close=function(b){function c(){f.detach().trigger("closed.bs.alert").remove()}var d=a(this),e=d.attr("data-target");e||(e=d.attr("href"),e=e&&e.replace(/.*(?=#[^\s]*$)/,""));var f=a(e);b&&b.preventDefault(),f.length||(f=d.hasClass("alert")?d:d.parent()),f.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",c).emulateTransitionEnd(150):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.2.0",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),d[e](null==f[b]?this.options[b]:f[b]),setTimeout(a.proxy(function(){"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}a&&this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),c.preventDefault()})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b).on("keydown.bs.carousel",a.proxy(this.keydown,this)),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.2.0",c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},c.prototype.keydown=function(a){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.to=function(b){var c=this,d=this.getItemIndex(this.$active=this.$element.find(".item.active"));return b>this.$items.length-1||0>b?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g="next"==b?"left":"right",h="next"==b?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}if(e.hasClass("active"))return this.sliding=!1;var j=e[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:g});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,f&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(e)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:g});return a.support.transition&&this.$element.hasClass("slide")?(e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one("bsTransitionEnd",function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(1e3*d.css("transition-duration").slice(0,-1))):(d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger(m)),f&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b);!e&&f.toggle&&"show"==b&&(b=!b),e||d.data("bs.collapse",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};c.VERSION="3.2.0",c.DEFAULTS={toggle:!0},c.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},c.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var c=a.Event("show.bs.collapse");if(this.$element.trigger(c),!c.isDefaultPrevented()){var d=this.$parent&&this.$parent.find("> .panel > .in");if(d&&d.length){var e=d.data("bs.collapse");if(e&&e.transitioning)return;b.call(d,"hide"),e||d.data("bs.collapse",null)}var f=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[f](0),this.transitioning=1;var g=function(){this.$element.removeClass("collapsing").addClass("collapse in")[f](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return g.call(this);var h=a.camelCase(["scroll",f].join("-"));this.$element.one("bsTransitionEnd",a.proxy(g,this)).emulateTransitionEnd(350)[f](this.$element[0][h])}}},c.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(d,this)).emulateTransitionEnd(350):d.call(this)}}},c.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var d=a.fn.collapse;a.fn.collapse=b,a.fn.collapse.Constructor=c,a.fn.collapse.noConflict=function(){return a.fn.collapse=d,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(c){var d,e=a(this),f=e.attr("data-target")||c.preventDefault()||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""),g=a(f),h=g.data("bs.collapse"),i=h?"toggle":e.data(),j=e.attr("data-parent"),k=j&&a(j);h&&h.transitioning||(k&&k.find('[data-toggle="collapse"][data-parent="'+j+'"]').not(e).addClass("collapsed"),e[g.hasClass("in")?"addClass":"removeClass"]("collapsed")),b.call(g,i)})}(jQuery),+function(a){"use strict";function b(b){b&&3===b.which||(a(e).remove(),a(f).each(function(){var d=c(a(this)),e={relatedTarget:this};d.hasClass("open")&&(d.trigger(b=a.Event("hide.bs.dropdown",e)),b.isDefaultPrevented()||d.removeClass("open").trigger("hidden.bs.dropdown",e))}))}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.2.0",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(b){if(/(38|40|27)/.test(b.keyCode)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var e=c(d),g=e.hasClass("open");if(!g||g&&27==b.keyCode)return 27==b.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.divider):visible a",i=e.find('[role="menu"]'+h+', [role="listbox"]'+h);if(i.length){var j=i.index(i.filter(":focus"));38==b.keyCode&&j>0&&j--,40==b.keyCode&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f+', [role="menu"], [role="listbox"]',g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$backdrop=this.isShown=null,this.scrollbarWidth=0,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.2.0",c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var c=this,d=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(d),this.isShown||d.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.$body.addClass("modal-open"),this.setScrollbar(),this.escape(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.backdrop(function(){var d=a.support.transition&&c.$element.hasClass("fade");c.$element.parent().length||c.$element.appendTo(c.$body),c.$element.show().scrollTop(0),d&&c.$element[0].offsetWidth,c.$element.addClass("in").attr("aria-hidden",!1),c.enforceFocus();var e=a.Event("shown.bs.modal",{relatedTarget:b});d?c.$element.find(".modal-dialog").one("bsTransitionEnd",function(){c.$element.trigger("focus").trigger(e)}).emulateTransitionEnd(300):c.$element.trigger("focus").trigger(e)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.$body.removeClass("modal-open"),this.resetScrollbar(),this.escape(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(300):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keyup.dismiss.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var c=this,d=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var e=a.support.transition&&d;if(this.$backdrop=a('<div class="modal-backdrop '+d+'" />').appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus.call(this.$element[0]):this.hide.call(this))},this)),e&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;e?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(150):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var f=function(){c.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",f).emulateTransitionEnd(150):f()}else b&&b()},c.prototype.checkScrollbar=function(){document.body.clientWidth>=window.innerWidth||(this.scrollbarWidth=this.scrollbarWidth||this.measureScrollbar())},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.scrollbarWidth&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right","")},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null,this.init("tooltip",a,b)};c.VERSION="3.2.0",c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport);for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show()},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var c=a.contains(document.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!c)return;var d=this,e=this.tip(),f=this.getUID(this.type);this.setContent(),e.attr("id",f),this.$element.attr("aria-describedby",f),this.options.animation&&e.addClass("fade");var g="function"==typeof this.options.placement?this.options.placement.call(this,e[0],this.$element[0]):this.options.placement,h=/\s?auto?\s?/i,i=h.test(g);i&&(g=g.replace(h,"")||"top"),e.detach().css({top:0,left:0,display:"block"}).addClass(g).data("bs."+this.type,this),this.options.container?e.appendTo(this.options.container):e.insertAfter(this.$element);var j=this.getPosition(),k=e[0].offsetWidth,l=e[0].offsetHeight;if(i){var m=g,n=this.$element.parent(),o=this.getPosition(n);g="bottom"==g&&j.top+j.height+l-o.scroll>o.height?"top":"top"==g&&j.top-o.scroll-l<0?"bottom":"right"==g&&j.right+k>o.width?"left":"left"==g&&j.left-k<o.left?"right":g,e.removeClass(m).addClass(g)}var p=this.getCalculatedOffset(g,j,k,l);this.applyPlacement(p,g);var q=function(){d.$element.trigger("shown.bs."+d.type),d.hoverState=null};a.support.transition&&this.$tip.hasClass("fade")?e.one("bsTransitionEnd",q).emulateTransitionEnd(150):q()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top=b.top+g,b.left=b.left+h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=k.left?2*k.left-e+i:2*k.top-f+j,m=k.left?"left":"top",n=k.left?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(l,d[0][n],m)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c,a?50*(1-a/b)+"%":"")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(){function b(){"in"!=c.hoverState&&d.detach(),c.$element.trigger("hidden.bs."+c.type)}var c=this,d=this.tip(),e=a.Event("hide.bs."+this.type);return this.$element.removeAttr("aria-describedby"),this.$element.trigger(e),e.isDefaultPrevented()?void 0:(d.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?d.one("bsTransitionEnd",b).emulateTransitionEnd(150):b(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName;return a.extend({},"function"==typeof c.getBoundingClientRect?c.getBoundingClientRect():null,{scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop(),width:d?a(window).width():b.outerWidth(),height:d?a(window).height():b.outerHeight()},d?{top:0,left:0}:b.offset())},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.validate=function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){clearTimeout(this.timeout),this.hide().$element.off("."+this.type).removeData("bs."+this.type)};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.2.0",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").empty()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},c.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){var e=a.proxy(this.process,this);this.$body=a("body"),this.$scrollElement=a(a(c).is("body")?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",e),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.2.0",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b="offset",c=0;a.isWindow(this.$scrollElement[0])||(b="position",c=this.$scrollElement.scrollTop()),this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight();var d=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[b]().top+c,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){d.offsets.push(this[0]),d.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<=e[0])return g!=(a=f[0])&&this.activate(a);for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parentsUntil(this.options.target,".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.2.0",c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});if(b.trigger(f),!f.isDefaultPrevented()){var g=a(d);this.activate(b.closest("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})}}},c.prototype.activate=function(b,c,d){function e(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),g?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var f=c.find("> .active"),g=d&&a.support.transition&&f.hasClass("fade");g?f.one("bsTransitionEnd",e).emulateTransitionEnd(150):e(),f.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(c){c.preventDefault(),b.call(a(this),"show")})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=this.unpin=this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.2.0",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=a(document).height(),d=this.$target.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;"object"!=typeof f&&(h=g=f),"function"==typeof g&&(g=f.top(this.$element)),"function"==typeof h&&(h=f.bottom(this.$element));var i=null!=this.unpin&&d+this.unpin<=e.top?!1:null!=h&&e.top+this.$element.height()>=b-h?"bottom":null!=g&&g>=d?"top":!1;if(this.affixed!==i){null!=this.unpin&&this.$element.css("top","");var j="affix"+(i?"-"+i:""),k=a.Event(j+".bs.affix");this.$element.trigger(k),k.isDefaultPrevented()||(this.affixed=i,this.unpin="bottom"==i?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(j).trigger(a.Event(j.replace("affix","affixed"))),"bottom"==i&&this.$element.offset({top:b-this.$element.height()-h}))}}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},d.offsetBottom&&(d.offset.bottom=d.offsetBottom),d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); \ No newline at end of file diff --git a/rest_framework/templates/rest_framework/base.html b/rest_framework/templates/rest_framework/base.html index dcb0da2c0..58e7e86cd 100644 --- a/rest_framework/templates/rest_framework/base.html +++ b/rest_framework/templates/rest_framework/base.html @@ -15,8 +15,7 @@ {% block style %} {% block bootstrap_theme %} - <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> - <!--<link rel="stylesheet" type="text/css" href="{% static "rest_framework/css/bootstrap.min.css" %}"/>--> + <link rel="stylesheet" type="text/css" href="{% static "rest_framework/css/bootstrap.min.css" %}"/> <link rel="stylesheet" type="text/css" href="{% static "rest_framework/css/bootstrap-tweaks.css" %}"/> {% endblock %} <link rel="stylesheet" type="text/css" href="{% static "rest_framework/css/prettify.css" %}"/> From bacf8cfa9d9331d0876e7ad7adccdabc5f4833a5 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 31 Oct 2014 15:40:08 +0000 Subject: [PATCH 176/249] Guard against malicious string inputs for numbers. Closes #1903. --- rest_framework/fields.py | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 82b7eb374..d5dccd723 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -545,7 +545,9 @@ class IntegerField(Field): 'invalid': _('A valid integer is required.'), 'max_value': _('Ensure this value is less than or equal to {max_value}.'), 'min_value': _('Ensure this value is greater than or equal to {min_value}.'), + 'max_string_length': _('String value too large') } + MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs. def __init__(self, **kwargs): max_value = kwargs.pop('max_value', None) @@ -559,8 +561,11 @@ class IntegerField(Field): self.validators.append(MinValueValidator(min_value, message=message)) def to_internal_value(self, data): + if isinstance(data, six.text_type) and len(data) > self.MAX_STRING_LENGTH: + self.fail('max_string_length') + try: - data = int(six.text_type(data)) + data = int(data) except (ValueError, TypeError): self.fail('invalid') return data @@ -574,7 +579,9 @@ class FloatField(Field): 'invalid': _("A valid number is required."), 'max_value': _('Ensure this value is less than or equal to {max_value}.'), 'min_value': _('Ensure this value is greater than or equal to {min_value}.'), + 'max_string_length': _('String value too large') } + MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs. def __init__(self, **kwargs): max_value = kwargs.pop('max_value', None) @@ -587,9 +594,12 @@ class FloatField(Field): message = self.error_messages['min_value'].format(min_value=min_value) self.validators.append(MinValueValidator(min_value, message=message)) - def to_internal_value(self, value): + def to_internal_value(self, data): + if isinstance(data, six.text_type) and len(data) > self.MAX_STRING_LENGTH: + self.fail('max_string_length') + try: - return float(value) + return float(data) except (TypeError, ValueError): self.fail('invalid') @@ -604,8 +614,10 @@ class DecimalField(Field): 'min_value': _('Ensure this value is greater than or equal to {min_value}.'), 'max_digits': _('Ensure that there are no more than {max_digits} digits in total.'), 'max_decimal_places': _('Ensure that there are no more than {max_decimal_places} decimal places.'), - 'max_whole_digits': _('Ensure that there are no more than {max_whole_digits} digits before the decimal point.') + 'max_whole_digits': _('Ensure that there are no more than {max_whole_digits} digits before the decimal point.'), + 'max_string_length': _('String value too large') } + MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs. coerce_to_string = api_settings.COERCE_DECIMAL_TO_STRING @@ -621,16 +633,19 @@ class DecimalField(Field): message = self.error_messages['min_value'].format(min_value=min_value) self.validators.append(MinValueValidator(min_value, message=message)) - def to_internal_value(self, value): + def to_internal_value(self, data): """ Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. """ - value = smart_text(value).strip() + data = smart_text(data).strip() + if len(data) > self.MAX_STRING_LENGTH: + self.fail('max_string_length') + try: - value = decimal.Decimal(value) + value = decimal.Decimal(data) except decimal.DecimalException: self.fail('invalid') From 207208fedff2457e921ef7d825ea7c3933b5dd6e Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 31 Oct 2014 16:38:39 +0000 Subject: [PATCH 177/249] Lazy loading of fields and validators. Closes #1963. --- rest_framework/fields.py | 21 ++++++++++++++-- rest_framework/serializers.py | 34 +++++++++++--------------- rest_framework/utils/representation.py | 5 ++++ tests/test_fields.py | 4 +-- tests/test_model_serializer.py | 4 +-- tests/test_validators.py | 16 +++++++++--- 6 files changed, 54 insertions(+), 30 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index d5dccd723..8cc8e81ec 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -143,7 +143,7 @@ class Field(object): def __init__(self, read_only=False, write_only=False, required=None, default=empty, initial=empty, source=None, label=None, help_text=None, style=None, - error_messages=None, validators=[], allow_null=False): + error_messages=None, validators=None, allow_null=False): self._creation_counter = Field._creation_counter Field._creation_counter += 1 @@ -166,9 +166,11 @@ class Field(object): self.label = label self.help_text = help_text self.style = {} if style is None else style - self.validators = validators[:] or self.default_validators[:] self.allow_null = allow_null + if validators is not None: + self.validators = validators[:] + # These are set up by `.bind()` when the field is added to a serializer. self.field_name = None self.parent = None @@ -214,6 +216,21 @@ class Field(object): else: self.source_attrs = self.source.split('.') + # .validators is a lazily loaded property, that gets its default + # value from `get_validators`. + @property + def validators(self): + if not hasattr(self, '_validators'): + self._validators = self.get_validators() + return self._validators + + @validators.setter + def validators(self, validators): + self._validators = validators + + def get_validators(self): + return self.default_validators[:] + def get_initial(self): """ Return a value to use when the field is being returned as a primitive diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index c9f70f2da..82e932ddd 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -282,21 +282,23 @@ class SerializerMetaclass(type): @six.add_metaclass(SerializerMetaclass) class Serializer(BaseSerializer): - def __init__(self, *args, **kwargs): - super(Serializer, self).__init__(*args, **kwargs) + @property + def fields(self): + if not hasattr(self, '_fields'): + self._fields = BindingDict(self) + for key, value in self.get_fields().items(): + self._fields[key] = value + return self._fields + def get_fields(self): # Every new serializer is created with a clone of the field instances. # This allows users to dynamically modify the fields on a serializer # instance without affecting every other serializer class. - self.fields = BindingDict(self) - for key, value in self._get_base_fields().items(): - self.fields[key] = value - - self.validators = getattr(getattr(self, 'Meta', None), 'validators', []) - - def _get_base_fields(self): return copy.deepcopy(self._declared_fields) + def get_validators(self): + return getattr(getattr(self, 'Meta', None), 'validators', []) + def get_initial(self): if self._initial_data is not None: return ReturnDict([ @@ -520,14 +522,6 @@ class ModelSerializer(Serializer): }) _related_class = PrimaryKeyRelatedField - def __init__(self, *args, **kwargs): - super(ModelSerializer, self).__init__(*args, **kwargs) - if 'validators' not in kwargs: - validators = self.get_default_validators() - if validators: - self.validators.extend(validators) - self._kwargs['validators'] = validators - def create(self, validated_attrs): # 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 @@ -578,13 +572,13 @@ class ModelSerializer(Serializer): instance.save() return instance - def get_default_validators(self): + def get_validators(self): field_names = set([ field.source for field in self.fields.values() if (field.source != '*') and ('.' not in field.source) ]) - validators = [] + validators = getattr(getattr(self, 'Meta', None), 'validators', []) model_class = self.Meta.model # Note that we make sure to check `unique_together` both on the @@ -627,7 +621,7 @@ class ModelSerializer(Serializer): return validators - def _get_base_fields(self): + def get_fields(self): declared_fields = copy.deepcopy(self._declared_fields) ret = SortedDict() diff --git a/rest_framework/utils/representation.py b/rest_framework/utils/representation.py index 180b51f8d..2a7c46753 100644 --- a/rest_framework/utils/representation.py +++ b/rest_framework/utils/representation.py @@ -82,6 +82,11 @@ def serializer_repr(serializer, indent, force_many=None): ret += field_repr(field.child_relation, force_many=field.child_relation) else: ret += field_repr(field) + + if serializer.validators: + ret += '\n' + indent_str + 'class Meta:' + ret += '\n' + indent_str + ' validators = ' + smart_repr(serializer.validators) + return ret diff --git a/tests/test_fields.py b/tests/test_fields.py index 3e102ab5a..96d09900e 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -85,7 +85,7 @@ class TestSource: class ExampleSerializer(serializers.Serializer): example_field = serializers.CharField(source='example_field') with pytest.raises(AssertionError) as exc_info: - ExampleSerializer() + ExampleSerializer().fields assert str(exc_info.value) == ( "It is redundant to specify `source='example_field'` on field " "'CharField' in serializer 'ExampleSerializer', because it is the " @@ -1018,7 +1018,7 @@ class TestSerializerMethodField: example_field = serializers.SerializerMethodField('get_example_field') with pytest.raises(AssertionError) as exc_info: - ExampleSerializer() + ExampleSerializer().fields assert str(exc_info.value) == ( "It is redundant to specify `get_example_field` on " "SerializerMethodField 'example_field' in serializer " diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index 18170bc06..b8b621be8 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -181,7 +181,7 @@ class TestRegularFieldMappings(TestCase): fields = ('auto_field', 'invalid') with self.assertRaises(ImproperlyConfigured) as excinfo: - TestSerializer() + TestSerializer().fields expected = 'Field name `invalid` is not valid for model `ModelBase`.' assert str(excinfo.exception) == expected @@ -198,7 +198,7 @@ class TestRegularFieldMappings(TestCase): fields = ('auto_field',) with self.assertRaises(ImproperlyConfigured) as excinfo: - TestSerializer() + TestSerializer().fields expected = ( 'Field `missing` has been declared on serializer ' '`TestSerializer`, but is missing from `Meta.fields`.' diff --git a/tests/test_validators.py b/tests/test_validators.py index 6cc52c837..e6e0b23a8 100644 --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -86,10 +86,12 @@ class TestUniquenessTogetherValidation(TestCase): def test_repr(self): serializer = UniquenessTogetherSerializer() expected = dedent(""" - UniquenessTogetherSerializer(validators=[<UniqueTogetherValidator(queryset=UniquenessTogetherModel.objects.all(), fields=('race_name', 'position'))>]): + UniquenessTogetherSerializer(): id = IntegerField(label='ID', read_only=True) race_name = CharField(max_length=100) position = IntegerField() + class Meta: + validators = [<UniqueTogetherValidator(queryset=UniquenessTogetherModel.objects.all(), fields=('race_name', 'position'))>] """) assert repr(serializer) == expected @@ -173,10 +175,12 @@ class TestUniquenessForDateValidation(TestCase): def test_repr(self): serializer = UniqueForDateSerializer() expected = dedent(""" - UniqueForDateSerializer(validators=[<UniqueForDateValidator(queryset=UniqueForDateModel.objects.all(), field='slug', date_field='published')>]): + UniqueForDateSerializer(): id = IntegerField(label='ID', read_only=True) slug = CharField(max_length=100) published = DateField(required=True) + class Meta: + validators = [<UniqueForDateValidator(queryset=UniqueForDateModel.objects.all(), field='slug', date_field='published')>] """) assert repr(serializer) == expected @@ -231,10 +235,12 @@ class TestHiddenFieldUniquenessForDateValidation(TestCase): serializer = TestSerializer() expected = dedent(""" - TestSerializer(validators=[<UniqueForDateValidator(queryset=HiddenFieldUniqueForDateModel.objects.all(), field='slug', date_field='published')>]): + TestSerializer(): id = IntegerField(label='ID', read_only=True) slug = CharField(max_length=100) published = HiddenField(default=CreateOnlyDefault(<function now>)) + class Meta: + validators = [<UniqueForDateValidator(queryset=HiddenFieldUniqueForDateModel.objects.all(), field='slug', date_field='published')>] """) assert repr(serializer) == expected @@ -246,9 +252,11 @@ class TestHiddenFieldUniquenessForDateValidation(TestCase): serializer = TestSerializer() expected = dedent(""" - TestSerializer(validators=[<UniqueForDateValidator(queryset=HiddenFieldUniqueForDateModel.objects.all(), field='slug', date_field='published')>]): + TestSerializer(): id = IntegerField(label='ID', read_only=True) slug = CharField(max_length=100) published = DateTimeField(default=CreateOnlyDefault(<function now>), read_only=True) + class Meta: + validators = [<UniqueForDateValidator(queryset=HiddenFieldUniqueForDateModel.objects.all(), field='slug', date_field='published')>] """) assert repr(serializer) == expected From 964b3401fbcf27afcc2f1e41c5b0e7c538b1c68f Mon Sep 17 00:00:00 2001 From: Andy Baker <andy@andybak.net> Date: Sat, 1 Nov 2014 10:25:59 +0000 Subject: [PATCH 178/249] typo fix --- docs/topics/3.0-announcement.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 9aeb5df6f..f69c0b252 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -323,7 +323,7 @@ Alternatively, specify the field explicitly on the serializer class: #### Fields for model methods and properties. -With `ModelSerilizer` you can now specify field names in the `fields` option that refer to model methods or properties. For example, suppose you have the following model: +With `ModelSerializer` you can now specify field names in the `fields` option that refer to model methods or properties. For example, suppose you have the following model: class Invitation(models.Model): created = models.DateTimeField() From 56d054e6348a7806dd2591562d7738f1aa0bb002 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 3 Nov 2014 11:06:45 +0000 Subject: [PATCH 179/249] Proper escaping of URLs when replacing query parameter --- rest_framework/templatetags/rest_framework.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/templatetags/rest_framework.py b/rest_framework/templatetags/rest_framework.py index d9424f022..7251f0711 100644 --- a/rest_framework/templatetags/rest_framework.py +++ b/rest_framework/templatetags/rest_framework.py @@ -23,7 +23,7 @@ def replace_query_param(url, key, val): query_dict = QueryDict(query).copy() query_dict[key] = val query = query_dict.urlencode() - return urlparse.urlunsplit((scheme, netloc, path, query, fragment)) + return escape(urlparse.urlunsplit((scheme, netloc, path, query, fragment))) # Regex for adding classes to html snippets From b5c98f686d8aa8f249aa0270f8ee0560482d9538 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 3 Nov 2014 11:10:24 +0000 Subject: [PATCH 180/249] Properly escape URLs when replacing query parameter --- rest_framework/templatetags/rest_framework.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/templatetags/rest_framework.py b/rest_framework/templatetags/rest_framework.py index 864d64dd0..7c914ed65 100644 --- a/rest_framework/templatetags/rest_framework.py +++ b/rest_framework/templatetags/rest_framework.py @@ -22,7 +22,7 @@ def replace_query_param(url, key, val): query_dict = QueryDict(query).copy() query_dict[key] = val query = query_dict.urlencode() - return urlparse.urlunsplit((scheme, netloc, path, query, fragment)) + return escape(urlparse.urlunsplit((scheme, netloc, path, query, fragment))) # Regex for adding classes to html snippets From 96bb77dc35a75df0fd9ad2fabb0f4661b2485600 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 3 Nov 2014 11:20:18 +0000 Subject: [PATCH 181/249] Version 2.4.4 --- docs/topics/release-notes.md | 10 ++++++++++ rest_framework/__init__.py | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md index 16589f3b9..11d12ae32 100644 --- a/docs/topics/release-notes.md +++ b/docs/topics/release-notes.md @@ -40,6 +40,16 @@ You can determine your currently installed version using `pip freeze`: ## 2.4.x series +### 2.4.4 + +**Date**: [3rd November 2014](https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%222.4.4+Release%22+). + +* **Security fix**: Escape URLs when replacing `format=` query parameter, as used in dropdown on `GET` button in browsable API to allow explicit selection of JSON vs HTML output. +* Maintain ordering of URLs in API root view for `DefaultRouter`. +* Fix `follow=True` in `APIRequestFactory` +* Resolve issue with invalid `read_only=True`, `required=True` fields being automatically generated by `ModelSerializer` in some cases. +* Resolve issue with `OPTIONS` requests returning incorrect information for views using `get_serializer_class` to dynamically determine serializer based on request method. + ### 2.4.3 **Date**: [19th September 2014](https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%222.4.3+Release%22+). diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py index 7f724c185..15b12d9be 100644 --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -8,7 +8,7 @@ ______ _____ _____ _____ __ """ __title__ = 'Django REST framework' -__version__ = '2.4.3' +__version__ = '2.4.4' __author__ = 'Tom Christie' __license__ = 'BSD 2-Clause' __copyright__ = 'Copyright 2011-2014 Tom Christie' From 650a91ac24cbd3e5b4ad5d7d7c6706fdf6160a78 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 3 Nov 2014 11:29:48 +0000 Subject: [PATCH 182/249] Fix URL escaping --- rest_framework/templatetags/rest_framework.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rest_framework/templatetags/rest_framework.py b/rest_framework/templatetags/rest_framework.py index 7c914ed65..84ba1b0a7 100644 --- a/rest_framework/templatetags/rest_framework.py +++ b/rest_framework/templatetags/rest_framework.py @@ -22,7 +22,7 @@ def replace_query_param(url, key, val): query_dict = QueryDict(query).copy() query_dict[key] = val query = query_dict.urlencode() - return escape(urlparse.urlunsplit((scheme, netloc, path, query, fragment))) + return urlparse.urlunsplit((scheme, netloc, path, query, fragment)) # Regex for adding classes to html snippets @@ -75,7 +75,7 @@ def add_query_param(request, key, val): """ iri = request.get_full_path() uri = iri_to_uri(iri) - return replace_query_param(uri, key, val) + return escape(replace_query_param(uri, key, val)) @register.filter From d27b8cc09b83bac10346effa1021493d2835b794 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 3 Nov 2014 12:00:19 +0000 Subject: [PATCH 183/249] PUT as create docs, and move mixin out to external gist --- docs/api-guide/generic-views.md | 14 ++++++++++ docs/topics/3.0-announcement.md | 2 +- rest_framework/mixins.py | 48 --------------------------------- 3 files changed, 15 insertions(+), 49 deletions(-) diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 49be0cae8..d2836fa6d 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -368,6 +368,20 @@ If you are using a mixin across multiple views, you can take this a step further Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project. +--- + +# PUT as create + +Prior to version 3.0 the REST framework mixins treated `PUT` as either an update or a create operation, depending on if the object already existed or not. + +Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existance of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses. + +Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious. + +If you need to generic PUT-as-create behavior you may want to include something like [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views. + +--- + # Third party packages The following third party packages provide additional generic view implementations. diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index f69c0b252..97ffdcf3f 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -694,7 +694,7 @@ Allowing `PUT` as create operations is problematic, as it necessarily exposes in Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but we've now opted for the 404 behavior as the default, due to it being simpler and more obvious. -If you need to restore the previous behavior you can include the `AllowPUTAsCreateMixin` class in your view. This class can be imported from `rest_framework.mixins`. +If you need to restore the previous behavior you may want to include [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views. #### Customizing error responses. diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index 467ff5155..2074a1072 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -6,10 +6,8 @@ which allows mixin classes to be composed in interesting ways. """ from __future__ import unicode_literals -from django.http import Http404 from rest_framework import status from rest_framework.response import Response -from rest_framework.request import clone_request from rest_framework.settings import api_settings @@ -89,49 +87,3 @@ class DestroyModelMixin(object): def perform_destroy(self, instance): instance.delete() - - -# The AllowPUTAsCreateMixin was previously the default behaviour -# for PUT requests. This has now been removed and must be *explicitly* -# included if it is the behavior that you want. -# For more info see: ... - -class AllowPUTAsCreateMixin(object): - """ - The following mixin class may be used in order to support PUT-as-create - behavior for incoming requests. - """ - def update(self, request, *args, **kwargs): - partial = kwargs.pop('partial', False) - instance = self.get_object_or_none() - serializer = self.get_serializer(instance, data=request.data, partial=partial) - serializer.is_valid(raise_exception=True) - - if instance is None: - lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field - lookup_value = self.kwargs[lookup_url_kwarg] - extra_kwargs = {self.lookup_field: lookup_value} - serializer.save(**extra_kwargs) - return Response(serializer.data, status=status.HTTP_201_CREATED) - - serializer.save() - return Response(serializer.data) - - def partial_update(self, request, *args, **kwargs): - kwargs['partial'] = True - return self.update(request, *args, **kwargs) - - def get_object_or_none(self): - try: - return self.get_object() - except Http404: - if self.request.method == 'PUT': - # For PUT-as-create operation, we need to ensure that we have - # relevant permissions, as if this was a POST request. This - # will either raise a PermissionDenied exception, or simply - # return None. - self.check_permissions(clone_request(self.request, 'POST')) - else: - # PATCH requests where the object does not exist should still - # return a 404 response. - raise From 9ce130d1b56039b0b7a7b04024f95c8c49c8fff7 Mon Sep 17 00:00:00 2001 From: Rocky Meza <rocky@fusionbox.com> Date: Mon, 3 Nov 2014 06:56:42 -0700 Subject: [PATCH 184/249] Fixed some typos in 3.0 release notes --- docs/topics/3.0-announcement.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 97ffdcf3f..f9987ad0f 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -748,7 +748,7 @@ You can revert this behavior, and display filenames in the representation by usi You can also modify serializer fields individually, using the `use_url` argument: - uploaded_file = serializers.FileField(user_url=False) + uploaded_file = serializers.FileField(use_url=False) Also note that you should pass the `request` object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form `https://example.com/url_path/filename.txt`. For example: @@ -790,7 +790,7 @@ You can modify this behavior globally by using the `COERCE_DECIMAL_TO_STRING` se 'COERCE_DECIMAL_TO_STRING': False } -Or modify it on an individual serializer field, using the `corece_to_string` keyword argument. +Or modify it on an individual serializer field, using the `coerce_to_string` keyword argument. # Return `Decimal` instances in `serializer.data`, not strings. amount = serializers.DecimalField( From 003c42b0f51f9bfa93964be69fb8cb68b7394280 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 3 Nov 2014 14:01:02 +0000 Subject: [PATCH 185/249] Use invalid_data key for error message. Closes #2002. --- rest_framework/serializers.py | 10 +++++++++- tests/test_validation.py | 7 +++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 82e932ddd..f00b685f4 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -15,6 +15,7 @@ from django.db import models from django.db.models.fields import FieldDoesNotExist from django.utils import six from django.utils.datastructures import SortedDict +from django.utils.translation import ugettext_lazy as _ from rest_framework.exceptions import ValidationError from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.settings import api_settings @@ -282,6 +283,10 @@ class SerializerMetaclass(type): @six.add_metaclass(SerializerMetaclass) class Serializer(BaseSerializer): + default_error_messages = { + 'invalid': _('Invalid data. Expected a dictionary, but got {datatype}.') + } + @property def fields(self): if not hasattr(self, '_fields'): @@ -339,8 +344,11 @@ class Serializer(BaseSerializer): 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: ['Invalid data'] + api_settings.NON_FIELD_ERRORS_KEY: [message] }) value = self.to_internal_value(data) diff --git a/tests/test_validation.py b/tests/test_validation.py index 4d64e6e11..1b6aa358d 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -87,8 +87,11 @@ class TestAvoidValidation(TestCase): def test_serializer_errors_has_only_invalid_data_error(self): serializer = ValidationSerializer(data='invalid data') self.assertFalse(serializer.is_valid()) - self.assertDictEqual(serializer.errors, - {'non_field_errors': ['Invalid data']}) + self.assertDictEqual(serializer.errors, { + 'non_field_errors': [ + 'Invalid data. Expected a dictionary, but got unicode.' + ] + }) # regression tests for issue: 1493 From 2b535954cdfb050f96588c60d45664b3802dcc25 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 3 Nov 2014 14:14:12 +0000 Subject: [PATCH 186/249] Py2/3 compat for validation test --- tests/test_validation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_validation.py b/tests/test_validation.py index 1b6aa358d..c278d90f3 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -89,7 +89,7 @@ class TestAvoidValidation(TestCase): self.assertFalse(serializer.is_valid()) self.assertDictEqual(serializer.errors, { 'non_field_errors': [ - 'Invalid data. Expected a dictionary, but got unicode.' + 'Invalid data. Expected a dictionary, but got %s.' % type('').__name__ ] }) From 0da30e6d1dea68d7c075067dd997fb1e0e26f27b Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 3 Nov 2014 14:43:00 +0000 Subject: [PATCH 187/249] Add note about 3.0 being merged to master --- README.md | 8 +++++++- docs/index.md | 6 ++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ec13e1b33..394d7fcf4 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,13 @@ **Awesome web-browseable Web APIs.** -**Note**: Full documentation for the project is available at [http://www.django-rest-framework.org][docs]. +Full documentation for the project is available at [http://www.django-rest-framework.org][docs]. + +--- + +**Note**: The incoming 3.0 version has now been merged to the `master` branch on GitHub. For the source of the currently available PyPI version, please see the `2.4.4` tag. + +--- # Overview diff --git a/docs/index.md b/docs/index.md index 5b31cc830..6288efa3c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -9,6 +9,10 @@ --- +**Note**: The incoming 3.0 version has now been merged to the `master` branch on GitHub. For the source of the currently available PyPI version, please see the `2.4.4` tag. + +--- + <p> <h1 style="position: absolute; width: 1px; @@ -43,8 +47,6 @@ Some reasons you might want to use REST framework: **Above**: *Screenshot from the browsable API* ----- - ## Requirements REST framework requires the following: From 21d06a4103d1966cd6e19f7cc6f3c6e450cc1680 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 3 Nov 2014 15:03:10 +0000 Subject: [PATCH 188/249] Added NON_FIELD_ERRORS_KEY to serializer docs. Closes #1971. --- docs/api-guide/settings.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 6a855c929..2144a2ed3 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -399,6 +399,12 @@ This should be a function with the following signature: Default: `'rest_framework.views.exception_handler'` +#### NON_FIELD_ERRORS_KEY + +A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors. + +Default: `'non_field_errors'` + #### URL_FIELD_NAME A string representing the key that should be used for the URL fields generated by `HyperlinkedModelSerializer`. From 78ac332f18c51bb151ae32f1f3d207595b0b3ca2 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 3 Nov 2014 15:08:19 +0000 Subject: [PATCH 189/249] Add docs on Meta inheritance. Closes #1926. --- docs/api-guide/serializers.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index a3694510e..eeeffa136 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -413,6 +413,16 @@ Alternative representations include serializing using hyperlinks, serializing co For full details see the [serializer relations][relations] documentation. +## Inheritance of the 'Meta' class + +The inner `Meta` class on serializers is not inherited from parent classes by default. This is the same behaviour as with Django's `Model` and `ModelForm` classes. If you want the `Meta` class to inherit from a parent class you must do so explicitly. For example: + + class AccountSerializer(MyBaseSerializer): + class Meta(MyBaseSerializer.Meta): + model = Account + +Typically we would recommend *not* using inheritance on inner Meta classes, but instead declaring all options explicitly. + --- # HyperlinkedModelSerializer From 09f3eedb235b476202cbd4e5a94b883898f3f661 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 3 Nov 2014 15:23:16 +0000 Subject: [PATCH 190/249] Add notes re view-level and instance-level permissions checks. Closes #1819. --- docs/api-guide/permissions.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index e867a4569..f3ae81717 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -183,11 +183,7 @@ If you need to test if a request is a read operation or a write operation, you s --- -**Note**: In versions 2.0 and 2.1, the signature for the permission checks always included an optional `obj` parameter, like so: `.has_permission(self, request, view, obj=None)`. The method would be called twice, first for the global permission checks, with no object supplied, and second for the object-level check when required. - -As of version 2.2 this signature has now been replaced with two separate method calls, which is more explicit and obvious. The old style signature continues to work, but its use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed. - -For more details see the [2.2 release announcement][2.2-announcement]. +**Note**: The instance-level `has_object_permission` method will only be called if the view-level `has_permission` checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call `.check_object_permissions(request, obj)`. If you are using the generic views then this will be handled for you by default. --- From 5d7b8356082e7c70f2723d1773c13125a4608dcc Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 3 Nov 2014 16:17:53 +0000 Subject: [PATCH 191/249] Tweaks to validation notes --- docs/topics/3.0-announcement.md | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index f9987ad0f..b30643c00 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -188,14 +188,11 @@ Alternatively if you want the errors to be against a specific field, use a dicti This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field. -#### Limitations of ModelSerializer validation. +#### Differences between ModelSerializer validation and ModelForm. -This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes. +This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behaviour on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes. -This change comes with the following limitations: - -* The model `.clean()` method will not be called as part of serializer validation. Use the serializer `.validate()` method to perform a final validation step on incoming data where required. -* The `.unique_for_date`, `.unique_for_month` and `.unique_for_year` options on model fields are not automatically validated. Again, you'll need to handle these explicitly on the serializer if required. +It's important to note that this change also means that the model `.clean()` method will not be called as part of serializer validation, as it would be if using a `ModelForm`. Use the serializer `.validate()` method to perform a final validation step on incoming data where required. #### Writable nested serialization. From 1925d465ae0c3558d6919e56ee753602ac61119f Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 3 Nov 2014 16:42:00 +0000 Subject: [PATCH 192/249] Call out 'get_value' and 'get_attribute' --- docs/topics/3.0-announcement.md | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index b30643c00..78abc5eec 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -562,7 +562,26 @@ The `MultipleChoiceField` class has been added. This field acts like `ChoiceFiel The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`. -The `field_from_native()` and `field_to_native()` methods are removed. +The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example... + + def field_to_native(self, obj, field_name): + """A custom read-only field that returns the class name.""" + return obj.__class__.__name__ + +Now if you need to access the entire object you'll instead need to override one or both of the following: + +* Use `get_attribute` to modify the attribute value passed to `to_representation()`. +* Use `get_value` to modify the data value passed `to_internal_value()`. + +For example: + + def get_attribute(self, obj): + # Pass the entire object through to `to_representation()`, + # instead of the standard attribute lookup. + return obj + + def to_representation(self, value): + return value.__class__.__name__ #### Explicit `queryset` required on relational fields. From 3375fecc8bf8f8ba781d952e6dd5986b947a7ec2 Mon Sep 17 00:00:00 2001 From: Tom Davis <tom@recursivedream.com> Date: Mon, 3 Nov 2014 15:05:45 -0500 Subject: [PATCH 193/249] Fix typo That's all. --- docs/topics/3.0-announcement.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 78abc5eec..e8428bc20 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -369,7 +369,7 @@ This class implements the same basic API as the `Serializer` class: * `.errors` - Returns an errors during validation. * `.save()` - Persists the validated data into an object instance. -There are four mathods that can be overriding, depending on what functionality you want the serializer class to support: +There are four methods that can be overridden, depending on what functionality you want the serializer class to support: * `.to_representation()` - Override this to support serialization, for read operations. * `.to_internal_value()` - Override this to support deserialization, for write operations. From 735240569733ae40b96f83e15e7a19faee3b44bf Mon Sep 17 00:00:00 2001 From: Sumana Harihareswara <sumanah@panix.com> Date: Tue, 4 Nov 2014 17:18:13 -0500 Subject: [PATCH 194/249] Updated book link in HATEOAS page Per http://www.crummy.com/2013/10/03/0 , the new book is *RESTful Web APIs* and the old book, *RESTful Web Services*, is obsolete. --- docs/topics/rest-hypermedia-hateoas.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/topics/rest-hypermedia-hateoas.md b/docs/topics/rest-hypermedia-hateoas.md index 3d7004880..4e3ccf924 100644 --- a/docs/topics/rest-hypermedia-hateoas.md +++ b/docs/topics/rest-hypermedia-hateoas.md @@ -13,7 +13,7 @@ The following fall into the "required reading" category. * Roy Fielding's dissertation - [Architectural Styles and the Design of Network-based Software Architectures][dissertation]. * Roy Fielding's "[REST APIs must be hypertext-driven][hypertext-driven]" blog post. -* Leonard Richardson & Sam Ruby's [RESTful Web Services][restful-web-services]. +* Leonard Richardson & Mike Amundsen's [RESTful Web APIs][restful-web-apis]. * Mike Amundsen's [Building Hypermedia APIs with HTML5 and Node][building-hypermedia-apis]. * Steve Klabnik's [Designing Hypermedia APIs][designing-hypermedia-apis]. * The [Richardson Maturity Model][maturitymodel]. @@ -37,7 +37,7 @@ What REST framework doesn't do is give you is machine readable hypermedia format [cite]: http://vimeo.com/channels/restfest/page:2 [dissertation]: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm [hypertext-driven]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven -[restful-web-services]: http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260 +[restful-web-apis]: http://restfulwebapis.org/ [building-hypermedia-apis]: http://www.amazon.com/Building-Hypermedia-APIs-HTML5-Node/dp/1449306578 [designing-hypermedia-apis]: http://designinghypermediaapis.com/ [restisover]: http://blog.steveklabnik.com/posts/2012-02-23-rest-is-over From 4d3831cae8753a1580adc23d580e6fd0f73953a7 Mon Sep 17 00:00:00 2001 From: Aron Jones <aron.jones@gmail.com> Date: Tue, 4 Nov 2014 22:01:23 -0500 Subject: [PATCH 195/249] add glyphicons font files --- .../fonts/glyphicons-halflings-regular.eot | Bin 0 -> 20335 bytes .../fonts/glyphicons-halflings-regular.svg | 229 ++++++++++++++++++ .../fonts/glyphicons-halflings-regular.ttf | Bin 0 -> 41280 bytes .../fonts/glyphicons-halflings-regular.woff | Bin 0 -> 23320 bytes 4 files changed, 229 insertions(+) create mode 100644 rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.eot create mode 100644 rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.svg create mode 100644 rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.ttf create mode 100644 rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.woff diff --git a/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.eot b/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.eot new file mode 100644 index 0000000000000000000000000000000000000000..4a4ca865d67e86f961bc6e2ef00bffa4e34bb9ed GIT binary patch literal 20335 zcma%iRa9Lu*X_aGIXLtH2X}XOcXxM};>BGK?k>gMi@Uo+afec%&=$Y_zI(@iAMVRd zMzYtMnVHGh`(bBgBrYld0G2WU0R1n+0{)ZW{#ye8Pyh%N;2)-_`hS4`dHjR_o8s?3 z%Kr!aAA=Sk15gC$0aO9906BmJKn0)-&;Wq`d1e4dfc3v(2XF@106hNnKnJJ;tp3?v z|4=i4`#;17p#2YV|JP~<aQVjr0oVY{0M>t*4IuDO^FK=e+xx$$?LVd`z~aAr@Bit+ z4B+|46aYB=Q+D{L`5%t;Kdt|aZw_GpXL0?v@B%pgd3^uI=KcSkIq3hHHvk~6A@l#d zDHwovCxFWvz!d;sGQ^&}h@CLq(3!MVaFhSyL!rg*&d8F%X_&hML`QYBTiRZ}i=N8C zfX|m2SCm$2B^?XKJ=3POS<xXNB{p2XXK+_wMOGVZnBZVi5e}6Y|6&<yQ)U%t_?I)| z$UxGPI3f<gbzDcS=uvd*F-hJ48@*B~rQ%a$ce$2W*h2m|CL*EzQysJG(21!-486pi z9Op(2E~L-}(eO7?`oQPh!vSmW(NSH=-))ZKL~;2xY%vBbW>}r1sVM9Nj*l5q`5#S% zQ}FD^zy1Pj*xUGOm4;*C;l80oktO?~%SdX8H^8@@idBFWyOINSr_!xo{REWRlXgw| z3-(h5XcHaEdPKzyy2-P+Rljn4lR?IelEOtWLiC?_9FW&x@kpuRtfsn*-QLS4E<Fz) zG9ld#Bnh;*Rbk?ER9!Ta)FqrS7@C4{EAs~A!V%DK>oN{{q0u8pt_^hD_!V);D{hen z-XpV~5QeQTYTIl1+B^5r72`!7FRQQ$Jh74=Gm*OkaIoNUC<v*|(E(8Aj*LvEM{1C? zyZ{#C??5QU&iBe&ZNxqGYA?UnmFg=wgvPZ$3)LsZ<b+4p4zbj9^8U=85Dk&+ntVHr z-r%wsOFM1J-)x^j=IMDx@M(3Dm-KN|ZXVOBlKmw$OFqyu(Llh8E3%Y~Y1Zon!|%`h zMcSPk^tyruyKs(okWegQr7FUGWbEIh%zF!S#n>7!wk7rRZVuVK6urnp@}QDpB~9*S zkVWg8LyXz8-%53>GXb$%*H0(bqkUIN`Oz8g=bse?bAumC8`5XqA+(_y{fV^j(1$BZ za*@mJ(&?Dl2k;8tW}O6OaavJE|17u#1t>M^0!@SDJc2)cLZL`m7!-)74CQUXoksM* z9m|Sjh}@dm-Tnc8<77&TfjT<DBnM~uOZbdpn&3nTeG7&uB2JuE_!o?tRkNOzP3&=A zEDuTrGt7%gwS6eHB2ZxuiO)~H$16mlbPgX8`65kyA_0q9Jew6Q1?oKNFm36(NeDbT zyoAZuFs$gjT7S+q9g&=H<@4}a3NYbc%Huc5)Gu8~{PLXe11y!f4`DxY+GU7$<OPgI zKA&H2TehO}XUXyf6XLWE)!&2|tW?qu6)DUjXH&lLih<2cjkXGyG^Kb@F}{FN`O7_A zha#<!6v2V|85wmU=0->6H{3)kXMM774`D!eA0|(<upEfJww;oFGKR9TK`B-XFHDiJ zgfovK8YC}?nt?-yJ3&V9yEw2GTcsxSag$w)zxt#lHbo&aNr)yz=t;gG@-99WW(#3& zouaUeY$ja)`Gzz_iZln>RuQz@iQO(4-7lX|aK*M`Y=f%R{_&<<ZCpgesc!3o%>*A? zB(AZUl6JXgz^9c9q7ZW~Lpncpv1I^6O4mGX@3P^Q)?jBgx(f#RD_4y0q5aC_beGG> zn%RbEy_vdx`sL?|Jvlgyxal-}XM^FDQYp|Euiu=%8o(=wic+XSimJ4(Adn3`QH6^D zQ}H@oBN{|Zg^2u|@8c~h7Kv&HCx??xy^J$3{B0{XnlrThDaoQqjXjXHi#b!KIjA7( z$hT;Ah_VP&j)(Z6&(xn;KF3rHsF^A#il?$)q4Pp#sly?|%OmoRG|MiNW3+)?3Wd9= zgbUjzTLX+!G&oYj9P;jnHmT91qKPzxkj@>rsqi|=M5$PfrRCY%E7${xLDZFtYcC%k zorpLj$T65dN+HV@=yRlKSS8W~SMxFkK1~U-XW2@DXcG`4-V)z|605uD4Q{MP10fD5 zc!T#)n57))zXXfg=dwnZuD_`DCJc3cHE6HuA(>36o_neqgoF0pRK0eEc~{rD8%Pfh z@dtE6ovkazKj3fd{)*&tB0YA^1d^^?2oeNyB7u(P+O4$@lCNc~%mb5iP)dLGM|z;x zEkRYM_^U`g%s5j<P^+nOOTy8^iNh+21HwPm!4tDZXyB_m{E__A7TT$++afF&z$%d5 zdbJfD%=H6{Yf~cV?+Rzx^RMpdNs;Rbegf65K#JCFs?Aj|Pp-_KSh;iZ)`&d5KF8sA zSTK1}bE2=(sOE}r@EuJD5`xOEryD%18G?xM;om|M5-F!#&|Y)1#1=-H$E8L9ld~*p z`={=|ZfPBqdY-{($JY@KNU3*2U3j;NB|GEwg&yTp_<`fG+2#^DECE%f(&>iH=8Q2h zlS%BdC6DaYEWi0UNhnc*zFT$fV`4_VMNU~nH;q(Ld?!#lIvm)K;W_4C(l3+4TZ=QI zD%siB%cY+Y7vMFM_KAg?sxm(^nJsMIV?v|vAS8l;zotv$#Ml-Y!n7|X5Y5C)=TiGZ zQ+=(9%lk0&L&hDtwRD=Ua6wQeS{g2mvwc>^|4$ot-2Hi`z)|V$N{mNAEZC3gw_8%z zq(L3Bcwr2gin62<CFE6*m7X=38JYv0`R+-1aFSbE%?6(FH>dXM8cG-D-auD7HayLz zJI2|m=8$F?Ko>v@P4{(W5g=}-b$%tJgfywp`6&A96|Zx{9N;1@_>hto7TQf3EIMm+ zJ`;@@4ycXnHM>|iJ?FXkWGc8YuGviO&L*^ajd+vyLIxAAT{isADQQM5S;YP+jAYp7 z3E1Nm1HDd%SXi``NR*so7XidvRPj#BM7A`S{cU%VISQOhrMLr08;N36AYg9}40Ml# zU)GUxQy(D1%P`@`HDaXn&%m8`hOu~_2a`%P{v7w2;KUNhll)N(y4wD#p#{+($uLOB z!X;K=sci1erRm1=Qcx#ja(r=E8*89RNH8`C7T4|#uVRc=Kaf}0Xw)>8g0(4H!ZrK^ zh-Kf(V#NQcMU79on9bk?`U7eI{Nu-CdboLYH-7lJI|7VCob2872$p->3n)-J>N|b% zIn3vzKet~nvHB=bP6rDRV|&&4LL}S7`iu2ok&r8ecw~yUROul?44VSV3;<PPWZ~5! z_|9gZYsa;uPFf1MZVUgTD4Fk3FD8RN+a+VIvQkXq2WiEoh9-D5rq2+~kYwFByFH0V zmHBgwt2=Um#HqKIE8^q*HOkzSb3#IJqMAe+j8?%H+JkNk9xlmNWT?fmFz7?eR#L2R zp($LHR$)v1K2`$HpZoUZ#WqP3-t6C)MpAtsT1cc2)CUfH#!oyXo<noD#b!SlX%D&X zhuWjVqw@fXq<RZa15$&L!{AKrHIJFY`&jXv7?sAhaU_dse&o*RNB(ip($=~<v#*(~ z?lmG+0~@igA~er}*y6#PA6I-!k;^$fAg#%n>z7qSQWl+y^cX=$j~O<Bq?IYYtt*Av zr`(RTVdzagmx?Srl~9;7Pzk3?abKG2R}WIw<Z=}$WIZ}_#0FlU31&cp!!iS}79B$! zH<OV9U;Iy3cs0)u>Q;o~0+_)5WDRF0^JbuD_umr4Mn$EPEyB-_e<pQ3H010%gdgQ9 zH0;sXO{u1bNMkXf4|e&kIYW{QvjZ>og^1*P#Ui}dCDH6-GndXgi$XV2SNHe#HHQoU z`2f{kT*~Y-Gtyd}I#v=*PbShJzp4hgaK>cr++;2GSGr7^2gA_3H1F;=<l9$`^knte zpQ^;CAfUc8JdE2Jgu={Rs`bMCvm#r_W3-mRiZjX=QJ@T*0UVz%hey|>06B{L4@fTs zD?F!vb_51Hnzb3BJlYiI4qZ5fDt|CaKX-N&2aP_DVX`bH*FN93cV*3fPvociz|dFF zDI@_;;4`*j9yW7pmnXjE<g**}4Sp!*=R~NKa2H(U*twWCy6bfcYbY3I%V(c!2|r{7 zY31<}TcSMa)NDLaz|=u;BON-McI&lS$B}9Qio7;d+%{vkxIcB`O&Byf=^ODKX}vXE zF{&$m8RE37?XNMPViooY02Ob3_b`fD>wqe@BEQw*5Kcl$=zJxCo$}$5>0aU8*UXir zlo6vuHSn81M=rz-M|tYukSa7I2M$#Q-7`8&2-+UvW25@8gOf1VSR}3RdVFr|-&}4T zky0u`XuQc%0#b=LJWu5hm&cbB$Zk<Hwb(>2FeYD~v-Cc92u|%sI<e~IKs@PAPBFWb zlR*CsinQd$1x+D9hF|0+awrW08Mg>Uh-6<!tT`|@EG}TQY7ag)w=g`+g5$LeDEOl* zhZ0f(LyYXxp_<HTr91$1QKsLh42R0!XSK4JDUG~Y=w5Ju2P=rh3jA{D(CfDrtt6bq z!!67fVC;8^+g%as8;~hF!vyz}g%6k#-(ash9?6;-)s}HWjB}Z3&?dxmQsg_h>5dJR zZ3)g?oGWe-H6(Dl5E)k2)Hal?$9R73FM9`l`qB^<^f4kuce&|T)yCo{^=_a`TY*c$ zRRh_284jJjLoW$Wjv_@n$8LbXuW0pZw;g`-3$XUHD0Me!pbdD8z$3+L^KKYOabFdl zZW8&J8yRWfjLh?e7QJEkgl<&QwDnZ2^WwgBH0{AjxI^@Q)51nlGRVgj8j^jL0%{L5 zg~N&QybX0(ldaaot?}x4%vuVeTbZ96fpg*k(_p?a+IFGn!YUuS;~_Z0CLyGFeQ=ow zhS}^5R4dLfu9Q@MFw7c5_Tg`%mq$XF81YXSFD~rt=E6o|lVBQmHpMG(*<)M(E(4f* zifS(;Yjenr?~y*l>F20zQ%mciliU45f-wznJZdw(tS7t6>004*2#X3Ej3pco3fi`a z?|gM_ckVQxZ*D!nTeU<CtC+)eWn7Cp-#HuV`z@+~X*h<KA_>+|gbdPEj(!rKUXu)| zkLqUGanZqn25Ek?PHa9%4W|%Ad_<Af42^|XZBP@V-(-P{AzOtc=k{RfE0lAHndD3w zCorJ5w>2AJ^C4ZsK(9AW?d?fe_y54j#ceCX7%ZMmS`{x=_0fcCjb0L>U_D>5f4kNy zHQQg5@4aYV)6gpTnv`z06M5a}w7=9Zxp`bcn&i(EOAPWj!?Z(2O?^DESnGfRDGcs1 z?IvJ*{LKonl7#robcFc@OJ<~_Nrt1&v@ePe#wEFKMxfTA!AwJm2~n9HG8Q3?YR-Yz z9Qm3kx|c48;)6Kyoo?<`!|@@xwp~u#ofuQm>ip4bLvO_8W)9{2phqI7{WR9NLgJ5S zHO8hXtJ(CY)mUG&o(gGo!3Qk!=#XUS13O&o{vweBJ4o1y<~#&5^$s69ECV9xM}=+2 z3!NJW8%Q`f_Ja)nexErX5!VB@V=TLVghSEjRt5vdJ8zuRg0R+Y>(Wb*7ED)es#R7< zyy<hf-A~;fzE_Vhzy_lJJ_hS5C_Fn-Ys8&4`90}V(U6AdcX;ahv0V0|D$%GVTo}%d z%`Xq11N@_+QTEFC8kq^^q<^$qHbz{`pXRyMV!^rx(?*Detg(%?lJ-%GNxD*UPY)8T z{zwpVSO1CZ4|w*uRQ(o0TX(GnCrSa6xB9WZTTVS+WF#0<=gQ&#ApBqkhtln9(AI@3 zPaBm+C7>j>az=m}1XQ+E7Z@KG=Cs|{!+EejQ_B-7_Z_Y<Xf-uVv_(PTS2Sw=Q4|;& zgu$v5i<{QHHtZ<)O|z_n0Tow~R##jqG)Ko>;kETxVVJOayFzr&scDu#RzsdT7?ZD( zjt$GiPqMQDN##jNA(UuHMgjopqE;pkUTep+3YhG2G!BnK?~X#v<ppz1GopVhVk~iJ z9)J}bWR2N4McPD8cAjR)(es%iC15{NvDk*ur_>(Hh{G+w3pu5aBF+5$)Hq);#9CbG zsE7UhKwvg;w*V(0K7kvgnm5CXt2oMK#y!&dqW6^CO`o-9h;rpe8sX@M7vdNHrSI)y z9KlvS+@+-`CzlS3h}P)VbJn)MN&1rZJDgsR=F2FHZMpd&S1VRKi;7W;=|X`v`iwr; z6={w%x(Bj(^(a<%?7PB*S%}>sft}U!!qdscsQgT@3X5WihmLBxuS7?1$@SvvJ3<<| zt}Y%yqH_W&6!_(na-jr#Zv7W*Cu#c6Hqr$o{eMTHmIWfcuI+rsXc1x$ibc)|lxs`| z^lhQp&^b^BTL(xEI!6k8bxom-D8C}+6_a%`?CYjSuFcEh5J1&Y`Z-6Dj-I`%()n$9 zg*b<&Zs^xdC{p2ab~}fxiuobr7XT7pIefDq+B0S-e*#Ncv}xLJi{{yPWu)?Esyu0; z1qsK_FAEg-C+$p0cp*xgs1s4btkM&3lqqeQRpD2eomd(OP0Q@*e&Xas38amh5^boC zOw$(pnvN$4MdoQ_u*a%EGU#34!L8h;hCq2qu>vma`dr@6OJ$uR*Uy0|v+9(q#{vUE z-6#WJn9K=D1b|=3z9t2tlyis<332BeH7r+zY@~b=^WA5yu<fPm7RjBbbuqrcXHVKv zw+nPMm=KzG8)-dK<z$0Pt6Ui8{T0zsuyDZ}B`O{xKE&IvZtp6*up2w)J@gX?S9Oqy zCS5`6J&kx=5j&$*J^v(F;@(WC?74P&!ks4Yd!<9(*N%gDX&Bc(3)tLgvT;OY=1_7_ zj70d-6D}2OF$6th?$0z7wX0p7u+;C=j&lCgh?r{D&rp#NcC$1?MZ_dJu}SsqkU?TK z=qE|t<m4~g{3P3t-VJkRb}};PpGkMyk%<t0AF^a&-6ybu*Hu`lNpdM4WcezZTxb`5 z-XD9Yjn)34Aj}!N$N3;qy8Zh;9^Fq^`$_SV^f`B&XF-t*4w<;XH?t?0elq8<A8Amp zJB%m<lWH91bDt*zIu{w2eg|zT-NtNe$TFe0H-^%;M}@;qR(|m6^w76OUUF<!bkYMc z^Sj0z`C&>vSMiyU=H97SQ7PJ=xDq8^5h@!5s)7NwIC(^9c}UqFKh>XnFPu|+L@P;S z3sSA!`G>+GcF}A^nfl|n_2P=oi#0>A$BphJo^niV$39q>jBn7=yG3jodFC|0-)C$R z@AvsPawzRcdI+N@#+XCUhE-bV6R(fb0#L8<{kZo-bBF0d_eb2=Oq%CRy|M%BGBmTi z*(vF=mDqfB)Ffbr1WObL5rtaXXn7h$vMIMyd!!E!)5Fe{yHa{ZKHpGwQ9J-@cQ$OX z8Bux&6WJ%|zF+jJZ&(g-&u~QV-Y_~q?DJ>#3~9WiBeIU_uh)eb{b{VUn_K9kFfYXL z#W?5L8z;XrA?Kc&ua35Hi_uhWghl9)h*)J}%wG+Xnnp2ZOl*YtK3VQxUMfBM+z>E2 zeI`!tBDijjXYxlLEZu<O@O=5)cfidSSht6%IB`qR^SRi%>7t_T<~!mR0{o>6W*Ejr z6v8z^G$W!dDq*^y$WbyhI)x}-s>tdk0<Cc3ioO1pJ{fP6Y(F$trRT2*j0^mu@xips z)8yfpsJ|GZpA*8m?W)5OAKs486ubh`#8%{HZQ7h)9%|@<)1g|^V9S{Ud3i&m5k;ry z5$istivD`~Kx@|!1j%2HedK9<<`!dy4v&fNjAM1C$4sWcKL@Zey?!dG<4WO6w{&}5 zgKHE4{N%dHQp5v73Lb9fcx$k|yQz_nf&<E4Cf8EsIM1uVvPU&jMv1jo`rnnb>{-;A z91U?k6Rg*%T*U)Uv_P<mYJ~IjZKh?I?nr?S?oQgvx#teX-mCJ%f4hb>P_}4jhJ6|~ z)$B}m4(d`YtCBcrVbz?cQGo|NhMK(@OnGsU7<Jm>OAKgUB<ntwP0|xtI#IR3rhRUm zB}lRG%Hqg|8^>JLh?E@OO@sfUG8M``oQbcDgDKEy^t6!AhE@HqgSG<3Q{ND7tH!G1 zQFCZgl=Ykxr~0pdq)`n2y3~Y0cvkO5i!CLTAc68-9cOMi2c29BTcg!W5=XzHR68tT zH%o4w$B?>YF0Aq0w*Q@DIf|UyjajcxO2`!Av{p;s2#z_Xfp*{$2fM>65~br|rCyhX zcrN@r4!w~3imlj-eew7qq8d&vtYnSAT9&|&Y&=~}zF5=-5at@Gr1s6~`eBk{nJh+@ z#(=xEI>c6xXU(ucS*a_!ww@WYvo?~@3dBjqAUH~h9mW5q!R#);8l<ku!%jS!9Y6-o z`uOWoJ&>%8+oJnb+-ydqv)LHQJSgY=p%{@~Fk(V6=o{<5fV>)fPWOyXSo|G?G=*~> z?z><)(Ss@<re!j_43?Cd9-d~0STy;Ikqe~!)>lE|vU-2vhORxCM>@LEx4O{!kmzI5 zFUOuOX^BHASj%#FATqS(FnqPTp^|Sq;eg3wKvIzUJ%FNpoCY`^OPv(^>&j{V#RFzE z@3Y)bA(4m_iaS`J&gG(v^)Jth;W$iESCeCBA1#B(N63V{dggoJ%RQn}c>a@^%gazJ zI$Shg5<N22t2lIl;+e)HfO+hN<$(&_ug@>yVpcpnJOOWY^dBUI=3iC>#a1p2NQs|b zgZHukR9HwV8Sgp{#+jN7ZB3DI6<m99=;3fkN{smAXFJsq^M|0vAEBpFy_o0U=vD?t z?zmE8_}ZmDiu0CYKf!?6jGmiuXjf_hP<2fs8IP)4%~i1W79743#nNSJ&>~hIHv@&% z=$?K2gzM;xC?K<9N0|-BMSk4bLI)uB*!ugfY0qP3R%y5O?&{Xfzojfbw?zj^P+_;e zRVm>&GsN)=H<Py%__i1^7|tOxuE&!af_os_K8Kc7^4GqKwMnuX?hv?wl+viMTYHy1 z?Xzc(PF<I|uv`C8l-?8wk8jGK;dR!zb`y5%6?tXlXrqPk_62k72ki(<(YNuOTrNj! z2{9#lK#um1_upuZc=!#Efe)@&Et@FqiEbt6$IpFhlCiH1Gp6VMJ(1r+i6Sv;hob#< zBWHJD^gTk(__$MsTj}G4^QARKgAd^4W6~cYFvhAmio;J&%K}-3N%2UhHR{bme?<_V z<3O}lC#vJ^*)+_=d4d+GQKgkUzBbI~h1D8#2}eLNbb<W;vcdQ3dBlXk4qd*5P85k^ z^<d`z@}nh%>BH+0BHxJo&ckuL8w0=_w~q6R{ghxeMmsDh;9@n%VFE`Zx%pQglC=A4 zmJFxIgNwqP)8^b#RwBGP+eI;wi}{^<jUT6)>pYMTtQ4h21k5DL#G?TZ4VCjrqHlXx z5GWyy1)M+9Im*H1Nb!*p1miCdMHEs>^!0KnPX60;FztLJwN}7vh;E>|7i^aSKwZPp zbmc@;Z{n(|)caxrl1<CFphzpY;P}JW9V&YY%V}bcpLg7B{&;!0Wku&3Fh)b@+WPh3 z%uyrV0vM2R)&++)NU>Z94YDTS$mif`TC>B#m4S#$l?uReS>1@v!TRjv$vg^osFiop z3Ec1yBx|_DM8|$B+gdt2+Wo8>VSiOZMk{KxbsETEqXrMe43bz3J;k2|bk1|VfW}}N ziBRxsE0VSSOf}i%^gY0FFMldwBHt78EjW?Hs`TiH)s0WX#E(VMU>!x(pRNEl0?(%d z(09!|c3J9g+xi&)MKNr%Lz~VacC(%gKWoY@ID6_>a>(E=mVmuqrKtH5d$d}xX&NeD z5RiuBXo9`O{xL>+V-49mRc(3kT+>qNP814Xc&F=6k?M%@t6NOb@@_X`d3htI>|zGN z&z3d$7^TV;cV+eyHCzB+pyNz1atbYX3gZfiSjHB<0Ehv&M)7xxzlJu32@Iosx5?qd z-7Ka#WS9+1pr}6b%d2z-ZT+Fzpf`63fy)jTb-|y39hX-WFKTi7kn^+4(;QJI%l!pK ze2L!7r+ad0PfD2bsar6XgD>XWJxwwoHCORf9r0VEIM_<BWND<pEI5=QaS)gGF}@1R znH|v!Z&(5!-9pejNy+g(h8$6$1Y__L`z*OvF2iqdO8c)js=PclmH;D-Cnm?*f^>qM zCzw=0@8aB8TV{tjzE5zvR&0MR>so`xq~rHSLBuI)mS!Dh1{CI~)~Nb^?^R@Gb*0A1 z=&MnM%PG*qmrKBjp8ZIYS@DFDNwe5Ww=2e65vs{7<p%KtHF2F3Blir)Z<5b=;%pun zKrxw#sJ%83soGV`tbKALGcfhXP8-ZWTi4{o)mVBuvW!BuyJ`KPLF439_<%%#bA7Q& zp72T9-<8K_mT$v9&)zzxLEMqBt+Tz5J=bB1W1Otu2VF8Vpl>e0?Ou*xB{?A9P$i{y zM|4xJ3)%!G%8d{u-AC5&>)0?3EeMgln4Yut1`I~s-Cl*~G*Ri1k>5}JY295;&pq@- z#Lm^4Hp$Vz)X?2y^sW@;*ClyG-%gBU|LBB2+bG$zX%YcrI$cSa$$Sdz2EBDDiX$!I z{_-)%I3e)hC3KOBqNUpTOsPtReVV3GD|?sDzlE<cZB*G{Ydue?ezLGN{6bFMbmW-r zw)Q*vo+foQLpFc;$L~RxkCGuIY`BhQDYOu%dzULfTnIGlI(s4wBDp{&G1YN0HvYt} zCpFsDioRlY8MeBK9Wmi7dm-f)XBLIb%nu6Pv{6I_7UT0ATHB|WAcn{TC`PxUeWV-* zhdK9<bP{mPv`$gSdL#zbV!LWzbq4pNn2}y&iy`ogaY?A!C5r`8Jcp0<Zw)3EEN-~R zLLW;)Y6+&JsViQ4#!(yp6a<>Y;lsV>UYEWf_58h)t*RN0JkrGu0p9p8L{s_RPwvTR zXR9)eJN*RNMO^RZbZOXGNdieWgVSs&xvqTIv}1x>vCDtEk6_WWAVXu?Nu7sREv!;U zh%KMgdA}u72`Xz6{1nx8ud@3we5$9_>x#f2Ci}@h{1$Fh&}3<tbk38~&rUa<5)0^F z^Qb;FS*o<SguKe@X&a1LVx~X!UMwbTR)aw`9oiQ*f`d)}`LPRR8bdG?2mL4>CiF{d z+}gjEHbU-5+06vi&lbqcVU4dKyM_2lgko*<ReACrRdJ>2LU$@58M9ER0>@8%8{Q`H zM^pmfKp*!)YkLi|P(GT%H`-^=EmrEUhQ4I?ux{(gb8Cfs3Y;=$r!4-O%2yn10(6sR zU6x<wcSlR3=Xy>mo^&_$SnfCEbTemLPST3#%z3J!5Y}po{ihZicg?6_ADfUcz?o1} zmJxCzhnNT~o!=vhmRTEXGQ4OT$Zvhr5{5Midj2y-p}oGVqRFwQiNxp#2-*sjF6fsF zV6X<GK@F!wePUU;7xT5>hhsSL>wR!QmL`QcBPeEpof>)1LNkZE`AL+G5)@6qC>qR! z8+){akxki?kaFfX6i}pXp_`Xlck94~S-?9*q=QqL2z=I4B@Zvi@4?yJho3QIdNI8l z#4QKGd<)2;6Vy;X#e*x_gP*hHWyFFgqukOJH7ndQUKry!7s+}S>|FP?VT3DlK1qQQ zk=oA%rP<Di#}0$a?hQK@^jNC2+{{nOa{1-JuGN-u{`9VO-+ywu6Afn5!+)vInz}{! zBl0(x?R(%zB>%@u3Q)BH<r|^Paa2MPE=FFo3z*x4C<&P&<>2;)Li&oL3#M*r$!{Ih zASM=(#VCobo1BhR#*@dO*~PX)#gN9<0l;rNRKG4|p!^Nocw@Iy>-~ZJ?0T#CqSxD+ zevj?m@H}89TT2L<6HsC#BB(?}DykVK9k*1%F~}N9y4KadeB)RvJq;@3pmQntjRuyp zd+bH2w#~~?gnNl>cBMwx5@vUCsl~4k*^~r4aR!EORAjW02r1eGW<}-vIl3BCwVUEw zh(xbpj>h?!;M4gDxV}8^il-Ur;r34S_`LeD#vXa-JKk@`B;%!=m}ILfo6GC<dZvO? zS7(QZPL+pBE8);iH4PKjVa_*y6Zt2g>RP-vnwGMvS1TCwL(fwPc-To}O1cyV3K?4x z{_{<Fg{d@#rjB5}AEg<^=qEQRpIA97HMxux`4p1VPC2C@z2faqsTOl$2-|+8kh&a3 zbrd^IFP)$co672tU{8;er@;7LZqm#|XEur)a+_u~rnVETrT<E4$EH3X^TuOrTC%TE zc@b^#eTC{a+k)_}X@_ugF0$jzW7TGbtt}NG>-<pm*;sEvkI76dH5uivPuy+3TYCiF zwZQ^BDoqoqsG>2*jZ}zOd{hm(Z%1afi9LPcXUtDSf?C9Eh3I80lt-6uc=&~q`FuW) zKHDvFXfegSj8LcxD#zUuF<lZDwF2cd8MqiH=n+}$F4<UvUKgt0VO&vaIwj!MS7uhG zACQ5QGZ!fEFC+eW0rja@5v|a!zf3zhNh5MRk1)K$J~DKxqme{)-x*>PYuggI{ZvI5 zj|TJPpX&$cTSpufZ23uYl>m#4Uva-%N<10wTI1Mav~)-=p+fo(j6RRxz{*!Z9U-)C z9>Fg)gf&-?LrVVy@(_wx>%nb~#fWvMjZ<K2yhtV7T(tpP?anusB-trf%NM~yT`jjT zXZIu<$DGmp{vWQ}{T?~D<8bi6D`5!o9MLFX(azod6iahGu?|%r7YXp_25ce!<7I+z zdr{_0jli`OqO(qQlE6cRj6Z@iI09z^i-FLJf@3klwfN=mcKQ$BgEcHyT&a6QkUR`R zU87{V`XVeB{1EP08nE9gEL_AOTa!DXuz4Kb$(mQC+Pxt4fxasUtoF&`Ad)0uD`_l5 zK)gSH0amD9$|PSYwtfin-1grFUYRKfPB`eBpeP4ty`~H#JB8TnnzwZhx6zx_dgbFc z^{$LTcfHng8ZMPA?lTjHuBs>~3snIE4PjYc%6*#^HD>*h`@M=No(8gEO?tGG;DGL! zIknN6VVIpLepd7%^9kPQ=@m~$#G`d&22uBd7N`xiP7nd~8%zL8zY7$6HJXuC?e(YU zo|ZhfFlXWkh}8`aNOTEuicNS}80_)bI`FU)e}Gw)H(>SGZcAB2IjJ%f(xjS0D3g$f zpKWvE6C}I95gE5ucsGJw!I(^u@Qq2m!}b62JC2|pO%)yPHM(i^a4hL6s!^uhSYDQ( zs6-SU+3-3w$KoVN{lR=H^hVSP#<mTjt&w+5$(ctAUFxIZurQIiFcp;M8%2K_=Jv?_ z>EnRfCNooS9%oP_bri+sHqLwpN!J;gB#HbCT*wP$kPMWfp>3s$!F>BG0nI}(tOBcS z`;|a~gZLF43#h#S#h9K<bvS-?439-?rOv?zBZqMoDO)8m(}QWECutrkfa?*Is@T<O z_&jfAiFL_!j%tT}KF9GMHjvg-?(sD}e=&tm?rVzY0?dj#$<o98aBEy#sGWl@eCQ&< zuX_2pLGi*8F6sN!-M$d5HTXuHH7~<mrr&q;EKpi-9-r4=cadSsugA<m_$nj)<xVdu zgqs&1m0`|;+JE0lmQkS{2ZC;^gkmx&$+7`Otgu0UZiHf~)0;bg(clJ~R1uB9MW@DC zS@iDss&sLFhO!7{zhcsBzjs+@Tt7;tY)Og!98tADI$YXMvWgm#G8*hgxmNa9fI*96 zAZ;`oqa`)sTa&j`De_`tYY^rvf?alzBdN*1Z(|Oq?^I;UU~5GJs2RpVO9_Ehf0fp$ zcg@T0?@Ov2V8mtsTu*c{?^jA!5T!4QcbYZA&ul|HG_K^p2({}{<g=QyIA6z5t<d%Y zpo8Ici{k$tK^<S*&i#bS1t?OxX@XYVA`!?fOl@4jLKa2nq8w9Hi1`ZXT<{1_<QZML zRE@b95tIwo8q>-xNW62tdPsD6m#K0iM?V&GbYaL+Tv1R7X)gj~#SmUb78qLnlqoP^ zSe`gkIP@zojM0&GO=h@|U1Brj_A5+?CK^Vl?qgjE)=Mo|Man|gckYv`pkbSNoKK!l zI{10#kbR9{p%uRJ4wx<2MtMI>or0N#cP<&(WR_(NRzrNObQ6E4VtUzc?fH?Q`SmTe ze9vOyJ~XZ1o3+9UPw0YlgJEIwL%gBxaQO=tjEqDxu@8q>P<_RrX#GyAh7*w=e!%zM zvmm+X4>-{%3kZ>L>`>A9e(Oe^W8*8imEKjvrX~B9Z?mF4pdgAW0GcqQ8K?PWbOtli z6v1wXRcjUM?UkNSiRv~-lG&n<e--rauQ9#NC1=FP*xvXf62yZe-(g1=ElX!ljP>=6 z$-Xti>!AZ`H4B7vrP6?>0{7UrywB2v>KcE_pW4LIO&E1X8z-=<F0PfslW&!6IV5+! zqWqqqE?X)B5Y}b&<wa2KA9JTXGe<G0ugB@Y;<ejIkgztLNM19ut6|sb_HD8hD#9IR zuZ1RpHvx`Gnn&<8O^IGc@VgbIQf$R*xJF2K2GwkBQ*fheO4?L=A}&V`lHnt_b~1QI z-9r|Le#_eOpb9T(7PTra#Um|&-^9k%7*eo6v7!P3xFzd<lp2A(tqAu)E=A~N8iM@H z<u(IP)cNtI;C2d$PE~U?M$<m<v1xYiZopLT<`<Z*4xM#2-p4g8L85)ah@e;S@HNA| z=Ol8NurlG_jBO((r<gie1VCws6;hKp*WIM*YybG(ma>J<qFb_5pz}6L?%UnRtvEMt z$pjZt++<)(td{kmU=tnslLn^wky>L#R3C|YNnMkc!*60bMHvnH<`ilEG%{J&Fe*%+ zjTZG$y6;1$L>`qR_sp}wV<hTsgOfV;QwuVw7e|k8cB|9Nf;n9Hbf?HHIQP-fE$pV1 z#JkN^-|$Xv_HeIllkdMG_H);mUPU)3zG7&CNP!iDh>!83lNr^{s08V1fY$}RtDBk_ zY{PKqIRP(E+njlJ>;-Ne9DTE9Yc-7W#!7e7F3YVtOg2yK#&M<)w#4K*c(bn^FnHGi zOO53p1ce|18`isRiPy2)Cp&cXWCMewS7U(<3?fr$6<2fP(VAkoOk?Mn;n6cy6eoEN zcTNR*-IloNR3v5#qTkK~&Q92!hf<Hg;5*feGaQW9#5h~%v>f@mt5?U>fQ)(sn9?kZ zoELH=@&o-m=!`QtVP*4!Zq3MI*C)c*169O@A6{Sw1BrU77bX<7)o+B=OKOT3M_qUu z)G%1v*Dw$3!{WTWe}2o~d*W7}{itvohqK!zI4HNk!NALAmrWckmSUmNsWC3}z589I z?(Ph?T0sx*T5P5eOv%MYbRzUJ)6Kn!@@StdaavA^up>Bu#v(VH%nlM5iNgY!YUrMi ze_F{-tA~K?Z+>D_Z`ea`+x(I<v}`yjSJ@f>5S4r<h?^0#X=%Wal|me=zQo6%Ws{Zl z=}+-u8|cSCJ!T@_UYH<%$YX<TRjg$Zl<$DRvW$!jEr@(;cl8%tv5L0M$dqu_cE`17 zMI9u>c!$&2G#xZi5!P+od8TU36$-U+2lUz(G)^M=`)XHCub}p+?s<^N%UM4vVLX!W z3!0^;2XT5crok6h1={vUZ6hmQ4N20z`>5mfN}W4i2ah$KgcnPPpEs_(#;Q{)27f<( z*y2iflq`qB-OJXu(8w@R=)->-a6|4bNxNMnft?20HkuCy$6$L09kd)G)W4O=9BM|{ z0njynOnyNaTVrFARb&?Wz)KO0c=aeIrmJGdj2T21U*d{=r&%WGB_fB}!Crdq%$!h6 zTYHZU91PZ_u6~E*gTy3XA#JV7W1QF6sjN;@hLE{nCX07QHTpvH15PaG$-!bfNO#d# zL<U}`Qn>z-yQ&tSY!D@K{1sPCqy(XopWKKD^Su(X0yAdtrAPbwvb;0KzwfBiTWK|Q z=@~d0^<3M_hSR&Ce?AW}16N8iRRYrnJD8B8G!k~7@GQoI<#32mT-zRtY2CpF2f(XA zMU6CkH@0EN1UN@jBxhBao0Y7;t{jc1e4a+0fB6N7b2yPo(8A@@2haBnasAf%nJCjH zql`!qJ9zbokA$A+Li$D^=r%*k928%W0a#o<gs&`x3@ms*43R~6)ynuL*qETxc54Nv z^pBjRgAQ+@bKw`5;mQ|kZCg0Gw@KQe)8%EVGk1lJ<f4_oO2bud96F<Au}P+y9pZ5_ zadu@Z;OMTx@X}Sm_JkwiZ42|}V<KTUgwsLX9z^4Jf!Wc-X9FRs6DjJM?42@;z_eC5 zUJ21(owhni(My_rYDNMIf>K{oyi-%i#({q!i0)WJ1(aFJgY*$gn{8I=(Ww04qI1{H zye0i*Mr`~uq|h*1yj(Kb6ltw^K@0a<ye8X(oRqDde~yan6YYyu-Fn2RK#X_5K=Ppq z-rpjOTr`I4OJ;W(>m&(EmI`#hR*0ct8#{B~3BSz88+3Bzg4k81*^8%KE#*02QR*UK z2M-^JFu#z+ux)Gj9-Ypn7I{$oQ)oL1`l&|nToNk4Tamb^hRS)nuoZIEjHOtFqfhay zZUTan1jXVWhNrTYA$UlLl2*5w4DdkB`Zffs@;~cY=26uyjz?2T9bVi&2sRpcJQEc} zsw<xl^KlN5{CdJGgdh3YfK~~bf@i6+a1k`1n_L0^rf&!;tv*PXSF_&+QjFzMV+z*{ z3z<A(vf-IEV-EC<-lk{Xp?}FhdX1TA65X2fDfyy*7Pf@qRpgF~XW4FwZNf&>q*+P- zDN^CmeDw%s_1+%}Im49+!#OjZ;j(Q*hfk#Bm}vcixtLUk-l>q@`BV7ppOrG2W#Z%& zW()~2c*wbgWlG&}uVk<U0$Y?beTsvTbSNqYPCD97tBNC!-8~e57?YUrlBx*ZLKn{g zcBPw`%8s^Su5C+b#GMET{v_#pq(#hqKNXW8uxJr!mWcI^<`7UR<IWE}EZ{43a!Oy) z$w_WC9xi}v>UND;LEy@?#C{}77N~WYzz)?Az@B@SyxF&QfwgRVOOn%0aye75&&}>S zzXc$D2{D5sKzp?kZ^aDn`*nF+3|f|e(o$M#yR)s_4THwu&3vi*JPwOBR)%9|cQ^)g z4XHCFEsKY{w1K@z=AIAvPKl3~tb_^UIhBwmBDl`00~fq=Sz&xh<>PA2hJCH!hGwUW zSgtprf2*L$jmE;I<{4F(Ggnc%YAXfr=SqhudnSKgbgU~un2Z{YIR{ZU&<I3x!^_iT zd6J4u;Fn@-WyexQ3?V<(Usett3C++vK)`ux$MaZS7UG<_$O=<e&c7X8n$ReU`wY8q z?n`O;^Nm-AThR0xjbj)g0!weYObHM-BE)A+;z{bkS&M>6?3OUcSLAaY@eW`eEgpt7 zlUlHem*R=;T?P@87+ei=K*i)c(`M7rgYp~;1v3UAroT0zo2b1J>$(E72e7wJRJ^j+ zfwa{lP}t<C*rwUgoVd5LVnEn5EM1ks_wbZY3vFSs=#|3cw@9}Pkfq3AF7h7aR#sC8 zxsEs|MsOzJ5XuyRfK3#A9}Un2qYDGT3x>eWV2Cat(t`GRp|FvPh+q_fqDrDbm_Mgv ze11tcDh~Zxw+#nx2(x{He?+>B8}7!V`sarmVDe6{$$s5`AD)NF!*)Lkxhe86X@8YJ zUKj5XynC5Tkh`933miE2XeIrq<MiFpQF2nV|K7lzL|8v?M%9Tq9N#$?4}FL6Wg+_Q z&7!?a`a3PR^Vppce;!n(2=H?W$eoi0I?xqdaa3c^+-`wjPE~=QkHXl|{#vtX@JW?i zB5JNRT2b-_T&XiT0qbrq6QHR}zG^P5NqGXJt;oz71|{K&DhM9Ir`H>#2DMX^k7QLZ zL|1DDSCs`<i3V58E^0J|R#1$}OU0%k0x2=+r9qmGyp;oHYM`NF)1jh)l72Hdzrom> zP~b8wgEc_A<xbya)Vd!S=|g{ht(CM<-QT2nCjNC!N<IKNg$GD@Nl&$+8B<w#gr&v} zT|6x%)*c&N2fT08Y3}X<u6EZ~PF0uq^+nk~V}Ct|FYMzCJSx0V+;g^m;m^E!7peET zY%Qs7kF6Fas?fDhC$E+Ztz1K{)updBt}gJdy4Wh$u}{gb=J&2F-zq+{58J7}cCO*- zu8FL!(66?!uhPpYYqw9>KuOkS68=kJJcC!<yf)I-%phM1Am{Jw6V&AVcK9geu!_;3 zNztZCv>LEhv(jc*PJc+JDJEZntc9XnDeon^R1KS8VypEKVS=!F?4_G(KTNE3yww1& z<<4Fsm#(W&-EE|$ep#8R2{KX@^9n+)nbR_CuKu2`y-?j&_Et#qL+_J4;tN=2WAJ?_ z>GAwa1Ld2`rz_J{-N+hUE`7D?$vACB{U+#Df4rK7HY2#|H7ad3`gquCdhAM5`64&^ zml&N+{;t8*A@sURFNd(28=x_y`ZPiZmZ*JTwE@14fXfD|h6GL5)jmGBn&D0L=Vf@m zCfsvhVa?!2*QXbkyXRHMl<ZCH{j?F+zPGq&hEgSZ&=(wb@UcLs>vIPVI=m<zbw(|3 zh!~I^EDuDbU<H%>yUYfFf`Kvx;HNNg+~nfLnniq{U32A~2`%1Vz|wmTEs2e$)WSRz z)ul1TY;;WAQl)z-Kdg2cN`8In{^lIY0O)kQ^I2SoQWf~F>*MJp!pVm!TB9y-tC8z^ zo;bCQ?{j%6p6`I;Hk8t!SYr(BA&><YJPn!Vfv_1bci>}DrGx<Rk~V(OXz^s~%l^1L zNs5F|1DJoS9X=rV^Ei{UhI7Sa>g2UYggV|Zk#`Og7%@FQAPviijGoxn3uBn010T08 zQ!nF<YbEU>ZtP~|hjSMd!(1+p*Ez!^!t-}`5!<GW`N3w9{opB;L!0<0{){=Qf0!sd zdJZ21P^{l-D9VyQS)>O{-R&*GB$6p41JkhO#U#<lJ4wKTdjsZpyVjnYBjmC3Y1Abb zL}+_=q^VTKFx|qWC{qo9C!}CNsimA{RMI-G`?I>f{uNj#66xGL$#dz~=tSkpT%4i1 zgjkQKiEa<V8V&OZfnTe+HLLN9bvb%P5(qZD6th4Q4psZS0g)$^JCVnlr2=1=B^pnz zHkEjoK!<?g6-lg*C<~Q_JN=V#vDjAEP-wFaMHVVaIw_Lp@ug<v^HP_jA`H=G{$EQ` z2?MstlR2dsX5Z5S-G4`oWRj8u>nt8(H)O7-+8ZSoA)7^JvjbKP-NF5#si838FETR9 z{>F}aEty|AxCF?_9K2a!PCD&{mLIaLn~rY9PkVlT{$&jW-^9L(DZPjb!3!(?6gP<p zSnHDlJ|Ei{)+mi-zA8QS{Uldi*T{fvj~1f;;~TBD5&0tcY#q@+SKR4<>!oRptb@n+ zj;Sj1EzP&rTH|dsUF5T#cGro6G4AR2oYP4A6C$$HZsMhb-}MgVJ|9Df9nr7lJz}vl z148Mpnh9;=>i)2Bv@-|m)b&vQU&MMd0hk@(3OOg^&bfmPD_5YKI;h1GgnmUyKMvNS z*Dl@jFEe{GgQYV82Q5l}U@Y#R&i56es!fO#KF~6>m8^j5_VYi$aL3MIurDD=iV!Y# zw)C$KqzsWw6ml!_bkB58+Pnr)j72yJ19dZ;QpeC@=Ysqc6~m1XlxJ}t=Y?#A9ovZP z4*s&io?KSB=5X_Mq0Qr!nZ-97Pc{p8>NN2hw6L1$?|*wdwE()u@GV+8cRmVu4i|nF z2YCia`{H&dzX+@+F~z3}&2HZ~A$J#(3rizQU8HeGveHLO?>XOiq=P#{F`>io&|}#} z+qQJb#$=b8bg=Ps!<e=*Q1NgtcRPDjv(skV{LWDb2qM%@0jkAdR|YXU0)}J-VZ(VO zv{x7b=rlg@Lz!+#pLF{TdI%25r;P3_tLf~a<1m~dWu^)9X|!-0660VwNc|xU#^vge z@^(9+jgIL+eQIJRI$f4Bvf&oE!3Tlij2W+dFrJlUF}JLwhCMn|&0t0&QiAZsfXGG{ zjVgYBHlRRYDA$rq63PP+5>{v58DK!Z#EWBz+L4AD9zp%|)i>xTf3e{0+~^1&1o6#K zwr3ZRDa!hJPfU|eB7lm6qeNDi)%|oq=$rtSjhii9m6^WZH{st=9fQ#dhr52sEKcDV z){U(4C-G#*1B4TJGjp`CK?-PIECS&zl`y!FXqtN(X=qEa*gBq3^TFm}Cpj!<Z{cv# z;p5tQI%$Z$20OlQviaF0JElDg#~SU^X~`l_pY%vASZ0xn9S0Yw$2u3igP1lXelC%Z z2*Nof*G5IpJ`LAQfra2br^_S`U+d$_|6|HwCI3FVcFQm=9DfPaw@B4Y8{dT0y+k4E zlgVOJAdU3x>nLubX7V)$@?A?AU0HyDi|)^#d;oP?m&OB|M4~*^s!BC_{@R=DqVy`) z^iz3jFK^wAHbnd?@;r6FdFZxmHA=CJY>9NY7`vW2a@8_3y<&DFpgBkW@T`=eFK8oO zT(y#eS}lrO`ZBfcPaK>$9u2=+_Mtg1J;2yBN4^5}D8XEx0WdGci3PQk{1UaB<UE<p z8D`qI;@`ZcO@RWg>gCLjA8J&l$QM)18CRi~T;S54ZH(@Xo~$ZF&Js?~!|%D|ZX{Jj z*pc-L3P~#WkVf!P51DxQ^K}CDD=Y?hNA?;=vpqJIB;E8g<Grx~XB0mj5jVCYFvz3m zozDa>GMv4?>|>Zb{znXRL*?)Qk_|}2j?T(<E&w89hKoiSXZPI-lh9uBE~nB`%*8Y# z0*Mb7{70kelul8q(i?D38kQ;^)BGIT#K;2Gc0O-)-=R8XhCD-fRvj!KI&~!nB-tRG z6%kRhp-(a38yn%fxx|3}2(9<WM#3p+PG7FznDP&kSXY4la!18Kyf5=Ze)I7u!bdJ( zu?5bwDq0yf-U=#2@w}%y&$HLPl6$#(8-eKuK@GsLtjyl^z3cs%=|~N9Fg8@Hk?0sO zFcH?lo!^oJ&7L(?lfC9U1Xsda3V1RB)6)_cQU>SeEif3wmvZ0!0BKWR*&#M-@We+n zd!Y-D_)%BP<+!zHM-WgMA-<|E26O*5#V&wF-H?7K{bi0t!Ja@<#T11p`z7kR9bL^I zxiX|bgk@gG;U~e3#Vwfd>bW+G#e;04x)I0s4A&VgI(Fju_0T|cY>fvK^f~+n#M)-I zKA?@0B{P@33F-*DS_^ETL0XcaOIRdDW5V4B_zY`Nd?M#7>oeG!Z^6Ba-dCk{J;lsy ziiSUhyO+>s{C7)Dns`2Rf*jY`gHkmU5gRa2MLAKjTZu0mAO#oAut#vEzYF_C!?|MG zQb|RYeITrDng~^K9yR@$=Tu)pB6?55gtAr{5~EPTj*pnXeR>Z%m;6GME0_TE(4-rw zME3E8f@iqWlgt=}U9DMBcpA3%b9qbF|E~5M9NWd;*ghbr%TH)&^)5!yC%XZ`v?wJT zr0zUE{g^+XtUw(U<CES&(3<db-ms$#xRyo&i|iLUnwfO!GBc62%3?D8j2l>kwXI0C z{Oks!jZS1P^C2&m%)dTuRCl66MJ9OSvo;iOkk@*49_fS4UK2sIg}$oN5`T)WV_j~$ z#*y;(_hW2|toQ1WCxQ6-vCr-?6*3i$CB?T(Iy(Uu4B{Jjn3Fs5)HYKiwn<7UMvAhM ztl~cib)k*j3wl0-&k>Du))lCI$!YL3LpY?I>g)lzF_iS&;YrENcF9<pGPareaKQ_u zk;9qaZ5X`WZ}92U{WL!Q3MCp_?{n!Yd&lr1)Boh%g|Xxi1SaS4j?y{-XsDM?QC&ZG z1C!MO!N?iNJ%CMtP+Z^lbl9d`GfLmgia1Po*<g1)0qa?4#NUk37pPWwGKaoPxaGKE zlC=XR0&?TC4_PvoZuC)-t<rLGRTQ$iP`5hay$5HoqRo_Na|Pnr`tU#HHc07|;74Hj z!qm;VWU@G*IT(xCLhhak8R26E?%PS0ZvBuA*UK2NMgLa-ln!h0y)n3$^pz2`t8-vW z_$nTKKXezOjOw48006+*nwmFJO1`#&fdGWCiqkD7sasUfz;_pVMBcRwH{1}QD`~wD z3f{p}D|=i$neFMFyRFp(a3=Mu7kqE95mqL_urHCyiPQ)u55VgID%`}l`e(;=enO4K zO%min#Pd)4c^Ha7g-73~U~Y*Re}w@G-v)?<N(pl{g+kn$^z->RH%gj>X+U<l5{R#i zeRb_z)DtHChjKhzSXdd2hJuFVx-!?UZ<{Bv&F=~~Smfx8c91VFSwMcY!r~gQh;_4J zOUX5)w190A)A~Ii(mm$Wdjz7+@!Zbw)y`;qFC#onmdMN*Scb&IMQx0<4lOaVs8c46 z!IMGIM-vi&2Wu+U&QQ#StkB27f*;S9WR3)~LZK5_XE#vZ^VVau69ZT*OE>NtpO7cW z=y9bt<!tR_1N{UV6(xx*jJ0I+P{#hKL*kwh1!Ez^Yy~o>%UHUm14b%KvB>fmkT=b_ zigd)xBgK2#{h33=bql4K;;83zkU~UB12jdN28+Nt#W^PWf(SsT=lZwNXYAXwH8p+D z2T-wD1`6V}x`JJU5)g?l{KfbY3U{K*jkF9_;!&pOj7b7b<4O5g2XbEfm_g;#Ldp;i zD<HAyfJD^t!cs~WCSJOZK#3RVPGsup88C`7Rf3=cAq^6&T7fs%O63r?XE~yi1!mA7 zna;{J9Qkw1-3UMA0wD%}%n!-Y!Xj9=+iWqffz)Qr7>-*QR?1x>UX&lEA{7w}jiYCK zu00NA=#@F<vg;mbDp+u2Cm`^pB9D$SuF?1*ev~tQ*g(VAhomo-nH)TCcp+8*-Yg6! zLi{f4nxX{d2{LSYa3e26(CocWi^ygemrkhSURI982(!+05zXQl!4QP&O!;PCt+s1Z zWR_PxUi3&Yixw5M8nCHkDg6_=f+hk<NnN9L+cM@b=#dgGpHK)@8o3Tu8lzbqo_cep zfkrzRw<d0IDq5HAtvFClU_=X?$v_a?KO=Yoh36u0OxZ$S!+WUQ>mB`CEgOPGL>*m* z6L!@dqJzFD(40JE-qoB9C0HFL3|4tOJ91pPVZFhw7eu;Rz0}w$sh&XNz#XOq2TvIr zi{~9k7L7M7L#!M~crc`I6W5)r$aG3}pV7pj%;E`lEP-KW&v?w!L}n}ma35b;S~Q7u zWn6QD1W4v?bv$l;!Bx=gbOuF)QJieN_M$nWNG4939a7d{0~7Bj<(#O7(pw&_f1Hi_ z;$$f3(K$+laQ-ssV9rcZ7sUxH?h(ODxMpu8`~q0R@3V<5ZUR7N0B>X7i^k1P11+>c z0#{3cU70M%f?eOzWe+MNx@4`<J(Dw-w@YU)iGhI=G%cAjvj9+hKt~smnz&+Oe@r!< zV6?O;tlzihz6-JNHINBuQ5fDw>O6KfNE}>-%Ay*gOP`j%nlT#j2qpj#<ZF-?C*ig5 zk8s^+=$=7F69S>O3UrUg4^id>oy3kT*kQp^XA&x9M7QbcQ+v;w05OGe_zv}@RU3qi z$Z4Z<QLq}U0KqK8lA(HvUg?_>BchBcVa$fo1DFN}YOT80bTTwDSQdcHnV+giyD-Lt zKm&qZyc%9CTM%PKoN%g{XgsPsNM}kO0}&4>JwWdya=9)5Ash~^0(uV>M^ySibGCwz z5$PN+Ml%p<d(<uKY~w&;a`wo<<>$>JJ^#x6tLs0KGyLupO&M$44kv!@+P4tPv-(Q) znW!s-B&%<X1rutuz;h!IMzv0su=E`}4cMUKQY-DkXd~rMVw?iG_$~;jzM?dERP5pX z@Y#?cvzEl%35fhKmUs0)0Sqmu3AkeDVMk@C6hoiH97G5`0^;F&iLxet#G@4-dX>k8 zp97OXN@#wwog-#6l6D~%M86snd|3)a+4OKr(u$6rle32G24##}>NW&kj7TOs3VXJL z<NyvrA~J%pX_!2TaZ%Mn4nO))0T5>c4+@7K%h<|@DEF@-){fDoU^iaDFf32}t$^lA zpl+iL|J2M+g9i#^{QP|PQi<;e0S?)xbB1g1_`<>Y)*w#P&y}I!c21Uq3Lc<XiLreo zCi(N(DRN-CGN=F_tqsA*{+t+Vy@iPEhscS5^dUHMT)VyoJ8lf8MK)z>PcH;4bqI0F zG%ZQswtudr3r3w}tQ`@KXB^ZxMGFdmidyI|W43A#-3$(6N2%hin*<U#`Vsw|3K*e* z+Xq8pJwmOUD0D<I**m0DZ_Ezzaz5l>4IsSIG5R3xLv0o-OG?OH@C^*jHSMd|)m^=k z8q!UF2K{Nd9S!5tX!S5^0(g18+nY#vy3{(tRE6@P4?zeK<>TM)kmGd_VPnQA7kRXf zk$~)TlH+gOn7m=j2vbKXB-!<?3w3xF`M3AFy&?>=9II_qaR7Fbv(Ms=PC#2#w`w#W z=rj4$Sqg431ZfI;P81F=%2aAK&1MMC_yLxuW9PMtShb@O%)R9~IY2N4HjJUXmwXHl z=J7qh5e!n|i23lJ3Aori$qjbqY+@PGGUPbj6mN#$9u42-kWv1HK)Xf*7du4zI&Ap; z+W-ZUfh=WXWVbD>z!yT90&Ktv@`?P+^ljzwm*<EOSQ!YkOiVo<Be{j1h`=k}S%4(M zeFL&?6~d#gd+G70xDqLF@j_G33z6kCr3QxYN_Q?~t3=z>P~Gn%)O?gB<ADH558H4S zE5cL+`0b!oSp)CyG_W>56rc2k8*yqZ<hgU@nH;7{RA7%vVjvt$C^wM09t&}apn3UA z!L9@*O|!YI!hQ<rU1vA*#s^oY)!+}EJcLz(c^@;wOG6E9v7#p#04m_B3DD!iQ5N{d zjARRIM%n#>4@7nX_L)j_!4bYw280A2s4z^0{)=R3vJz7Qz(N>0jX`Il$M5BbQk_^? zmb=2DwO)gQyg->t3JD)mBx;B)gI6cNIfElwxl5wF%+%+FNg$PFXf~%ubeSK6L2;*k z-ZS~l5;+l-wl6{w7Dyq}{-FV>Nn6E;24mwA6(n)DhTzooXGRi@WQFLUlc&&iO=I^T zivywJNawc^=E=0XFqsVRR01*<Ms0+Qte(862=!p!HfwwNy3sm3nig*3uWQ6)M8nNw z;zr&c4RH@kO+!!ZWJceGKI)c54md@nvT_ox-E^9HF1$yC=N5RO`I|yDLuRLk5~ld= zav}M<1ZaB)`08RK$`BHIa9Y#Zka|vJvMh>cO<5HEij|eEmVK8g?IfsAJNmq~EgQff zwRv%UW^p&6vzpem6AVaGtc3Q>G5wiRktPK3ep>JKPbd%NiVnQsT{NC%oJLL-qJ!8- zP-h)BwRyVw&H(-~!<FC{mXwl9ti39ohEf4rK?9XBq~H>h9FwJlK~Tt)s~GW9=N{%H zkHahpK^rHdVncAWv!My;Py*&Okv>@=Pj<^*TyrRLzrxUph})=cnGJ9$3I}j$lr?}= zz=2t)jatn_^K@B=I_NPS=#K1BtCqqQnsGNTQfmt49zY^Or3XLIkcNQ*9`Dm{tm+te zGzr-e8FMH~?kI6@V_qIbW6`2CEQp*Gn9!4LSZEWt8?F-u?T9E8^I{i=*dP+gY2|H` zMGdiKCZIJ#i3pZ4sls`onRd=e0U%n#Ca`${WrC4WU~lwxS=8N0NZz<u`9cKid(NN< zFsfY7BSEJ$B<7F*#5mA{&Zx}{jpGKTwORvcvQB+y*s1I#P`iCV?+xGzr9b*LWQvI~ zrhhpch%QjYplTjtZ|uO1%ml?(NWxbMN0G3Y$01InG)n-fngI@h=<$y!X45_xzYZ<; z4|EpnZuD8WG#tw++2doVPQwY<VfNOCe?%wX9=RS1CSNe=7ELA~UfP(%Vg@b3Ie@4? zWgW4dy>6!0k>0lr7=-Wgf`_F=oh+|pA(=&dOHWYHAe`np>Wv*)f@;~V6i<7s3mijc zZ4@C`gzXJ?yt*=6ewBc>XeQn}>W!UeP|~t^p?bStnK{#S5dlPbxd9>u#Kz1>gvttK zd3?&C7ALU8TXCu$a(pA?no^B&vR|6~ij}sirp*p(@KQZ_I24%eSY5C<cj*<5x2O(1 zQ7zNg%?Dm)>Jm0AN|Z&CLzOTfN7OG#0F=>!FqSk3<=Di4`u1Z0Ib8selOlzIIm3id zjw-_NQX_~=kIB1OdIh4uG&6)a$uAeQ-?@5aMkFz+U%>fER>c2C))6vM$q`s74=$Kg z<YQ)MSJLzORlSA*>iBjcvbZ75zzxgoHpoIECg8=M24@g-g`GL-3<#WPqoB05WJPdl z87<p^%7H7OewkiI<Lq+-QYB$D?Js>W0Pv(0o1vBq6^KzM1C(IlMdk&y!2xc`xZBy4 zbk(td%vXIm4b=}{q%u%bFrCz%#{%S}5bPliB~ozxLV*SG38`@jJQSBCAc+;i@e`;N zt0M8yifw!cxT+TeLU39XDrBSe#GhY&)-T|b;$R9N<h$qwC8QBId4VfUBKq>G^AM<x zW{qZS-ENHrsSdf5S-ouDAX9k*0%67<Rphyn%_~k&k6OP#jbGb=pA)02JE-dS`b1O+ zr1=;C6wFyiI!Tq?@<bwOp$VQ6<}27az_&?Ed(ewMf%20<^Z~F$y);Gm$3>HI2^Lq9 zN)VG}(M5cuIe|8Czv84=B1p?kNhb&-+kCJ~Cp@^WbcRlQNgg+8V1=ctJWBX)kq0fd zAfF&H0wQim;D^RNLt*)8>Blbt34>^ZniMi^9|qnB%ES;E!kSQ!IK8Y>A1x=m76zre zZ2g#{aC_l);B}ZbGf3Y$5Pf?Ha!#0t3<5F`ED$p<#rl0e5CFtqc!!Oi7M~UH7I8~> zKcNUu8%}Z~Bb?-HK-;xoKCjL8>_&0cLO;{MS&3$vA|)_!KSn*s%ug690fdLcraD7- fD&x8tjE$WbXjs&snU8)|^B;s6yTptcKAzx$Qp3K0 literal 0 HcmV?d00001 diff --git a/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.svg b/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.svg new file mode 100644 index 000000000..25691af8f --- /dev/null +++ b/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.svg @@ -0,0 +1,229 @@ +<?xml version="1.0" standalone="no"?> +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" > +<svg xmlns="http://www.w3.org/2000/svg"> +<metadata></metadata> +<defs> +<font id="glyphicons_halflingsregular" horiz-adv-x="1200" > +<font-face units-per-em="1200" ascent="960" descent="-240" /> +<missing-glyph horiz-adv-x="500" /> +<glyph /> +<glyph /> +<glyph unicode=" " /> +<glyph unicode=" " /> +<glyph unicode="*" d="M100 500v200h259l-183 183l141 141l183 -183v259h200v-259l183 183l141 -141l-183 -183h259v-200h-259l183 -183l-141 -141l-183 183v-259h-200v259l-183 -183l-141 141l183 183h-259z" /> +<glyph unicode="+" d="M0 400v300h400v400h300v-400h400v-300h-400v-400h-300v400h-400z" /> +<glyph unicode=" " /> +<glyph unicode=" " horiz-adv-x="652" /> +<glyph unicode=" " horiz-adv-x="1304" /> +<glyph unicode=" " horiz-adv-x="652" /> +<glyph unicode=" " horiz-adv-x="1304" /> +<glyph unicode=" " horiz-adv-x="434" /> +<glyph unicode=" " horiz-adv-x="326" /> +<glyph unicode=" " horiz-adv-x="217" /> +<glyph unicode=" " horiz-adv-x="217" /> +<glyph unicode=" " horiz-adv-x="163" /> +<glyph unicode=" " horiz-adv-x="260" /> +<glyph unicode=" " horiz-adv-x="72" /> +<glyph unicode=" " horiz-adv-x="260" /> +<glyph unicode=" " horiz-adv-x="326" /> +<glyph unicode="€" d="M100 500l100 100h113q0 47 5 100h-218l100 100h135q37 167 112 257q117 141 297 141q242 0 354 -189q60 -103 66 -209h-181q0 55 -25.5 99t-63.5 68t-75 36.5t-67 12.5q-24 0 -52.5 -10t-62.5 -32t-65.5 -67t-50.5 -107h379l-100 -100h-300q-6 -46 -6 -100h406l-100 -100 h-300q9 -74 33 -132t52.5 -91t62 -54.5t59 -29t46.5 -7.5q29 0 66 13t75 37t63.5 67.5t25.5 96.5h174q-31 -172 -128 -278q-107 -117 -274 -117q-205 0 -324 158q-36 46 -69 131.5t-45 205.5h-217z" /> +<glyph unicode="−" d="M200 400h900v300h-900v-300z" /> +<glyph unicode="◼" horiz-adv-x="500" d="M0 0z" /> +<glyph unicode="☁" d="M-14 494q0 -80 56.5 -137t135.5 -57h750q120 0 205 86.5t85 207.5t-85 207t-205 86q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5z" /> +<glyph unicode="✉" d="M0 100l400 400l200 -200l200 200l400 -400h-1200zM0 300v600l300 -300zM0 1100l600 -603l600 603h-1200zM900 600l300 300v-600z" /> +<glyph unicode="✏" d="M-13 -13l333 112l-223 223zM187 403l214 -214l614 614l-214 214zM887 1103l214 -214l99 92q13 13 13 32.5t-13 33.5l-153 153q-15 13 -33 13t-33 -13z" /> +<glyph unicode="" d="M0 1200h1200l-500 -550v-550h300v-100h-800v100h300v550z" /> +<glyph unicode="" d="M14 84q18 -55 86 -75.5t147 5.5q65 21 109 69t44 90v606l600 155v-521q-64 16 -138 -7q-79 -26 -122.5 -83t-25.5 -111q18 -55 86 -75.5t147 4.5q70 23 111.5 63.5t41.5 95.5v881q0 10 -7 15.5t-17 2.5l-752 -193q-10 -3 -17 -12.5t-7 -19.5v-689q-64 17 -138 -7 q-79 -25 -122.5 -82t-25.5 -112z" /> +<glyph unicode="" d="M23 693q0 200 142 342t342 142t342 -142t142 -342q0 -142 -78 -261l300 -300q7 -8 7 -18t-7 -18l-109 -109q-8 -7 -18 -7t-18 7l-300 300q-119 -78 -261 -78q-200 0 -342 142t-142 342zM176 693q0 -136 97 -233t234 -97t233.5 96.5t96.5 233.5t-96.5 233.5t-233.5 96.5 t-234 -97t-97 -233z" /> +<glyph unicode="" d="M100 784q0 64 28 123t73 100.5t104.5 64t119 20.5t120 -38.5t104.5 -104.5q48 69 109.5 105t121.5 38t118.5 -20.5t102.5 -64t71 -100.5t27 -123q0 -57 -33.5 -117.5t-94 -124.5t-126.5 -127.5t-150 -152.5t-146 -174q-62 85 -145.5 174t-149.5 152.5t-126.5 127.5 t-94 124.5t-33.5 117.5z" /> +<glyph unicode="" d="M-72 800h479l146 400h2l146 -400h472l-382 -278l145 -449l-384 275l-382 -275l146 447zM168 71l2 1z" /> +<glyph unicode="" d="M-72 800h479l146 400h2l146 -400h472l-382 -278l145 -449l-384 275l-382 -275l146 447zM168 71l2 1zM237 700l196 -142l-73 -226l192 140l195 -141l-74 229l193 140h-235l-77 211l-78 -211h-239z" /> +<glyph unicode="" d="M0 0v143l400 257v100q-37 0 -68.5 74.5t-31.5 125.5v200q0 124 88 212t212 88t212 -88t88 -212v-200q0 -51 -31.5 -125.5t-68.5 -74.5v-100l400 -257v-143h-1200z" /> +<glyph unicode="" d="M0 0v1100h1200v-1100h-1200zM100 100h100v100h-100v-100zM100 300h100v100h-100v-100zM100 500h100v100h-100v-100zM100 700h100v100h-100v-100zM100 900h100v100h-100v-100zM300 100h600v400h-600v-400zM300 600h600v400h-600v-400zM1000 100h100v100h-100v-100z M1000 300h100v100h-100v-100zM1000 500h100v100h-100v-100zM1000 700h100v100h-100v-100zM1000 900h100v100h-100v-100z" /> +<glyph unicode="" d="M0 50v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5zM0 650v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400 q-21 0 -35.5 14.5t-14.5 35.5zM600 50v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5zM600 650v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400 q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5z" /> +<glyph unicode="" d="M0 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM0 450v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200 q-21 0 -35.5 14.5t-14.5 35.5zM0 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5 t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 450v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5 v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM800 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM800 450v200q0 21 14.5 35.5t35.5 14.5h200 q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM800 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5z" /> +<glyph unicode="" d="M0 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM0 450q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v200q0 21 -14.5 35.5t-35.5 14.5h-200q-21 0 -35.5 -14.5 t-14.5 -35.5v-200zM0 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 50v200q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5 t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5zM400 450v200q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5zM400 850v200q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5 v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5z" /> +<glyph unicode="" d="M29 454l419 -420l818 820l-212 212l-607 -607l-206 207z" /> +<glyph unicode="" d="M106 318l282 282l-282 282l212 212l282 -282l282 282l212 -212l-282 -282l282 -282l-212 -212l-282 282l-282 -282z" /> +<glyph unicode="" d="M23 693q0 200 142 342t342 142t342 -142t142 -342q0 -142 -78 -261l300 -300q7 -8 7 -18t-7 -18l-109 -109q-8 -7 -18 -7t-18 7l-300 300q-119 -78 -261 -78q-200 0 -342 142t-142 342zM176 693q0 -136 97 -233t234 -97t233.5 96.5t96.5 233.5t-96.5 233.5t-233.5 96.5 t-234 -97t-97 -233zM300 600v200h100v100h200v-100h100v-200h-100v-100h-200v100h-100z" /> +<glyph unicode="" d="M23 694q0 200 142 342t342 142t342 -142t142 -342q0 -141 -78 -262l300 -299q7 -7 7 -18t-7 -18l-109 -109q-8 -8 -18 -8t-18 8l-300 300q-119 -78 -261 -78q-200 0 -342 142t-142 342zM176 694q0 -136 97 -233t234 -97t233.5 97t96.5 233t-96.5 233t-233.5 97t-234 -97 t-97 -233zM300 601h400v200h-400v-200z" /> +<glyph unicode="" d="M23 600q0 183 105 331t272 210v-166q-103 -55 -165 -155t-62 -220q0 -177 125 -302t302 -125t302 125t125 302q0 120 -62 220t-165 155v166q167 -62 272 -210t105 -331q0 -118 -45.5 -224.5t-123 -184t-184 -123t-224.5 -45.5t-224.5 45.5t-184 123t-123 184t-45.5 224.5 zM500 750q0 -21 14.5 -35.5t35.5 -14.5h100q21 0 35.5 14.5t14.5 35.5v400q0 21 -14.5 35.5t-35.5 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-400z" /> +<glyph unicode="" d="M100 1h200v300h-200v-300zM400 1v500h200v-500h-200zM700 1v800h200v-800h-200zM1000 1v1200h200v-1200h-200z" /> +<glyph unicode="" d="M26 601q0 -33 6 -74l151 -38l2 -6q14 -49 38 -93l3 -5l-80 -134q45 -59 105 -105l133 81l5 -3q45 -26 94 -39l5 -2l38 -151q40 -5 74 -5q27 0 74 5l38 151l6 2q46 13 93 39l5 3l134 -81q56 44 104 105l-80 134l3 5q24 44 39 93l1 6l152 38q5 40 5 74q0 28 -5 73l-152 38 l-1 6q-16 51 -39 93l-3 5l80 134q-44 58 -104 105l-134 -81l-5 3q-45 25 -93 39l-6 1l-38 152q-40 5 -74 5q-27 0 -74 -5l-38 -152l-5 -1q-50 -14 -94 -39l-5 -3l-133 81q-59 -47 -105 -105l80 -134l-3 -5q-25 -47 -38 -93l-2 -6l-151 -38q-6 -48 -6 -73zM385 601 q0 88 63 151t152 63t152 -63t63 -151q0 -89 -63 -152t-152 -63t-152 63t-63 152z" /> +<glyph unicode="" d="M100 1025v50q0 10 7.5 17.5t17.5 7.5h275v100q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5v-100h275q10 0 17.5 -7.5t7.5 -17.5v-50q0 -11 -7 -18t-18 -7h-1050q-11 0 -18 7t-7 18zM200 100v800h900v-800q0 -41 -29.5 -71t-70.5 -30h-700q-41 0 -70.5 30 t-29.5 71zM300 100h100v700h-100v-700zM500 100h100v700h-100v-700zM500 1100h300v100h-300v-100zM700 100h100v700h-100v-700zM900 100h100v700h-100v-700z" /> +<glyph unicode="" d="M1 601l656 644l644 -644h-200v-600h-300v400h-300v-400h-300v600h-200z" /> +<glyph unicode="" d="M100 25v1150q0 11 7 18t18 7h475v-500h400v-675q0 -11 -7 -18t-18 -7h-850q-11 0 -18 7t-7 18zM700 800v300l300 -300h-300z" /> +<glyph unicode="" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM500 500v400h100 v-300h200v-100h-300z" /> +<glyph unicode="" d="M-100 0l431 1200h209l-21 -300h162l-20 300h208l431 -1200h-538l-41 400h-242l-40 -400h-539zM488 500h224l-27 300h-170z" /> +<glyph unicode="" d="M0 0v400h490l-290 300h200v500h300v-500h200l-290 -300h490v-400h-1100zM813 200h175v100h-175v-100z" /> +<glyph unicode="" d="M1 600q0 122 47.5 233t127.5 191t191 127.5t233 47.5t233 -47.5t191 -127.5t127.5 -191t47.5 -233t-47.5 -233t-127.5 -191t-191 -127.5t-233 -47.5t-233 47.5t-191 127.5t-127.5 191t-47.5 233zM188 600q0 -170 121 -291t291 -121t291 121t121 291t-121 291t-291 121 t-291 -121t-121 -291zM350 600h150v300h200v-300h150l-250 -300z" /> +<glyph unicode="" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM350 600l250 300 l250 -300h-150v-300h-200v300h-150z" /> +<glyph unicode="" d="M0 25v475l200 700h800l199 -700l1 -475q0 -11 -7 -18t-18 -7h-1150q-11 0 -18 7t-7 18zM200 500h200l50 -200h300l50 200h200l-97 500h-606z" /> +<glyph unicode="" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -172 121.5 -293t292.5 -121t292.5 121t121.5 293q0 171 -121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM500 397v401 l297 -200z" /> +<glyph unicode="" d="M23 600q0 -118 45.5 -224.5t123 -184t184 -123t224.5 -45.5t224.5 45.5t184 123t123 184t45.5 224.5h-150q0 -177 -125 -302t-302 -125t-302 125t-125 302t125 302t302 125q136 0 246 -81l-146 -146h400v400l-145 -145q-157 122 -355 122q-118 0 -224.5 -45.5t-184 -123 t-123 -184t-45.5 -224.5z" /> +<glyph unicode="" d="M23 600q0 118 45.5 224.5t123 184t184 123t224.5 45.5q198 0 355 -122l145 145v-400h-400l147 147q-112 80 -247 80q-177 0 -302 -125t-125 -302h-150zM100 0v400h400l-147 -147q112 -80 247 -80q177 0 302 125t125 302h150q0 -118 -45.5 -224.5t-123 -184t-184 -123 t-224.5 -45.5q-198 0 -355 122z" /> +<glyph unicode="" d="M100 0h1100v1200h-1100v-1200zM200 100v900h900v-900h-900zM300 200v100h100v-100h-100zM300 400v100h100v-100h-100zM300 600v100h100v-100h-100zM300 800v100h100v-100h-100zM500 200h500v100h-500v-100zM500 400v100h500v-100h-500zM500 600v100h500v-100h-500z M500 800v100h500v-100h-500z" /> +<glyph unicode="" d="M0 100v600q0 41 29.5 70.5t70.5 29.5h100v200q0 82 59 141t141 59h300q82 0 141 -59t59 -141v-200h100q41 0 70.5 -29.5t29.5 -70.5v-600q0 -41 -29.5 -70.5t-70.5 -29.5h-900q-41 0 -70.5 29.5t-29.5 70.5zM400 800h300v150q0 21 -14.5 35.5t-35.5 14.5h-200 q-21 0 -35.5 -14.5t-14.5 -35.5v-150z" /> +<glyph unicode="" d="M100 0v1100h100v-1100h-100zM300 400q60 60 127.5 84t127.5 17.5t122 -23t119 -30t110 -11t103 42t91 120.5v500q-40 -81 -101.5 -115.5t-127.5 -29.5t-138 25t-139.5 40t-125.5 25t-103 -29.5t-65 -115.5v-500z" /> +<glyph unicode="" d="M0 275q0 -11 7 -18t18 -7h50q11 0 18 7t7 18v300q0 127 70.5 231.5t184.5 161.5t245 57t245 -57t184.5 -161.5t70.5 -231.5v-300q0 -11 7 -18t18 -7h50q11 0 18 7t7 18v300q0 116 -49.5 227t-131 192.5t-192.5 131t-227 49.5t-227 -49.5t-192.5 -131t-131 -192.5 t-49.5 -227v-300zM200 20v460q0 8 6 14t14 6h160q8 0 14 -6t6 -14v-460q0 -8 -6 -14t-14 -6h-160q-8 0 -14 6t-6 14zM800 20v460q0 8 6 14t14 6h160q8 0 14 -6t6 -14v-460q0 -8 -6 -14t-14 -6h-160q-8 0 -14 6t-6 14z" /> +<glyph unicode="" d="M0 400h300l300 -200v800l-300 -200h-300v-400zM688 459l141 141l-141 141l71 71l141 -141l141 141l71 -71l-141 -141l141 -141l-71 -71l-141 141l-141 -141z" /> +<glyph unicode="" d="M0 400h300l300 -200v800l-300 -200h-300v-400zM700 857l69 53q111 -135 111 -310q0 -169 -106 -302l-67 54q86 110 86 248q0 146 -93 257z" /> +<glyph unicode="" d="M0 401v400h300l300 200v-800l-300 200h-300zM702 858l69 53q111 -135 111 -310q0 -170 -106 -303l-67 55q86 110 86 248q0 145 -93 257zM889 951l7 -8q123 -151 123 -344q0 -189 -119 -339l-7 -8l81 -66l6 8q142 178 142 405q0 230 -144 408l-6 8z" /> +<glyph unicode="" d="M0 0h500v500h-200v100h-100v-100h-200v-500zM0 600h100v100h400v100h100v100h-100v300h-500v-600zM100 100v300h300v-300h-300zM100 800v300h300v-300h-300zM200 200v100h100v-100h-100zM200 900h100v100h-100v-100zM500 500v100h300v-300h200v-100h-100v-100h-200v100 h-100v100h100v200h-200zM600 0v100h100v-100h-100zM600 1000h100v-300h200v-300h300v200h-200v100h200v500h-600v-200zM800 800v300h300v-300h-300zM900 0v100h300v-100h-300zM900 900v100h100v-100h-100zM1100 200v100h100v-100h-100z" /> +<glyph unicode="" d="M0 200h100v1000h-100v-1000zM100 0v100h300v-100h-300zM200 200v1000h100v-1000h-100zM500 0v91h100v-91h-100zM500 200v1000h200v-1000h-200zM700 0v91h100v-91h-100zM800 200v1000h100v-1000h-100zM900 0v91h200v-91h-200zM1000 200v1000h200v-1000h-200z" /> +<glyph unicode="" d="M0 700l1 475q0 10 7.5 17.5t17.5 7.5h474l700 -700l-500 -500zM148 953q0 -42 29 -71q30 -30 71.5 -30t71.5 30q29 29 29 71t-29 71q-30 30 -71.5 30t-71.5 -30q-29 -29 -29 -71z" /> +<glyph unicode="" d="M1 700l1 475q0 11 7 18t18 7h474l700 -700l-500 -500zM148 953q0 -42 30 -71q29 -30 71 -30t71 30q30 29 30 71t-30 71q-29 30 -71 30t-71 -30q-30 -29 -30 -71zM701 1200h100l700 -700l-500 -500l-50 50l450 450z" /> +<glyph unicode="" d="M100 0v1025l175 175h925v-1000l-100 -100v1000h-750l-100 -100h750v-1000h-900z" /> +<glyph unicode="" d="M200 0l450 444l450 -443v1150q0 20 -14.5 35t-35.5 15h-800q-21 0 -35.5 -15t-14.5 -35v-1151z" /> +<glyph unicode="" d="M0 100v700h200l100 -200h600l100 200h200v-700h-200v200h-800v-200h-200zM253 829l40 -124h592l62 124l-94 346q-2 11 -10 18t-18 7h-450q-10 0 -18 -7t-10 -18zM281 24l38 152q2 10 11.5 17t19.5 7h500q10 0 19.5 -7t11.5 -17l38 -152q2 -10 -3.5 -17t-15.5 -7h-600 q-10 0 -15.5 7t-3.5 17z" /> +<glyph unicode="" d="M0 200q0 -41 29.5 -70.5t70.5 -29.5h1000q41 0 70.5 29.5t29.5 70.5v600q0 41 -29.5 70.5t-70.5 29.5h-150q-4 8 -11.5 21.5t-33 48t-53 61t-69 48t-83.5 21.5h-200q-41 0 -82 -20.5t-70 -50t-52 -59t-34 -50.5l-12 -20h-150q-41 0 -70.5 -29.5t-29.5 -70.5v-600z M356 500q0 100 72 172t172 72t172 -72t72 -172t-72 -172t-172 -72t-172 72t-72 172zM494 500q0 -44 31 -75t75 -31t75 31t31 75t-31 75t-75 31t-75 -31t-31 -75zM900 700v100h100v-100h-100z" /> +<glyph unicode="" d="M53 0h365v66q-41 0 -72 11t-49 38t1 71l92 234h391l82 -222q16 -45 -5.5 -88.5t-74.5 -43.5v-66h417v66q-34 1 -74 43q-18 19 -33 42t-21 37l-6 13l-385 998h-93l-399 -1006q-24 -48 -52 -75q-12 -12 -33 -25t-36 -20l-15 -7v-66zM416 521l178 457l46 -140l116 -317h-340 z" /> +<glyph unicode="" d="M100 0v89q41 7 70.5 32.5t29.5 65.5v827q0 28 -1 39.5t-5.5 26t-15.5 21t-29 14t-49 14.5v71l471 -1q120 0 213 -88t93 -228q0 -55 -11.5 -101.5t-28 -74t-33.5 -47.5t-28 -28l-12 -7q8 -3 21.5 -9t48 -31.5t60.5 -58t47.5 -91.5t21.5 -129q0 -84 -59 -156.5t-142 -111 t-162 -38.5h-500zM400 200h161q89 0 153 48.5t64 132.5q0 90 -62.5 154.5t-156.5 64.5h-159v-400zM400 700h139q76 0 130 61.5t54 138.5q0 82 -84 130.5t-239 48.5v-379z" /> +<glyph unicode="" d="M200 0v57q77 7 134.5 40.5t65.5 80.5l173 849q10 56 -10 74t-91 37q-6 1 -10.5 2.5t-9.5 2.5v57h425l2 -57q-33 -8 -62 -25.5t-46 -37t-29.5 -38t-17.5 -30.5l-5 -12l-128 -825q-10 -52 14 -82t95 -36v-57h-500z" /> +<glyph unicode="" d="M-75 200h75v800h-75l125 167l125 -167h-75v-800h75l-125 -167zM300 900v300h150h700h150v-300h-50q0 29 -8 48.5t-18.5 30t-33.5 15t-39.5 5.5t-50.5 1h-200v-850l100 -50v-100h-400v100l100 50v850h-200q-34 0 -50.5 -1t-40 -5.5t-33.5 -15t-18.5 -30t-8.5 -48.5h-49z " /> +<glyph unicode="" d="M33 51l167 125v-75h800v75l167 -125l-167 -125v75h-800v-75zM100 901v300h150h700h150v-300h-50q0 29 -8 48.5t-18 30t-33.5 15t-40 5.5t-50.5 1h-200v-650l100 -50v-100h-400v100l100 50v650h-200q-34 0 -50.5 -1t-39.5 -5.5t-33.5 -15t-18.5 -30t-8 -48.5h-50z" /> +<glyph unicode="" d="M0 50q0 -20 14.5 -35t35.5 -15h1100q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM0 350q0 -20 14.5 -35t35.5 -15h800q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-800q-21 0 -35.5 -14.5t-14.5 -35.5 v-100zM0 650q0 -20 14.5 -35t35.5 -15h1000q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1000q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM0 950q0 -20 14.5 -35t35.5 -15h600q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-600q-21 0 -35.5 -14.5 t-14.5 -35.5v-100z" /> +<glyph unicode="" d="M0 50q0 -20 14.5 -35t35.5 -15h1100q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM0 650q0 -20 14.5 -35t35.5 -15h1100q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5 v-100zM200 350q0 -20 14.5 -35t35.5 -15h700q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-700q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM200 950q0 -20 14.5 -35t35.5 -15h700q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-700q-21 0 -35.5 -14.5 t-14.5 -35.5v-100z" /> +<glyph unicode="" d="M0 50v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM100 650v100q0 21 14.5 35.5t35.5 14.5h1000q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1000q-21 0 -35.5 15 t-14.5 35zM300 350v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15t-14.5 35zM500 950v100q0 21 14.5 35.5t35.5 14.5h600q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-600 q-21 0 -35.5 15t-14.5 35z" /> +<glyph unicode="" d="M0 50v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM0 350v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15 t-14.5 35zM0 650v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM0 950v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100 q-21 0 -35.5 15t-14.5 35z" /> +<glyph unicode="" d="M0 50v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15t-14.5 35zM0 350v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15 t-14.5 35zM0 650v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15t-14.5 35zM0 950v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15 t-14.5 35zM300 50v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15t-14.5 35zM300 350v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800 q-21 0 -35.5 15t-14.5 35zM300 650v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15t-14.5 35zM300 950v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15 h-800q-21 0 -35.5 15t-14.5 35z" /> +<glyph unicode="" d="M-101 500v100h201v75l166 -125l-166 -125v75h-201zM300 0h100v1100h-100v-1100zM500 50q0 -20 14.5 -35t35.5 -15h600q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-600q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM500 350q0 -20 14.5 -35t35.5 -15h300q20 0 35 15t15 35 v100q0 21 -15 35.5t-35 14.5h-300q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM500 650q0 -20 14.5 -35t35.5 -15h500q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-500q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM500 950q0 -20 14.5 -35t35.5 -15h100q20 0 35 15t15 35v100 q0 21 -15 35.5t-35 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-100z" /> +<glyph unicode="" d="M1 50q0 -20 14.5 -35t35.5 -15h600q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-600q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM1 350q0 -20 14.5 -35t35.5 -15h300q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-300q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM1 650 q0 -20 14.5 -35t35.5 -15h500q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-500q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM1 950q0 -20 14.5 -35t35.5 -15h100q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM801 0v1100h100v-1100 h-100zM934 550l167 -125v75h200v100h-200v75z" /> +<glyph unicode="" d="M0 275v650q0 31 22 53t53 22h750q31 0 53 -22t22 -53v-650q0 -31 -22 -53t-53 -22h-750q-31 0 -53 22t-22 53zM900 600l300 300v-600z" /> +<glyph unicode="" d="M0 44v1012q0 18 13 31t31 13h1112q19 0 31.5 -13t12.5 -31v-1012q0 -18 -12.5 -31t-31.5 -13h-1112q-18 0 -31 13t-13 31zM100 263l247 182l298 -131l-74 156l293 318l236 -288v500h-1000v-737zM208 750q0 56 39 95t95 39t95 -39t39 -95t-39 -95t-95 -39t-95 39t-39 95z " /> +<glyph unicode="" d="M148 745q0 124 60.5 231.5t165 172t226.5 64.5q123 0 227 -63t164.5 -169.5t60.5 -229.5t-73 -272q-73 -114 -166.5 -237t-150.5 -189l-57 -66q-10 9 -27 26t-66.5 70.5t-96 109t-104 135.5t-100.5 155q-63 139 -63 262zM342 772q0 -107 75.5 -182.5t181.5 -75.5 q107 0 182.5 75.5t75.5 182.5t-75.5 182t-182.5 75t-182 -75.5t-75 -181.5z" /> +<glyph unicode="" d="M1 600q0 122 47.5 233t127.5 191t191 127.5t233 47.5t233 -47.5t191 -127.5t127.5 -191t47.5 -233t-47.5 -233t-127.5 -191t-191 -127.5t-233 -47.5t-233 47.5t-191 127.5t-127.5 191t-47.5 233zM173 600q0 -177 125.5 -302t301.5 -125v854q-176 0 -301.5 -125 t-125.5 -302z" /> +<glyph unicode="" d="M117 406q0 94 34 186t88.5 172.5t112 159t115 177t87.5 194.5q21 -71 57.5 -142.5t76 -130.5t83 -118.5t82 -117t70 -116t50 -125.5t18.5 -136q0 -89 -39 -165.5t-102 -126.5t-140 -79.5t-156 -33.5q-114 6 -211.5 53t-161.5 139t-64 210zM243 414q14 -82 59.5 -136 t136.5 -80l16 98q-7 6 -18 17t-34 48t-33 77q-15 73 -14 143.5t10 122.5l9 51q-92 -110 -119.5 -185t-12.5 -156z" /> +<glyph unicode="" d="M0 400v300q0 165 117.5 282.5t282.5 117.5q366 -6 397 -14l-186 -186h-311q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v125l200 200v-225q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5 t-117.5 282.5zM436 341l161 50l412 412l-114 113l-405 -405zM995 1015l113 -113l113 113l-21 85l-92 28z" /> +<glyph unicode="" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h261l2 -80q-133 -32 -218 -120h-145q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5l200 153v-53q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5 zM423 524q30 38 81.5 64t103 35.5t99 14t77.5 3.5l29 -1v-209l360 324l-359 318v-216q-7 0 -19 -1t-48 -8t-69.5 -18.5t-76.5 -37t-76.5 -59t-62 -88t-39.5 -121.5z" /> +<glyph unicode="" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h300q61 0 127 -23l-178 -177h-349q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v69l200 200v-169q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5 t-117.5 282.5zM342 632l283 -284l567 567l-137 137l-430 -431l-146 147z" /> +<glyph unicode="" d="M0 603l300 296v-198h200v200h-200l300 300l295 -300h-195v-200h200v198l300 -296l-300 -300v198h-200v-200h195l-295 -300l-300 300h200v200h-200v-198z" /> +<glyph unicode="" d="M200 50v1000q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-437l500 487v-1100l-500 488v-438q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5z" /> +<glyph unicode="" d="M0 50v1000q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-437l500 487v-487l500 487v-1100l-500 488v-488l-500 488v-438q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5z" /> +<glyph unicode="" d="M136 550l564 550v-487l500 487v-1100l-500 488v-488z" /> +<glyph unicode="" d="M200 0l900 550l-900 550v-1100z" /> +<glyph unicode="" d="M200 150q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v800q0 21 -14.5 35.5t-35.5 14.5h-200q-21 0 -35.5 -14.5t-14.5 -35.5v-800zM600 150q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v800q0 21 -14.5 35.5t-35.5 14.5h-200 q-21 0 -35.5 -14.5t-14.5 -35.5v-800z" /> +<glyph unicode="" d="M200 150q0 -20 14.5 -35t35.5 -15h800q21 0 35.5 15t14.5 35v800q0 21 -14.5 35.5t-35.5 14.5h-800q-21 0 -35.5 -14.5t-14.5 -35.5v-800z" /> +<glyph unicode="" d="M0 0v1100l500 -487v487l564 -550l-564 -550v488z" /> +<glyph unicode="" d="M0 0v1100l500 -487v487l500 -487v437q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-1000q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v438l-500 -488v488z" /> +<glyph unicode="" d="M300 0v1100l500 -487v437q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-1000q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v438z" /> +<glyph unicode="" d="M100 250v100q0 21 14.5 35.5t35.5 14.5h1000q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1000q-21 0 -35.5 14.5t-14.5 35.5zM100 500h1100l-550 564z" /> +<glyph unicode="" d="M185 599l592 -592l240 240l-353 353l353 353l-240 240z" /> +<glyph unicode="" d="M272 194l353 353l-353 353l241 240l572 -571l21 -22l-1 -1v-1l-592 -591z" /> +<glyph unicode="" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM300 500h200v-200h200v200h200v200h-200v200h-200v-200h-200v-200z" /> +<glyph unicode="" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM300 500h600v200h-600v-200z" /> +<glyph unicode="" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM246 459l213 -213l141 142l141 -142l213 213l-142 141l142 141l-213 212l-141 -141l-141 142l-212 -213l141 -141 z" /> +<glyph unicode="" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM270 551l276 -277l411 411l-175 174l-236 -236l-102 102z" /> +<glyph unicode="" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM364 700h143q4 0 11.5 -1t11 -1t6.5 3t3 9t1 11t3.5 8.5t3.5 6t5.5 4t6.5 2.5t9 1.5t9 0.5h11.5h12.5 q19 0 30 -10t11 -26q0 -22 -4 -28t-27 -22q-5 -1 -12.5 -3t-27 -13.5t-34 -27t-26.5 -46t-11 -68.5h200q5 3 14 8t31.5 25.5t39.5 45.5t31 69t14 94q0 51 -17.5 89t-42 58t-58.5 32t-58.5 15t-51.5 3q-50 0 -90.5 -12t-75 -38.5t-53.5 -74.5t-19 -114zM500 300h200v100h-200 v-100z" /> +<glyph unicode="" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM400 300h400v100h-100v300h-300v-100h100v-200h-100v-100zM500 800h200v100h-200v-100z" /> +<glyph unicode="" d="M0 500v200h195q31 125 98.5 199.5t206.5 100.5v200h200v-200q54 -20 113 -60t112.5 -105.5t71.5 -134.5h203v-200h-203q-25 -102 -116.5 -186t-180.5 -117v-197h-200v197q-140 27 -208 102.5t-98 200.5h-194zM290 500q24 -73 79.5 -127.5t130.5 -78.5v206h200v-206 q149 48 201 206h-201v200h200q-25 74 -75.5 127t-124.5 77v-204h-200v203q-75 -23 -130 -77t-79 -126h209v-200h-210z" /> +<glyph unicode="" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM356 465l135 135 l-135 135l109 109l135 -135l135 135l109 -109l-135 -135l135 -135l-109 -109l-135 135l-135 -135z" /> +<glyph unicode="" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM322 537l141 141 l87 -87l204 205l142 -142l-346 -345z" /> +<glyph unicode="" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -115 62 -215l568 567q-100 62 -216 62q-171 0 -292.5 -121.5t-121.5 -292.5zM391 245q97 -59 209 -59q171 0 292.5 121.5t121.5 292.5 q0 112 -59 209z" /> +<glyph unicode="" d="M0 547l600 453v-300h600v-300h-600v-301z" /> +<glyph unicode="" d="M0 400v300h600v300l600 -453l-600 -448v301h-600z" /> +<glyph unicode="" d="M204 600l450 600l444 -600h-298v-600h-300v600h-296z" /> +<glyph unicode="" d="M104 600h296v600h300v-600h298l-449 -600z" /> +<glyph unicode="" d="M0 200q6 132 41 238.5t103.5 193t184 138t271.5 59.5v271l600 -453l-600 -448v301q-95 -2 -183 -20t-170 -52t-147 -92.5t-100 -135.5z" /> +<glyph unicode="" d="M0 0v400l129 -129l294 294l142 -142l-294 -294l129 -129h-400zM635 777l142 -142l294 294l129 -129v400h-400l129 -129z" /> +<glyph unicode="" d="M34 176l295 295l-129 129h400v-400l-129 130l-295 -295zM600 600v400l129 -129l295 295l142 -141l-295 -295l129 -130h-400z" /> +<glyph unicode="" d="M23 600q0 118 45.5 224.5t123 184t184 123t224.5 45.5t224.5 -45.5t184 -123t123 -184t45.5 -224.5t-45.5 -224.5t-123 -184t-184 -123t-224.5 -45.5t-224.5 45.5t-184 123t-123 184t-45.5 224.5zM456 851l58 -302q4 -20 21.5 -34.5t37.5 -14.5h54q20 0 37.5 14.5 t21.5 34.5l58 302q4 20 -8 34.5t-32 14.5h-207q-21 0 -33 -14.5t-8 -34.5zM500 300h200v100h-200v-100z" /> +<glyph unicode="" d="M0 800h100v-200h400v300h200v-300h400v200h100v100h-111q1 1 1 6.5t-1.5 15t-3.5 17.5l-34 172q-11 39 -41.5 63t-69.5 24q-32 0 -61 -17l-239 -144q-22 -13 -40 -35q-19 24 -40 36l-238 144q-33 18 -62 18q-39 0 -69.5 -23t-40.5 -61l-35 -177q-2 -8 -3 -18t-1 -15v-6 h-111v-100zM100 0h400v400h-400v-400zM200 900q-3 0 14 48t36 96l18 47l213 -191h-281zM700 0v400h400v-400h-400zM731 900l202 197q5 -12 12 -32.5t23 -64t25 -72t7 -28.5h-269z" /> +<glyph unicode="" d="M0 -22v143l216 193q-9 53 -13 83t-5.5 94t9 113t38.5 114t74 124q47 60 99.5 102.5t103 68t127.5 48t145.5 37.5t184.5 43.5t220 58.5q0 -189 -22 -343t-59 -258t-89 -181.5t-108.5 -120t-122 -68t-125.5 -30t-121.5 -1.5t-107.5 12.5t-87.5 17t-56.5 7.5l-99 -55z M238.5 300.5q19.5 -6.5 86.5 76.5q55 66 367 234q70 38 118.5 69.5t102 79t99 111.5t86.5 148q22 50 24 60t-6 19q-7 5 -17 5t-26.5 -14.5t-33.5 -39.5q-35 -51 -113.5 -108.5t-139.5 -89.5l-61 -32q-369 -197 -458 -401q-48 -111 -28.5 -117.5z" /> +<glyph unicode="" d="M111 408q0 -33 5 -63q9 -56 44 -119.5t105 -108.5q31 -21 64 -16t62 23.5t57 49.5t48 61.5t35 60.5q32 66 39 184.5t-13 157.5q79 -80 122 -164t26 -184q-5 -33 -20.5 -69.5t-37.5 -80.5q-10 -19 -14.5 -29t-12 -26t-9 -23.5t-3 -19t2.5 -15.5t11 -9.5t19.5 -5t30.5 2.5 t42 8q57 20 91 34t87.5 44.5t87 64t65.5 88.5t47 122q38 172 -44.5 341.5t-246.5 278.5q22 -44 43 -129q39 -159 -32 -154q-15 2 -33 9q-79 33 -120.5 100t-44 175.5t48.5 257.5q-13 -8 -34 -23.5t-72.5 -66.5t-88.5 -105.5t-60 -138t-8 -166.5q2 -12 8 -41.5t8 -43t6 -39.5 t3.5 -39.5t-1 -33.5t-6 -31.5t-13.5 -24t-21 -20.5t-31 -12q-38 -10 -67 13t-40.5 61.5t-15 81.5t10.5 75q-52 -46 -83.5 -101t-39 -107t-7.5 -85z" /> +<glyph unicode="" d="M-61 600l26 40q6 10 20 30t49 63.5t74.5 85.5t97 90t116.5 83.5t132.5 59t145.5 23.5t145.5 -23.5t132.5 -59t116.5 -83.5t97 -90t74.5 -85.5t49 -63.5t20 -30l26 -40l-26 -40q-6 -10 -20 -30t-49 -63.5t-74.5 -85.5t-97 -90t-116.5 -83.5t-132.5 -59t-145.5 -23.5 t-145.5 23.5t-132.5 59t-116.5 83.5t-97 90t-74.5 85.5t-49 63.5t-20 30zM120 600q7 -10 40.5 -58t56 -78.5t68 -77.5t87.5 -75t103 -49.5t125 -21.5t123.5 20t100.5 45.5t85.5 71.5t66.5 75.5t58 81.5t47 66q-1 1 -28.5 37.5t-42 55t-43.5 53t-57.5 63.5t-58.5 54 q49 -74 49 -163q0 -124 -88 -212t-212 -88t-212 88t-88 212q0 85 46 158q-102 -87 -226 -258zM377 656q49 -124 154 -191l105 105q-37 24 -75 72t-57 84l-20 36z" /> +<glyph unicode="" d="M-61 600l26 40q6 10 20 30t49 63.5t74.5 85.5t97 90t116.5 83.5t132.5 59t145.5 23.5q61 0 121 -17l37 142h148l-314 -1200h-148l37 143q-82 21 -165 71.5t-140 102t-109.5 112t-72 88.5t-29.5 43zM120 600q210 -282 393 -336l37 141q-107 18 -178.5 101.5t-71.5 193.5 q0 85 46 158q-102 -87 -226 -258zM377 656q49 -124 154 -191l47 47l23 87q-30 28 -59 69t-44 68l-14 26zM780 161l38 145q22 15 44.5 34t46 44t40.5 44t41 50.5t33.5 43.5t33 44t24.5 34q-97 127 -140 175l39 146q67 -54 131.5 -125.5t87.5 -103.5t36 -52l26 -40l-26 -40 q-7 -12 -25.5 -38t-63.5 -79.5t-95.5 -102.5t-124 -100t-146.5 -79z" /> +<glyph unicode="" d="M-97.5 34q13.5 -34 50.5 -34h1294q37 0 50.5 35.5t-7.5 67.5l-642 1056q-20 34 -48 36.5t-48 -29.5l-642 -1066q-21 -32 -7.5 -66zM155 200l445 723l445 -723h-345v100h-200v-100h-345zM500 600l100 -300l100 300v100h-200v-100z" /> +<glyph unicode="" d="M100 262v41q0 20 11 44.5t26 38.5l363 325v339q0 62 44 106t106 44t106 -44t44 -106v-339l363 -325q15 -14 26 -38.5t11 -44.5v-41q0 -20 -12 -26.5t-29 5.5l-359 249v-263q100 -91 100 -113v-64q0 -20 -13 -28.5t-32 0.5l-94 78h-222l-94 -78q-19 -9 -32 -0.5t-13 28.5 v64q0 22 100 113v263l-359 -249q-17 -12 -29 -5.5t-12 26.5z" /> +<glyph unicode="" d="M0 50q0 -20 14.5 -35t35.5 -15h1000q21 0 35.5 15t14.5 35v750h-1100v-750zM0 900h1100v150q0 21 -14.5 35.5t-35.5 14.5h-150v100h-100v-100h-500v100h-100v-100h-150q-21 0 -35.5 -14.5t-14.5 -35.5v-150zM100 100v100h100v-100h-100zM100 300v100h100v-100h-100z M100 500v100h100v-100h-100zM300 100v100h100v-100h-100zM300 300v100h100v-100h-100zM300 500v100h100v-100h-100zM500 100v100h100v-100h-100zM500 300v100h100v-100h-100zM500 500v100h100v-100h-100zM700 100v100h100v-100h-100zM700 300v100h100v-100h-100zM700 500 v100h100v-100h-100zM900 100v100h100v-100h-100zM900 300v100h100v-100h-100zM900 500v100h100v-100h-100z" /> +<glyph unicode="" d="M0 200v200h259l600 600h241v198l300 -295l-300 -300v197h-159l-600 -600h-341zM0 800h259l122 -122l141 142l-181 180h-341v-200zM678 381l141 142l122 -123h159v198l300 -295l-300 -300v197h-241z" /> +<glyph unicode="" d="M0 400v600q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-600q0 -41 -29.5 -70.5t-70.5 -29.5h-596l-304 -300v300h-100q-41 0 -70.5 29.5t-29.5 70.5z" /> +<glyph unicode="" d="M100 600v200h300v-250q0 -113 6 -145q17 -92 102 -117q39 -11 92 -11q37 0 66.5 5.5t50 15.5t36 24t24 31.5t14 37.5t7 42t2.5 45t0 47v25v250h300v-200q0 -42 -3 -83t-15 -104t-31.5 -116t-58 -109.5t-89 -96.5t-129 -65.5t-174.5 -25.5t-174.5 25.5t-129 65.5t-89 96.5 t-58 109.5t-31.5 116t-15 104t-3 83zM100 900v300h300v-300h-300zM800 900v300h300v-300h-300z" /> +<glyph unicode="" d="M-30 411l227 -227l352 353l353 -353l226 227l-578 579z" /> +<glyph unicode="" d="M70 797l580 -579l578 579l-226 227l-353 -353l-352 353z" /> +<glyph unicode="" d="M-198 700l299 283l300 -283h-203v-400h385l215 -200h-800v600h-196zM402 1000l215 -200h381v-400h-198l299 -283l299 283h-200v600h-796z" /> +<glyph unicode="" d="M18 939q-5 24 10 42q14 19 39 19h896l38 162q5 17 18.5 27.5t30.5 10.5h94q20 0 35 -14.5t15 -35.5t-15 -35.5t-35 -14.5h-54l-201 -961q-2 -4 -6 -10.5t-19 -17.5t-33 -11h-31v-50q0 -20 -14.5 -35t-35.5 -15t-35.5 15t-14.5 35v50h-300v-50q0 -20 -14.5 -35t-35.5 -15 t-35.5 15t-14.5 35v50h-50q-21 0 -35.5 15t-14.5 35q0 21 14.5 35.5t35.5 14.5h535l48 200h-633q-32 0 -54.5 21t-27.5 43z" /> +<glyph unicode="" d="M0 0v800h1200v-800h-1200zM0 900v100h200q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5h500v-100h-1200z" /> +<glyph unicode="" d="M1 0l300 700h1200l-300 -700h-1200zM1 400v600h200q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5h500v-200h-1000z" /> +<glyph unicode="" d="M302 300h198v600h-198l298 300l298 -300h-198v-600h198l-298 -300z" /> +<glyph unicode="" d="M0 600l300 298v-198h600v198l300 -298l-300 -297v197h-600v-197z" /> +<glyph unicode="" d="M0 100v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM31 400l172 739q5 22 23 41.5t38 19.5h672q19 0 37.5 -22.5t23.5 -45.5l172 -732h-1138zM800 100h100v100h-100v-100z M1000 100h100v100h-100v-100z" /> +<glyph unicode="" d="M-101 600v50q0 24 25 49t50 38l25 13v-250l-11 5.5t-24 14t-30 21.5t-24 27.5t-11 31.5zM100 500v250v8v8v7t0.5 7t1.5 5.5t2 5t3 4t4.5 3.5t6 1.5t7.5 0.5h200l675 250v-850l-675 200h-38l47 -276q2 -12 -3 -17.5t-11 -6t-21 -0.5h-8h-83q-20 0 -34.5 14t-18.5 35 q-55 337 -55 351zM1100 200v850q0 21 14.5 35.5t35.5 14.5q20 0 35 -14.5t15 -35.5v-850q0 -20 -15 -35t-35 -15q-21 0 -35.5 15t-14.5 35z" /> +<glyph unicode="" d="M74 350q0 21 13.5 35.5t33.5 14.5h18l117 173l63 327q15 77 76 140t144 83l-18 32q-6 19 3 32t29 13h94q20 0 29 -10.5t3 -29.5q-18 -36 -18 -37q83 -19 144 -82.5t76 -140.5l63 -327l118 -173h17q20 0 33.5 -14.5t13.5 -35.5q0 -20 -13 -40t-31 -27q-8 -3 -23 -8.5 t-65 -20t-103 -25t-132.5 -19.5t-158.5 -9q-125 0 -245.5 20.5t-178.5 40.5l-58 20q-18 7 -31 27.5t-13 40.5zM497 110q12 -49 40 -79.5t63 -30.5t63 30.5t39 79.5q-48 -6 -102 -6t-103 6z" /> +<glyph unicode="" d="M21 445l233 -45l-78 -224l224 78l45 -233l155 179l155 -179l45 233l224 -78l-78 224l234 45l-180 155l180 156l-234 44l78 225l-224 -78l-45 233l-155 -180l-155 180l-45 -233l-224 78l78 -225l-233 -44l179 -156z" /> +<glyph unicode="" d="M0 200h200v600h-200v-600zM300 275q0 -75 100 -75h61q124 -100 139 -100h250q46 0 83 57l238 344q29 31 29 74v100q0 44 -30.5 84.5t-69.5 40.5h-328q28 118 28 125v150q0 44 -30.5 84.5t-69.5 40.5h-50q-27 0 -51 -20t-38 -48l-96 -198l-145 -196q-20 -26 -20 -63v-400z M400 300v375l150 213l100 212h50v-175l-50 -225h450v-125l-250 -375h-214l-136 100h-100z" /> +<glyph unicode="" d="M0 400v600h200v-600h-200zM300 525v400q0 75 100 75h61q124 100 139 100h250q46 0 83 -57l238 -344q29 -31 29 -74v-100q0 -44 -30.5 -84.5t-69.5 -40.5h-328q28 -118 28 -125v-150q0 -44 -30.5 -84.5t-69.5 -40.5h-50q-27 0 -51 20t-38 48l-96 198l-145 196 q-20 26 -20 63zM400 525l150 -212l100 -213h50v175l-50 225h450v125l-250 375h-214l-136 -100h-100v-375z" /> +<glyph unicode="" d="M8 200v600h200v-600h-200zM308 275v525q0 17 14 35.5t28 28.5l14 9l362 230q14 6 25 6q17 0 29 -12l109 -112q14 -14 14 -34q0 -18 -11 -32l-85 -121h302q85 0 138.5 -38t53.5 -110t-54.5 -111t-138.5 -39h-107l-130 -339q-7 -22 -20.5 -41.5t-28.5 -19.5h-341 q-7 0 -90 81t-83 94zM408 289l100 -89h293l131 339q6 21 19.5 41t28.5 20h203q16 0 25 15t9 36q0 20 -9 34.5t-25 14.5h-457h-6.5h-7.5t-6.5 0.5t-6 1t-5 1.5t-5.5 2.5t-4 4t-4 5.5q-5 12 -5 20q0 14 10 27l147 183l-86 83l-339 -236v-503z" /> +<glyph unicode="" d="M-101 651q0 72 54 110t139 38l302 -1l-85 121q-11 16 -11 32q0 21 14 34l109 113q13 12 29 12q11 0 25 -6l365 -230q7 -4 17 -10.5t26.5 -26t16.5 -36.5v-526q0 -13 -86 -93.5t-94 -80.5h-341q-16 0 -29.5 20t-19.5 41l-130 339h-107q-84 0 -139 39t-55 111zM-1 601h222 q15 0 28.5 -20.5t19.5 -40.5l131 -339h293l107 89v502l-343 237l-87 -83l145 -184q10 -11 10 -26q0 -11 -5 -20q-1 -3 -3.5 -5.5l-4 -4t-5 -2.5t-5.5 -1.5t-6.5 -1t-6.5 -0.5h-7.5h-6.5h-476v-100zM1000 201v600h200v-600h-200z" /> +<glyph unicode="" d="M97 719l230 -363q4 -6 10.5 -15.5t26 -25t36.5 -15.5h525q13 0 94 83t81 90v342q0 15 -20 28.5t-41 19.5l-339 131v106q0 84 -39 139t-111 55t-110 -53.5t-38 -138.5v-302l-121 84q-15 12 -33.5 11.5t-32.5 -13.5l-112 -110q-22 -22 -6 -53zM172 739l83 86l183 -146 q22 -18 47 -5q3 1 5.5 3.5l4 4t2.5 5t1.5 5.5t1 6.5t0.5 6.5v7.5v6.5v456q0 22 25 31t50 -0.5t25 -30.5v-202q0 -16 20 -29.5t41 -19.5l339 -130v-294l-89 -100h-503zM400 0v200h600v-200h-600z" /> +<glyph unicode="" d="M2 585q-16 -31 6 -53l112 -110q13 -13 32 -13.5t34 10.5l121 85q0 -51 -0.5 -153.5t-0.5 -148.5q0 -84 38.5 -138t110.5 -54t111 55t39 139v106l339 131q20 6 40.5 19.5t20.5 28.5v342q0 7 -81 90t-94 83h-525q-17 0 -35.5 -14t-28.5 -28l-10 -15zM77 565l236 339h503 l89 -100v-294l-340 -130q-20 -6 -40 -20t-20 -29v-202q0 -22 -25 -31t-50 0t-25 31v456v14.5t-1.5 11.5t-5 12t-9.5 7q-24 13 -46 -5l-184 -146zM305 1104v200h600v-200h-600z" /> +<glyph unicode="" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q162 0 299.5 -80t217.5 -218t80 -300t-80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM298 701l2 -201h300l-2 -194l402 294l-402 298v-197h-300z" /> +<glyph unicode="" d="M0 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t231.5 47.5q122 0 232.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-218 -217.5t-300 -80t-299.5 80t-217.5 217.5t-80 299.5zM200 600l402 -294l-2 194h300l2 201h-300v197z" /> +<glyph unicode="" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q162 0 299.5 -80t217.5 -218t80 -300t-80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM300 600h200v-300h200v300h200l-300 400z" /> +<glyph unicode="" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q162 0 299.5 -80t217.5 -218t80 -300t-80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM300 600l300 -400l300 400h-200v300h-200v-300h-200z" /> +<glyph unicode="" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q121 0 231.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM254 780q-8 -33 5.5 -92.5t7.5 -87.5q0 -9 17 -44t16 -60 q12 0 23 -5.5t23 -15t20 -13.5q24 -12 108 -42q22 -8 53 -31.5t59.5 -38.5t57.5 -11q8 -18 -15 -55t-20 -57q42 -71 87 -80q0 -6 -3 -15.5t-3.5 -14.5t4.5 -17q104 -3 221 112q30 29 47 47t34.5 49t20.5 62q-14 9 -37 9.5t-36 7.5q-14 7 -49 15t-52 19q-9 0 -39.5 -0.5 t-46.5 -1.5t-39 -6.5t-39 -16.5q-50 -35 -66 -12q-4 2 -3.5 25.5t0.5 25.5q-6 13 -26.5 17t-24.5 7q2 22 -2 41t-16.5 28t-38.5 -20q-23 -25 -42 4q-19 28 -8 58q6 16 22 22q6 -1 26 -1.5t33.5 -4t19.5 -13.5q12 -19 32 -37.5t34 -27.5l14 -8q0 3 9.5 39.5t5.5 57.5 q-4 23 14.5 44.5t22.5 31.5q5 14 10 35t8.5 31t15.5 22.5t34 21.5q-6 18 10 37q8 0 23.5 -1.5t24.5 -1.5t20.5 4.5t20.5 15.5q-10 23 -30.5 42.5t-38 30t-49 26.5t-43.5 23q11 39 2 44q31 -13 58 -14.5t39 3.5l11 4q7 36 -16.5 53.5t-64.5 28.5t-56 23q-19 -3 -37 0 q-15 -12 -36.5 -21t-34.5 -12t-44 -8t-39 -6q-15 -3 -45.5 0.5t-45.5 -2.5q-21 -7 -52 -26.5t-34 -34.5q-3 -11 6.5 -22.5t8.5 -18.5q-3 -34 -27.5 -90.5t-29.5 -79.5zM518 916q3 12 16 30t16 25q10 -10 18.5 -10t14 6t14.5 14.5t16 12.5q0 -24 17 -66.5t17 -43.5 q-9 2 -31 5t-36 5t-32 8t-30 14zM692 1003h1h-1z" /> +<glyph unicode="" d="M0 164.5q0 21.5 15 37.5l600 599q-33 101 6 201.5t135 154.5q164 92 306 -9l-259 -138l145 -232l251 126q13 -175 -151 -267q-123 -70 -253 -23l-596 -596q-15 -16 -36.5 -16t-36.5 16l-111 110q-15 15 -15 36.5z" /> +<glyph unicode="" horiz-adv-x="1220" d="M0 196v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM0 596v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000 q-41 0 -70.5 29.5t-29.5 70.5zM0 996v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM600 596h500v100h-500v-100zM800 196h300v100h-300v-100zM900 996h200v100h-200v-100z" /> +<glyph unicode="" d="M100 1100v100h1000v-100h-1000zM150 1000h900l-350 -500v-300l-200 -200v500z" /> +<glyph unicode="" d="M0 200v200h1200v-200q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM0 500v400q0 41 29.5 70.5t70.5 29.5h300v100q0 41 29.5 70.5t70.5 29.5h200q41 0 70.5 -29.5t29.5 -70.5v-100h300q41 0 70.5 -29.5t29.5 -70.5v-400h-500v100h-200v-100h-500z M500 1000h200v100h-200v-100z" /> +<glyph unicode="" d="M0 0v400l129 -129l200 200l142 -142l-200 -200l129 -129h-400zM0 800l129 129l200 -200l142 142l-200 200l129 129h-400v-400zM729 329l142 142l200 -200l129 129v-400h-400l129 129zM729 871l200 200l-129 129h400v-400l-129 129l-200 -200z" /> +<glyph unicode="" d="M0 596q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM182 596q0 -172 121.5 -293t292.5 -121t292.5 121t121.5 293q0 171 -121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM291 655 q0 23 15.5 38.5t38.5 15.5t39 -16t16 -38q0 -23 -16 -39t-39 -16q-22 0 -38 16t-16 39zM400 850q0 22 16 38.5t39 16.5q22 0 38 -16t16 -39t-16 -39t-38 -16q-23 0 -39 16.5t-16 38.5zM514 609q0 32 20.5 56.5t51.5 29.5l122 126l1 1q-9 14 -9 28q0 22 16 38.5t39 16.5 q22 0 38 -16t16 -39t-16 -39t-38 -16q-14 0 -29 10l-55 -145q17 -22 17 -51q0 -36 -25.5 -61.5t-61.5 -25.5t-61.5 25.5t-25.5 61.5zM800 655q0 22 16 38t39 16t38.5 -15.5t15.5 -38.5t-16 -39t-38 -16q-23 0 -39 16t-16 39z" /> +<glyph unicode="" d="M-40 375q-13 -95 35 -173q35 -57 94 -89t129 -32q63 0 119 28q33 16 65 40.5t52.5 45.5t59.5 64q40 44 57 61l394 394q35 35 47 84t-3 96q-27 87 -117 104q-20 2 -29 2q-46 0 -78.5 -16.5t-67.5 -51.5l-389 -396l-7 -7l69 -67l377 373q20 22 39 38q23 23 50 23 q38 0 53 -36q16 -39 -20 -75l-547 -547q-52 -52 -125 -52q-55 0 -100 33t-54 96q-5 35 2.5 66t31.5 63t42 50t56 54q24 21 44 41l348 348q52 52 82.5 79.5t84 54t107.5 26.5q25 0 48 -4q95 -17 154 -94.5t51 -175.5q-7 -101 -98 -192l-252 -249l-253 -256l7 -7l69 -60 l517 511q67 67 95 157t11 183q-16 87 -67 154t-130 103q-69 33 -152 33q-107 0 -197 -55q-40 -24 -111 -95l-512 -512q-68 -68 -81 -163z" /> +<glyph unicode="" d="M80 784q0 131 98.5 229.5t230.5 98.5q143 0 241 -129q103 129 246 129q129 0 226 -98.5t97 -229.5q0 -46 -17.5 -91t-61 -99t-77 -89.5t-104.5 -105.5q-197 -191 -293 -322l-17 -23l-16 23q-43 58 -100 122.5t-92 99.5t-101 100q-71 70 -104.5 105.5t-77 89.5t-61 99 t-17.5 91zM250 784q0 -27 30.5 -70t61.5 -75.5t95 -94.5l22 -22q93 -90 190 -201q82 92 195 203l12 12q64 62 97.5 97t64.5 79t31 72q0 71 -48 119.5t-105 48.5q-74 0 -132 -83l-118 -171l-114 174q-51 80 -123 80q-60 0 -109.5 -49.5t-49.5 -118.5z" /> +<glyph unicode="" d="M57 353q0 -95 66 -159l141 -142q68 -66 159 -66q93 0 159 66l283 283q66 66 66 159t-66 159l-141 141q-8 9 -19 17l-105 -105l212 -212l-389 -389l-247 248l95 95l-18 18q-46 45 -75 101l-55 -55q-66 -66 -66 -159zM269 706q0 -93 66 -159l141 -141q7 -7 19 -17l105 105 l-212 212l389 389l247 -247l-95 -96l18 -17q47 -49 77 -100l29 29q35 35 62.5 88t27.5 96q0 93 -66 159l-141 141q-66 66 -159 66q-95 0 -159 -66l-283 -283q-66 -64 -66 -159z" /> +<glyph unicode="" d="M200 100v953q0 21 30 46t81 48t129 38t163 15t162 -15t127 -38t79 -48t29 -46v-953q0 -41 -29.5 -70.5t-70.5 -29.5h-600q-41 0 -70.5 29.5t-29.5 70.5zM300 300h600v700h-600v-700zM496 150q0 -43 30.5 -73.5t73.5 -30.5t73.5 30.5t30.5 73.5t-30.5 73.5t-73.5 30.5 t-73.5 -30.5t-30.5 -73.5z" /> +<glyph unicode="" d="M0 0l303 380l207 208l-210 212h300l267 279l-35 36q-15 14 -15 35t15 35q14 15 35 15t35 -15l283 -282q15 -15 15 -36t-15 -35q-14 -15 -35 -15t-35 15l-36 35l-279 -267v-300l-212 210l-208 -207z" /> +<glyph unicode="" d="M295 433h139q5 -77 48.5 -126.5t117.5 -64.5v335q-6 1 -15.5 4t-11.5 3q-46 14 -79 26.5t-72 36t-62.5 52t-40 72.5t-16.5 99q0 92 44 159.5t109 101t144 40.5v78h100v-79q38 -4 72.5 -13.5t75.5 -31.5t71 -53.5t51.5 -84t24.5 -118.5h-159q-8 72 -35 109.5t-101 50.5 v-307l64 -14q34 -7 64 -16.5t70 -31.5t67.5 -52t47.5 -80.5t20 -112.5q0 -139 -89 -224t-244 -96v-77h-100v78q-152 17 -237 104q-40 40 -52.5 93.5t-15.5 139.5zM466 889q0 -29 8 -51t16.5 -34t29.5 -22.5t31 -13.5t38 -10q7 -2 11 -3v274q-61 -8 -97.5 -37.5t-36.5 -102.5 zM700 237q170 18 170 151q0 64 -44 99.5t-126 60.5v-311z" /> +<glyph unicode="" d="M100 600v100h166q-24 49 -44 104q-10 26 -14.5 55.5t-3 72.5t25 90t68.5 87q97 88 263 88q129 0 230 -89t101 -208h-153q0 52 -34 89.5t-74 51.5t-76 14q-37 0 -79 -14.5t-62 -35.5q-41 -44 -41 -101q0 -28 16.5 -69.5t28 -62.5t41.5 -72h241v-100h-197q8 -50 -2.5 -115 t-31.5 -94q-41 -59 -99 -113q35 11 84 18t70 7q33 1 103 -16t103 -17q76 0 136 30l50 -147q-41 -25 -80.5 -36.5t-59 -13t-61.5 -1.5q-23 0 -128 33t-155 29q-39 -4 -82 -17t-66 -25l-24 -11l-55 145l16.5 11t15.5 10t13.5 9.5t14.5 12t14.5 14t17.5 18.5q48 55 54 126.5 t-30 142.5h-221z" /> +<glyph unicode="" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM602 900l298 300l298 -300h-198v-900h-200v900h-198z" /> +<glyph unicode="" d="M2 300h198v900h200v-900h198l-298 -300zM700 0v200h100v-100h200v-100h-300zM700 400v100h300v-200h-99v-100h-100v100h99v100h-200zM700 700v500h300v-500h-100v100h-100v-100h-100zM801 900h100v200h-100v-200z" /> +<glyph unicode="" d="M2 300h198v900h200v-900h198l-298 -300zM700 0v500h300v-500h-100v100h-100v-100h-100zM700 700v200h100v-100h200v-100h-300zM700 1100v100h300v-200h-99v-100h-100v100h99v100h-200zM801 200h100v200h-100v-200z" /> +<glyph unicode="" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM800 100v400h300v-500h-100v100h-200zM800 1100v100h200v-500h-100v400h-100zM901 200h100v200h-100v-200z" /> +<glyph unicode="" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM800 400v100h200v-500h-100v400h-100zM800 800v400h300v-500h-100v100h-200zM901 900h100v200h-100v-200z" /> +<glyph unicode="" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM700 100v200h500v-200h-500zM700 400v200h400v-200h-400zM700 700v200h300v-200h-300zM700 1000v200h200v-200h-200z" /> +<glyph unicode="" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM700 100v200h200v-200h-200zM700 400v200h300v-200h-300zM700 700v200h400v-200h-400zM700 1000v200h500v-200h-500z" /> +<glyph unicode="" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h300q162 0 281 -118.5t119 -281.5v-300q0 -165 -118.5 -282.5t-281.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500z" /> +<glyph unicode="" d="M0 400v300q0 163 119 281.5t281 118.5h300q165 0 282.5 -117.5t117.5 -282.5v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-163 0 -281.5 117.5t-118.5 282.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM400 300l333 250l-333 250v-500z" /> +<glyph unicode="" d="M0 400v300q0 163 117.5 281.5t282.5 118.5h300q163 0 281.5 -119t118.5 -281v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM300 700l250 -333l250 333h-500z" /> +<glyph unicode="" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h300q165 0 282.5 -117.5t117.5 -282.5v-300q0 -162 -118.5 -281t-281.5 -119h-300q-165 0 -282.5 118.5t-117.5 281.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM300 400h500l-250 333z" /> +<glyph unicode="" d="M0 400v300h300v200l400 -350l-400 -350v200h-300zM500 0v200h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5h-500v200h400q165 0 282.5 -117.5t117.5 -282.5v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-400z" /> +<glyph unicode="" d="M217 519q8 -19 31 -19h302q-155 -438 -160 -458q-5 -21 4 -32l9 -8h9q14 0 26 15q11 13 274.5 321.5t264.5 308.5q14 19 5 36q-8 17 -31 17l-301 -1q1 4 78 219.5t79 227.5q2 15 -5 27l-9 9h-9q-15 0 -25 -16q-4 -6 -98 -111.5t-228.5 -257t-209.5 -237.5q-16 -19 -6 -41 z" /> +<glyph unicode="" d="M0 400q0 -165 117.5 -282.5t282.5 -117.5h300q47 0 100 15v185h-500q-41 0 -70.5 29.5t-29.5 70.5v500q0 41 29.5 70.5t70.5 29.5h500v185q-14 4 -114 7.5t-193 5.5l-93 2q-165 0 -282.5 -117.5t-117.5 -282.5v-300zM600 400v300h300v200l400 -350l-400 -350v200h-300z " /> +<glyph unicode="" d="M0 400q0 -165 117.5 -282.5t282.5 -117.5h300q163 0 281.5 117.5t118.5 282.5v98l-78 73l-122 -123v-148q0 -41 -29.5 -70.5t-70.5 -29.5h-500q-41 0 -70.5 29.5t-29.5 70.5v500q0 41 29.5 70.5t70.5 29.5h156l118 122l-74 78h-100q-165 0 -282.5 -117.5t-117.5 -282.5 v-300zM496 709l353 342l-149 149h500v-500l-149 149l-342 -353z" /> +<glyph unicode="" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM406 600 q0 80 57 137t137 57t137 -57t57 -137t-57 -137t-137 -57t-137 57t-57 137z" /> +<glyph unicode="" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 800l445 -500l450 500h-295v400h-300v-400h-300zM900 150h100v50h-100v-50z" /> +<glyph unicode="" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 700h300v-300h300v300h295l-445 500zM900 150h100v50h-100v-50z" /> +<glyph unicode="" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 705l305 -305l596 596l-154 155l-442 -442l-150 151zM900 150h100v50h-100v-50z" /> +<glyph unicode="" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 988l97 -98l212 213l-97 97zM200 400l697 1l3 699l-250 -239l-149 149l-212 -212l149 -149zM900 150h100v50h-100v-50z" /> +<glyph unicode="" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM200 612l212 -212l98 97l-213 212zM300 1200l239 -250l-149 -149l212 -212l149 148l249 -237l-1 697zM900 150h100v50h-100v-50z" /> +<glyph unicode="" d="M23 415l1177 784v-1079l-475 272l-310 -393v416h-392zM494 210l672 938l-672 -712v-226z" /> +<glyph unicode="" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-850q0 -21 -15 -35.5t-35 -14.5h-150v400h-700v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 1000h100v200h-100v-200z" /> +<glyph unicode="" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-218l-276 -275l-120 120l-126 -127h-378v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM581 306l123 123l120 -120l353 352l123 -123l-475 -476zM600 1000h100v200h-100v-200z" /> +<glyph unicode="" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-269l-103 -103l-170 170l-298 -298h-329v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 1000h100v200h-100v-200zM700 133l170 170l-170 170l127 127l170 -170l170 170l127 -128l-170 -169l170 -170 l-127 -127l-170 170l-170 -170z" /> +<glyph unicode="" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-300h-400v-200h-500v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 300l300 -300l300 300h-200v300h-200v-300h-200zM600 1000v200h100v-200h-100z" /> +<glyph unicode="" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-402l-200 200l-298 -298h-402v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 300h200v-300h200v300h200l-300 300zM600 1000v200h100v-200h-100z" /> +<glyph unicode="" d="M0 250q0 -21 14.5 -35.5t35.5 -14.5h1100q21 0 35.5 14.5t14.5 35.5v550h-1200v-550zM0 900h1200v150q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-150zM100 300v200h400v-200h-400z" /> +<glyph unicode="" d="M0 400l300 298v-198h400v-200h-400v-198zM100 800v200h100v-200h-100zM300 800v200h100v-200h-100zM500 800v200h400v198l300 -298l-300 -298v198h-400zM800 300v200h100v-200h-100zM1000 300h100v200h-100v-200z" /> +<glyph unicode="" d="M100 700v400l50 100l50 -100v-300h100v300l50 100l50 -100v-300h100v300l50 100l50 -100v-400l-100 -203v-447q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v447zM800 597q0 -29 10.5 -55.5t25 -43t29 -28.5t25.5 -18l10 -5v-397q0 -21 14.5 -35.5 t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v1106q0 31 -18 40.5t-44 -7.5l-276 -116q-25 -17 -43.5 -51.5t-18.5 -65.5v-359z" /> +<glyph unicode="" d="M100 0h400v56q-75 0 -87.5 6t-12.5 44v394h500v-394q0 -38 -12.5 -44t-87.5 -6v-56h400v56q-4 0 -11 0.5t-24 3t-30 7t-24 15t-11 24.5v888q0 22 25 34.5t50 13.5l25 2v56h-400v-56q75 0 87.5 -6t12.5 -44v-394h-500v394q0 38 12.5 44t87.5 6v56h-400v-56q4 0 11 -0.5 t24 -3t30 -7t24 -15t11 -24.5v-888q0 -22 -25 -34.5t-50 -13.5l-25 -2v-56z" /> +<glyph unicode="" d="M0 300q0 -41 29.5 -70.5t70.5 -29.5h300q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5h-300q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM100 100h400l200 200h105l295 98v-298h-425l-100 -100h-375zM100 300v200h300v-200h-300zM100 600v200h300v-200h-300z M100 1000h400l200 -200v-98l295 98h105v200h-425l-100 100h-375zM700 402v163l400 133v-163z" /> +<glyph unicode="" d="M16.5 974.5q0.5 -21.5 16 -90t46.5 -140t104 -177.5t175 -208q103 -103 207.5 -176t180 -103.5t137 -47t92.5 -16.5l31 1l163 162q17 18 13.5 41t-22.5 37l-192 136q-19 14 -45 12t-42 -19l-118 -118q-142 101 -268 227t-227 268l118 118q17 17 20 41.5t-11 44.5 l-139 194q-14 19 -36.5 22t-40.5 -14l-162 -162q-1 -11 -0.5 -32.5z" /> +<glyph unicode="" d="M0 50v212q0 20 10.5 45.5t24.5 39.5l365 303v50q0 4 1 10.5t12 22.5t30 28.5t60 23t97 10.5t97 -10t60 -23.5t30 -27.5t12 -24l1 -10v-50l365 -303q14 -14 24.5 -39.5t10.5 -45.5v-212q0 -21 -14.5 -35.5t-35.5 -14.5h-1100q-20 0 -35 14.5t-15 35.5zM0 712 q0 -21 14.5 -33.5t34.5 -8.5l202 33q20 4 34.5 21t14.5 38v146q141 24 300 24t300 -24v-146q0 -21 14.5 -38t34.5 -21l202 -33q20 -4 34.5 8.5t14.5 33.5v200q-6 8 -19 20.5t-63 45t-112 57t-171 45t-235 20.5q-92 0 -175 -10.5t-141.5 -27t-108.5 -36.5t-81.5 -40 t-53.5 -36.5t-31 -27.5l-9 -10v-200z" /> +<glyph unicode="" d="M100 0v100h1100v-100h-1100zM175 200h950l-125 150v250l100 100v400h-100v-200h-100v200h-200v-200h-100v200h-200v-200h-100v200h-100v-400l100 -100v-250z" /> +<glyph unicode="" d="M100 0h300v400q0 41 -29.5 70.5t-70.5 29.5h-100q-41 0 -70.5 -29.5t-29.5 -70.5v-400zM500 0v1000q0 41 29.5 70.5t70.5 29.5h100q41 0 70.5 -29.5t29.5 -70.5v-1000h-300zM900 0v700q0 41 29.5 70.5t70.5 29.5h100q41 0 70.5 -29.5t29.5 -70.5v-700h-300z" /> +<glyph unicode="" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v300h-200v100h200v100h-300v-300h200v-100h-200v-100zM600 300h200v100h100v300h-100v100h-200v-500 zM700 400v300h100v-300h-100z" /> +<glyph unicode="" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h100v200h100v-200h100v500h-100v-200h-100v200h-100v-500zM600 300h200v100h100v300h-100v100h-200v-500 zM700 400v300h100v-300h-100z" /> +<glyph unicode="" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v100h-200v300h200v100h-300v-500zM600 300h300v100h-200v300h200v100h-300v-500z" /> +<glyph unicode="" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 550l300 -150v300zM600 400l300 150l-300 150v-300z" /> +<glyph unicode="" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300v500h700v-500h-700zM300 400h130q41 0 68 42t27 107t-28.5 108t-66.5 43h-130v-300zM575 549 q0 -65 27 -107t68 -42h130v300h-130q-38 0 -66.5 -43t-28.5 -108z" /> +<glyph unicode="" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v300h-200v100h200v100h-300v-300h200v-100h-200v-100zM601 300h100v100h-100v-100zM700 700h100 v-400h100v500h-200v-100z" /> +<glyph unicode="" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v400h-200v100h-100v-500zM301 400v200h100v-200h-100zM601 300h100v100h-100v-100zM700 700h100 v-400h100v500h-200v-100z" /> +<glyph unicode="" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 700v100h300v-300h-99v-100h-100v100h99v200h-200zM201 300v100h100v-100h-100zM601 300v100h100v-100h-100z M700 700v100h200v-500h-100v400h-100z" /> +<glyph unicode="" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM400 500v200 l100 100h300v-100h-300v-200h300v-100h-300z" /> +<glyph unicode="" d="M0 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM182 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM400 400v400h300 l100 -100v-100h-100v100h-200v-100h200v-100h-200v-100h-100zM700 400v100h100v-100h-100z" /> +<glyph unicode="" d="M-14 494q0 -80 56.5 -137t135.5 -57h222v300h400v-300h128q120 0 205 86.5t85 207.5t-85 207t-205 86q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5zM300 200h200v300h200v-300h200 l-300 -300z" /> +<glyph unicode="" d="M-14 494q0 -80 56.5 -137t135.5 -57h8l414 414l403 -403q94 26 154.5 104.5t60.5 178.5q0 120 -85 206.5t-205 86.5q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5zM300 200l300 300 l300 -300h-200v-300h-200v300h-200z" /> +<glyph unicode="" d="M100 200h400v-155l-75 -45h350l-75 45v155h400l-270 300h170l-270 300h170l-300 333l-300 -333h170l-270 -300h170z" /> +<glyph unicode="" d="M121 700q0 -53 28.5 -97t75.5 -65q-4 -16 -4 -38q0 -74 52.5 -126.5t126.5 -52.5q56 0 100 30v-306l-75 -45h350l-75 45v306q46 -30 100 -30q74 0 126.5 52.5t52.5 126.5q0 24 -9 55q50 32 79.5 83t29.5 112q0 90 -61.5 155.5t-150.5 71.5q-26 89 -99.5 145.5 t-167.5 56.5q-116 0 -197.5 -81.5t-81.5 -197.5q0 -4 1 -11.5t1 -11.5q-14 2 -23 2q-74 0 -126.5 -52.5t-52.5 -126.5z" /> +</font> +</defs></svg> \ No newline at end of file diff --git a/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.ttf b/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..67fa00bf83801d2fa568546b982c80d27f6ef74e GIT binary patch literal 41280 zcmc${2b>$#wLd<0X4JKkMs=IoY9(#guC%-Ix~!LV@5XgawLzwtVoFRi&4B<;Yzzq| z1QHw)z@da0*@PsIyqA!`6G@b6oWOe_b_$P#@)GbXG2Zd-d+unfZAkvV-{<pRThcUX z?mhS1bI<vnG6E9>LBX3Wc;?Pswd9i3FaAXkSUrx`&zn7GF0<l{z@}h7wrpi4d*Ks{ zZpZ!*_Sc_(*@n#v|6=<B_P;3z;#KEwxh5twNq6GM+Hl@_!R8AuTe&~;1opdee&dB3 zuHKB}9zifaOy@7W^!f`Tkz5@6UloMAr(d*jLqR-mNEd{A4&i+7ML1y3%5Fi}RgL|| zi!Qt7y6=5Y*@^w>_`M^SUUB}0?t9iO6@<@rQX4MYaNTB6W_twTb8q4L*yS58+j!vF z2j3Nh`>lc?ZQXpu)z^G$?&B8=!spQk>+PGb+PGPLztt}YU&eW%<JyhqT`=_QiZ`)O z{War7)DeC><I$he=TDu%_l-|m2S4M&9<>aO!9EjS$4lmWxSf0(+a;I;S#pX$!?81r zPxe(ID}q`APM!R3^`f;)g#n@JcY^fY<DiwPTG)y!c}ptai19rMd-SR|&aq3eM_1Jg zGFy(%<@gm7QCp}IVnVC1CuWajV&}%5Zty0LrC8dQb{~=s*$&klYChC=Xu+X%ht?mu z_|Wx-?mqOuVcX%F!_9~L4$nQj;PAS`7azX<@ZE>+Km6eDgyYBYd&V!e;1`7xevutA z9r7HC9qK$ZaA-Mx@w`Ku58Zlb*I{<pb2xUm^YFmo`G=PuUVnJ=;ad;yI{X0tMRxqZ zj{pAn>&GuRWclsyf4l#;7ri09Ui*6RHTP@wSWT=t=8ZXH=9myY8a)#IAo_0fKca`D z*F~?2UK+h1x;}btbX|01bV+nx^t9+egvQ|i`5yx>jQlJU@$>W=|A&(_6vm%?s-YdZ z;Q!}OV(bZjm;rz1-#tQ;_`j;qrV74A>f+@?>cTDSR3S05S~a&0%~;2e-Lx)tKxMv; z>UNd2#a>sPt?jDVwrIuBoW#0#yDGI^Tpd#fmJh|%fpzVw+(uuGC*n5@{id$Gt`64? z4cEQ9t}YQ*O|3)f+%4<)iFNDnd#1Lkv(9K&&23r(y9;-Z-F4Pkb*g}$v9xK8{LsMY zA#0mgiS=dLRa;x^Cc4QF@cS`UN-jvmR5`U!6_yWe-?)84j5em!#pCPhw)4Fe#va|! zZnVx*=ZWJcj<(n@cz2v_v5abIJ!>cyo0pio;gZ-;tZ<(36Leh_-5IxzZI8{{K6gW6 zdu)4x-!7pFD~8koT#5eCZPkH|w1e-s_?>1Ptd7U)Vh6W_4EWLlv~6{zZD=1ZbGId8 z2P-#E#D*5Ftc$B`-OzS)XhC9oBDQ_O_QVEi33Z3wsXZPV1}}y|p$^c7cTxw?(8S!t zhD+9u?+Ja?*M?4Pzmv$eu#nhpQDe)8rq_KJXZ&sZgaI}%ILH=#(<7WO@OQd+HCi6q zzG5hG9$KFmtiuOO41)3lD~5_fOqg~4V3EZbKGfLxYR$%a-ctNxpiRY5&;@Vp#E_7w zkT-73wkGUcB*ievEJBCIgv|7!MHb)9YG%{FPcKR$HU&+h!zMahw3wx1(~FFb=ajgT z%qfW`HlV-tm%m7{V~3g`k(p2s3i4uku@Dj(1y#tXRXLTFRY#Vo)fv@yP&H*$Z&|fu zwHnqcbawfA;^}-y$tn4eB_4=}ENLa7Skn0dlb+x4d<icm>BA$NM<yN6hxujHC;ajI zI)sHn(JlzBbaM;8xhY#@g1vR$0F!L3Om${d`$1LAs<yH!XNxvFow8YMtwp<yHtm9~ zRjcByt6_2U)A+}Bu{O3#->e@P+tN3)UA)gG`7`p@g}ksuP_r4esa$Nz(oZ#Y*myhQ zydBZ3YRahfIn`WNYqM$~qdLmPfP*d!c&KGlGHRZ;tf8!hquH$5;L+MytLn+B9c9&> z)%sYg){s}cs-;hDSBj2Uwy&>`sF=@n=M(u{Z@xE|4FyAq?hY~0;1VryOWYj5TSU%f z`^BD|*<wyKq℞P`J|cdg0FGqEGC9fAe(nbGgL}Bh`JgXZqNU1^s}T?Z&&Uvu{=| z5MH=A_x0$8O;41sZ5(v6BZW*);fXVLeCNVT@<W|9{<bsv3mv_Mh1U$Wx@$Yv_B?&b zC%)A2)ODQCN^F<BSbPEe<>kB}m6<AMG?Ov%AZtmw{n%C_Ck@}oQb5~67xs_8&)Vb{ z<<o?K5EWD@qq@o%Go}VJS_nU(*(AlQIh4M>&MwIx%*C_4-Kj)_rGq6J%mIJM#ave| z6W_b;$tSPtXlr}!^3VTT99+%bTYl9u??3I@aP6-itZ}+F;Z~$u6l4`VD`Otmv91d} zER<(S#b#32t`d6j;d0id9}tJcA&h=ofez}MOMLIh@MGecx|6jH@5S#($3Hm!f&3l$ zJD6Q&(h@95us6di-`kyGsRm0GTk_j84vH5XTyyaJs;URwjqa+=zdhYJa8^~?^<Wk5 zU*Ts}Rt1}o6N*?{T2)I~l`xI$8P$4FmC8lQN}MB^z_?b4Hmznbu7eX-i8BS$sVA<; zDmCudA&^oXetr1$LP1Q?@4Eym=F78?96~C>^8KtwNh&Fei-jtC-6@O7#R52HmK*O{ zb{aZAuyEO0ulKHHb62|T!ydZ}`=7qNxi+xAMLg%B;s5c3YOm_eH`jzt&r4U@9n$wC zpM7|lQe8tUd+7K(@(<((1)oqStP_e*@>*4IMh%tKx(s^5)cTCd4yu8&8t{;8P)(Qv zVE3AU;@u~S9&cl)Pc<pvd_nWNFa>OVYDiH%eQKR|9}_GlobT-NdeEVO-@<}^H#0Y+ z8Q5L)1Y^CPR4l~m!D{tOS)0XjnbmLA4_v#m^vM^Q_j}*d-(&C6IsFf%o!9CIaPl&X zg|#geFV+9@;`eX`hJ?@aA^BN(won6(WNK|j6%G<ly2@Ie!P4FRVuXe8CI<X2$<iSg zrkru@wb!?G-gw<7hI(gRfBWA4{wHp~ewO4J*s`)+UNC#ke7Sw)mVv(OZ@s0sdUf%Z zTdxPLj(<~_C*O~;w+l|NRNR;I#hK5>d{TZs`|W+=eeBozwtMwk^=<ckPLyI?DE(QV z$$a{|>|gMSwn`IzBM5z3t%CUFVn_xPg)&+-Z}Nm+_k}F^P&%JTTTZ;stRF1+?)Mjd z@9iZ^PjW}`nw`J<%#J^P=9j<Zbiy0v6SNu3;~v)2keb1|d$YkX^P3X^7GS%QGu8i9 zXC~RMdl)O+pDS%u)vcx6{RRE_J){L2-(SqvB?ne2A6An($bf{9hQ^)2j8KIlE^1Zf zvQ`~~ptNMvhMa0GtBqOJkx^4Q)mc`XvZ_0yw&YY#S#8UzzKq(DQ~hPNGfVxCWOGCg zrgrmjl*{|9PLIDalvQO9iKu<HDkVU>)n&CF?*><fvudooud%7ElTO7vS{zp<o7=l+ zS1M~gB$%8I2&US)zCP8hX!T(dP+fez>`C<GCcb=-f|#XoHt9HBC#xUsFO2>{+zjvK zuNOv-VW}N|3CU6jr(;`3FW{u)Z?q=6LBotNQy3JAAabkPmIDEaWZ{fDos*^;yfMJ( zfi(x~V>RAAS`5<>L~AaqQ?lA=oNs!R?p{dTU_il`#v4*K7~%2z>|@S{!3BYEIG}H) z_pxnpX#C#z?d;e^VeztYJHy`@w=?040O^T8t{05-eVK5saD{M-a1YjMP6ciHrC<aw zQg;E26wYXiw_@L4)@EOW{q~G@)@QKaSk_kEo&|Mw5p^^VF`W&}*F>KltrL=JU^%w? z%G&%P`t)e)acuLg*uJ=|U3XVDtKG{fM{{8sGiF08Ye*?QAHB~$=KSRE|D)H310@=Q zQ@pWVr#!_^eBAl$=<l+}PPTdMzfN{^+_fKj0Y?-_-i+}#jq#cakAttl<K2AvFV3m; zWpy@<s(KcUsk#ayx_-ilhE6e}+J=*lo<E4e?8Ts_Fqr1R<k6+kpn1V%ALa>-)<^As zJhjCaXt;)F)BDM{$J2alXh-S%@f4-CE-W<2@5?O&s9@<yvvin!Mamu+{_;=Q%lcVT zH?{!ZFyRv65_zsXS8(v_@-`N-F^i2|!fN$553pKRdq97azu}{Q;yzC6Z(^;Qpc|xx z=O<_fPzw?{HC$HX*<yW|)SUVhG@fuhZHA-JuPgdP(>VPh1%VaGs>!k%%NCO<x-^-< zw^B*kOx5FC$x$t%8S^v+Eu$y~A+r0_q@sHJ)Ea0VAy4f%ts~@x*5T>X!q7hU38p|b zovTxd{u+j_eYEZ&L7wLVxj-V2==n%JWNx8UD3m@%8`0O%MTNo`?Y_YEs;F@G1lm<7 z6B|dFie`mXi)&WTk!DpN9@opsy47=}Th&KCR=bk0jD2*^NKaw!Rn)8<*XyrZg3!aP zBWl)*%=02T#&ty@BtHoKp$@D49Dxi+JJ#tozAjnHMJVYQMGK5M)#A~d7;9g-==9M+ zC+sLPnKY*bgA}T+PoUvsAa#550cf*+sDeG+sdP`!3k^+d=n$DPfw7($6FBsXCobH2 zl%02U>xEDJ;>?F$edpDO&Sbv{2MRQk@FosD&zkxl&zG*#jvm#nE9D>W*MI%|7F>mk znUk(EmLpgb1%W{>X`^~fr%;5k(W+UUxg1kH8C5<=T0J^pMJF6Ela21U%bLQaO&%6D zgK<3auK;7Dt%RX3F)~Ql5#33aHxvaxlcG>7)XBT$-NHQKbm2UK)a&JCbx}s`1@%^N z>dh~!^F7)U+zkubO3-P(KsMA2u>BHcpF5E2BUWhiYBd=cmfCW#yk>y{qb^eRN%8a? zI@{~jT2CW}_xYn@Fv={!P(BpIW-dEZ?48L%z4>&$7n?oZ88MY%`Bd7HPGK|A;1<np zmNr{L7Be<Yq!b4H=7v<Q`2o>YEiG@Keut^O%am$rsLQ0x9U0T7rgScss@?4KCe!Dc zCnPOzoBk<Nd#BmB!jx?@-7&3Wxl~gnK44}S-dwyH|HXCj=9Ias&Ge~h9j8mRIAt<D zAXe2%r?<`cl&P(YzFgm)GUr-MpPHIEU8->zKkurMPR~sJlqu6;PIcA{-F)-Vx|?r? z`d|?X$B)aZ$q&7MOasjecMHWhX;F=^_B*??Sm@K4VoSC+2X&#Y3>A}<3RfGBXENMw zg?V3lkXD^WkCwy`019a$&9s<o;t~qDgWBZLAdl2eXsI5p3tR13wY#iVWsBWibWyht z7j=6`&xBAUK!AfNw5W`(EaR3NAJk4mK_gc3;YI2uebTGowlm+fX4cj`jrr_um*c}X z9j=0O`?Tia+0E0SL_)?8pBd6dW?8$t&^&EgGrpH~xLn6BC+2IOKD}9dVR*Lq0xaVX z_Zyp}b`f^ZOab{fuw&YUB2+Qx>)?Cn=eC2St6RCAO;o}h)=XB2SH>r+jiH(R9}{<p zx0mz-^iNzT-afo_crVEjaftYx1mIhc6D~m!8iXQ@C4ea4df1WXa?#9)U}h^Mg3p*u zTqhl+2vb<W<zWBDcDWqKzV2{|L#(YvzS-f@ox^9Ndy<#>PBK;&Wcg|NX{>QR@W3{K zY;bp3^^^Hp4EgCcp#a7O7KV(e2E!07sKTguG(W~^?4lZ66!OsI#=Iw^QS(<pPT3`w z4>L<sLfEm%ZnAX+&F{vZMX2)7DIc9OGsTG=T57zFG1==8<yfP)V&3{lN(AIR%*$po z@18ySd-@Cdd%+Lbnh!qEpPUDg@s05(_UsYQ)t~%;P7muK=>ZUvY)|-*On%Um?5>WA zl?50LJ%&XEbBcfmH}zOz=!^;alP6P=Rtc7q@Q=l%gyhRfi2{4}=YdE4KV#1hzuEkL zQ`e!oCxJ!)KmnXWYrzo%_u;5NbadmMK<}VRv{vp06NK?w7^1Q$Tj<s@%@jyYfOJ?H z=<b?DhNKd0kW^I)<SR$TU~@6TDbXTel|2deXZ;P5pZXivI{fUj1U!)l1#@jK6)?`= zSJ?N@qURwY0`S$al6-tFn=r6ZKCntzRSe|;%4EGq3!oJ+1z;p;HHzZhUnP4(TsNp! z)JUHi@a}h-d_h`c1uf)Lyw5SKO{lG`s6Y&|5s@!NY-A)QF773E?w&V}ys_t8<KwLN z*{b*7*PmX#yR`c#8+QWdMNxnHeLAo6=?bQu$g{P=h7q2vuqZTxQ5GeY05&cR+zMaT zQ%}H``-v}M5%;OpiW=xsafFyN$a~@gcRt6=7J=(QCud2i4ih<{oQfxx9X-1H)Lf~b zN7Ikkh4_+~lVb`r2b(L>1RM!76<rcBIQ|Tc1dMMRR5_WsxK7ri_~La0J3#gJ<wEg% zP6Fr{`&R~8x6R=ym9nfYTiP)EXbt-}l3aQc6Q8|_W%kGf8U}!%%pIX2<~>dG8csvB z!8uB~T2M}Lf-thpE(M7RjA_gX6%1j2BB6X0eI$mNZ8{a1K44Q>^W@3P_G84KehO22 zJG-|8&J9&`rg~weKrl1JkCIVq&`ucl7;DHYw@0%Zyc$6}?KFTU+2;?{&=A`cEfAzN zU!jp_g3S-`18T6M@<#h3A_2$=zd4rj5XfwaD;BKizzZu%((a@Bm!J{db@_d4*S%kS z85)uJ6H=aVdJ9w~XjG@unH$c0h>vFo<4HQ6M~DkI2t|eFJmy!hTnt8Ojt6To$AMXy z%Ec-Z9jL;jXKDjiV*u!Qj44=K))MH9htwFwi|JpZJZ~{M?9ff()c#tpX0uYaf>A6l zaV{Qgbe)MnbW#laMf4`G#PjHlIUp%<3ly2&o*d>RpmOTnmY2VHufF-SoA1<)E?~R( z=WgS$I7Euy4Rm(-QH_=+`sBw1ta=csoM*|uG8xBOE~wUwTAd@51<n9CCEysqpaEcl zVi?P*5Hs;Ctuc)`LPe7hgD`Qd2a7<dNZEkzz~v2MixdVZ0XeLgwA?3QXr#xzd|2>j zuy`QZW4sK^2*CTH5tN8z;Mj{$CxYdT<=<HPhxgL8#&%^clDsB;2=W?3*{Z_GAZ)%7 zBX&@&Ef-C-G-xK0)U_U3>Hw1#U3GNO1s#SIAVG`KswTTkWM*}C5vDY4%wW!qp-T+P zjiH`H`Pj08wXN8~6_I0Gp}9bcbE~-^4mD3Jt=O_<MF|SbUMMQ!A9s^J&iReTf-o=% z*loyI*T|DV5H4Ul@+W|VSVDdMEF$)^yy9XVlG%c8PrviJtyf)AXl}ak_FZ>gbB3QV zH@0hfXH~q;wCr?t<n%fArY8HG(@8{ecQwZR0dRGfaGG$TP|Of@`g3ZktoHJ84uedC z6<dZ@u?EnlwXC*!v@Eu!mDOn;&4aB_S(^pc&bER^PDi*NG!nE_2D8)R@%bg<ZYS0{ zH>u*vs1?)CViBPBqx&5q{6GO8C#^wH0-chR_FWDrbUXgQ%zxOyH_!jd8*jbwmGetZ z>mI9<zllR*+sp?k>0oWQ{QRn`etwI7z}UM6U%>aS8Ge=hn7*WU)BCt>J`RFVl82<X zfGc3iD{+%ziZj>?Fd<+Sqyf4cQeRYe?3g$5AO038R??pu*~f{I-;y@--*Usl#4Re< zL0XHkkYPBDUr**?V_4F#Mn-@8g*jJTGHZ?Tt9?CpKKr#hdN1F8-^loVTRu<vAGFU6 z3}ia@TM<eef%}Pmo6tU}lVEWziqY|5wb|zhhK%K%K@9D)xqJpc!+V%il5F(;u#y6B zOTZNb%LoP>^_1Pm+j5TO#%nF7n|JOqvwP95V~0xY6*TP0JMx!rzqf3C;CtWMZ5^~0 zfB$CDI*O00kSYqexd!cwb5wk$FblTdB4HV028U~%vtf*Q%f;rdIV3Y`GsSf4V#7cw zCfk?Lv4)H$nsHSE3V9aY)Liqi7Y81?fbh=cWVC3e2(E;^A(2-yY~Y<$WZLA)Y7gE$ zT8E=mZQ+p1K(^Syah8q-KrYPTrn>-c$%9<8=VN<XSxYUXPmi`3lpM^e%gV*R8FNXN zosNq-!&sU8f$Ey>nP74)pTvUR)I5b;omxX3DD3l3;dW|5Dauo)5oQzd4%ke=n%?~M z83VJpFzJdbi5`Mmay@YZ(+%OsARvLo1SC=ifx8=s3|(X#g#d^XKyO?vL1Z#q?Zb;5 zA-fy+dO>$`EsG3s{LwJd8U9DwWodXXebC_2=_AG&D82jX5Lrq30g|WU3-n9;qCyE< z1?eqPcW{p*(2a2s325o|LSc9|Aw45lHu+UfTu(L|)=yFP*VE`$m9;=Po8=Y}R!}aM z;WRW529hmKs7+7^%Bl}03PuiYIM^lC*n;I+XCVHGG6`wTL(U9~xvx*FgS6)E49qQ% zC;{JnAPtIzXtlv-0G~aTPufS%E41M&N2w&e_2F_XBhp*Ps!L~{dD73yyf)TNi=pdT zNP@zwBc%)LA(R<Rajxrmf$|guvxDn;ijS;d8x#DYU>5GyG`y`07Vhif3$W;Z9geJw zgy{`K@NafEbUml^`&HpcBusC(FOTyw{RZ@<`_@2y18KsYLzqEybJdUOVAyuJKY9E# zy8nLMKS(N6XIC9}f=p~dGDqksgTh&9$ghkW;;y0tOrSfn>_uvl!!@Z%D(&MWjXlLx z7&NiNe`EN*;PWEA7v?n9Fnd|GPcWzL5Jg4N0^J9*27<y{WU`6V39%N?-Js{hmBO>q z7YoDQg7}`yo;_9#7Azd&p?6FG5Qp_rgBBy82SCT5LYo66_9A;R95{9;5N0pvbL5-- zkqE^(jjVfQ!-e3bgNHXsw1b5N%MmuCoqMP$v;wgoMTy5;j9QS;YtRL7CxS8nfe{!6 zYy=iEL9<ry-#({1-2f63<0)K?$K;L&d{F2mxckvEiv$-o0qao~<l24->Hy%fV~2X0 z#O3|xh#tG%Z}*6UDbZ(VN9;Z^B|7ZGd+js^n6tA>CGoYbTiF@3mVJ2J=j|?+o!-zl z880I~AS@(>cJRd&JQ@M$a&ty)hnfb@Dh49Udl4-cqa2@%X3*EDM@yqOtz|8Tu0$~m zYE7Tknnsu6jma2wNo#M$UbG=W7NHtfw2m$aG@p0Bqoy_kFC!^NMs$OLQFh2!z+Ix7 zM>z-tp#eb?{XvR;XdvZpTC?;Pp)|W?cP_uOrPRD)YKOzQ8=6vKS83O-lDU7Vzki5< zI&>8&P1d?OJ+0UY_@_0)6vj2XSd1>}KL?^m6nZ%CJqw$-0WX955Z4na7eyyYccvyX z2oy84(4K}4Hj~9e7zP9&q!4U^wJrfm(Z$@1`9i)Pc3E?Oqwg$s=L%125BqXMlQ&{E z>$jY(Us+x6Y;n8Ureeo6gTdamKflqw7Liabz7AKF^yV>dXPvVae))f8uY5-TK6nmu zLi#@DYYY})m#|SN#)#+QW#bcJM;M=$vf9P1p(+nJjE@pf*Lay0t2mY|j1H`cWbB{< zX62)l?7%1mF)+<>Y}EIuEedwkE&~6dBlb|JM0baj?lBR1Nh1-F@yQZtvKvTG?J+hI z&{0KOurbPhb=|i^@dk$zgzj$L^7yjSm)G5T(>afPdhw-uA6jS0HA&OzL*Xj7Wgb&M zlRrD(WVJ}n+-Y0puDW+gX~U{BZY$ilWW@%sA>;t&rE~??y<?S;KtJK8g&1&=*PBEX z7fwb~^S)jhf;7N+m*i%WIT#9*mRxOp#@;l~Y%{U1iSeloH73)o_Re{ImRT9;^eK%# zCc&d&O{9}f=dpk7o^I{~F7#Xl7qVdv+$<F9h|<waQ8Wc<!Eu7?ouu1G0l=$va72m= zY6IOSs}r*YIshU%fHf4Wxg)0<CSEaIO<xPw;cGx3Xl(-ejX9&)AzJ|olK6^Z(WiJ1 zr=rRjf;85id?=yhEWo_t*uiMDG9?6d%PTNRrNE*^i*C9JucN!g7j|bofsS}Xsi1Ez zlp5k0zXE0Qi6@R7dO|v%mf3JRU=xphJzFSbr4^zrkPd^+q7Xm+4f!6(Kk6@#UMuxi zEOQfee0S|=x7+A0g3A8kPKKe|>=UgvhIy`es<9(OlyR{j0uR*$h-@{gKz7%1**%k? zlOYRapLB|@$Dc5IS1`Kn&y01wBjCvqRq&F2I@<N&E!1^!`$*ThyrZ>d%%3V$1Q2;S z`7-d2?uP^NVzR_O+)wXPjNWMt!S-8xyPDp`A$lL)3)O{|74C5<edN~P(^i;5SQog5 zmbV?4%Y^;O=O?yxtlgzkx?4w^$c~I|>YGP5#~nRMds7vZ5&8wZ(r^v{u0f2-j0|9Z zip8kJTaaIQyx-V2iuPB)t&iCs->brSvZGsL<3W8K8wA7Ug?@;aj&AC2jc$%R`qBL| zdSvwO<NEb+{_)A@$M@^++0KqOpACG>Cdpe&d%pIK&4rQpkrkD3LrejN4lxDjC1MIN zbgOuL!KFODppd1J+?pdF&NUDdw~~%f^u#*JCbB^gHccU`=Qh4}PL3Uz9NF=4`(x0F z!4s2d^>O=SPR@_sBD`gcXa1h;e}L-8c74pSj2ky(lN<+{$Yqronrf}kB1{D$72{Sr zg21pec7W=O5Y$8JI+^Eu1%a_gQk46_CW(W;L$pl@_}KW$<ByYhLo<h_Jc%#3fZJ$W zKft%SRM5F=xKNP_Fbhcz>rQ}4Z&r>0#QMlBVns7F0E8Zllg+cxU*K5-Sf8k)>cByD zR+)FVvn&69**9`M`(WL{B4+<s|D;$U{shqVkL=J`cRzfSKs7OS)1ty6jxUyE6}S$e zI_*4i5mSt;KS2F36kvV9t)|&%G(AucWFXcY{O#<T9EJwVr7bGH7j0{c4tt|*((N$U zed2b$zXk6M7Aghqj@U0W&qIikgZ;uI<bX(zxN;dmoVfcK_KctuKp_?P4@FdjYtSME zE+0kn0b_>Zf|eCMz5v#4M2e_>(&f1matzv>$xLYm+}2ys<ZHe1kgul3_u*b|ZQ*}d z%R-iX=UDZnOE)iFy17j{;;pUq9&_UT-EVyIVb-r70$T7BI=2*b`y67A>k)hGhn7C0 z(gTPkq8vJcwj0s41jbqohgBWoUbHHi+8U;|T7+t@X8;ywxom{_xz^qxr&GjB+{7?{ z?)snKaO2OeU$Eex`ugk*=bwFb>&zD)xMb4<4;<Vr{%Py4ZoB!_|GxjK{~jE)HEg<K z&!SK7=4T!toodX#77!Lx+6Nc{Ha%e!0Apd=8{RcS*f7k1Wi_8tX(G8OOyt?q{P3df zBQF}aj=Yn6XgQ@}qU&tQhpIZ+V`hW1LRy11eFC{;zcsmqAoM%|-InqZ1dk(hzC+9- zmN(xarc(%NaIsI!zU=C&BY_3W)-IWuTzc~tmR<GzTW@xqd8Wq_?6A8<o9(PT+kMVA zzx>6Q*3Y|V%e7a3;!|_hJy@6~o6q^?%_}agJ<l9m*tB3rckc4tn8yacy(C|Ryt25E z64naETGB9q$iOQ=1D56kW_Xu~8o{#GMAU$HX`eY9A=6O}Dq6IG2x28yaUg8CJY;2G ztRa!)wBhqXhO-8?`>3LmN6ZCOp;R)DbTxD_!`^<3T^{|m{t6j{><Ccww;$6FJoYx* z|7G^@Rr)6Ow=1s<oJBzUV{e<S--eOsq$_VK9e(WXw=c=Ehp)sn|9j<?tLsTd8NRyv zA*1TyL7rdf8Kw<<H)-If97~ZsaM3f0i~w5#uIeQD+~5HV2EvVCLCsc+xs>eFWHUZf zm^jAN4w)_Frm6I$XQV5vUy8DTjRhK9CUnLm-m&`L$(?y3a^Z#NM#AhO{Xt9h{8?*e z^%*@{9vd3z(Stqc5R0b}Wx?3b;V$q0wde}vW?eScuf6D37=90||J(*bzj%*0#>V?H z=Jx0K8Tas8B2mIGC}KU1@v@<#`+~6f>6ol&u{eSF72$P?(XxpM!b9KMW(*efuT1XT z8dfLf@77nq#YUqP(nh*8r}Q=I(+>R)bpG_uk`0L$)=UkOZjMm&65nC&!Fq&!W5aTZ zcq>1=B5*_zBuv5hn#YexXy!64NHIZGAxJb)(FDv#0PQS*H3Cr^_^>gcu0V`%0IMLy zE3x$VIT~8}zWy5U&60Q~YkJu@^0NMG{lLqJ@4%HW6O9e~_IA+N2Pzw0K?h<+AR-Lf zqCJHCVQm}rU?7eIF)rlQz#<Igfm~U9BWoBJ`Xcrp0AJtI7h*N$_rM$18A#F>;T}S| zkDDU0&~e-a63FN^N1Ke`+yL%j{4?%Uxe?v!#GC0gl^a%%-joS<jp`}>N<Ih0!dNnd zcHu@o<Ja#JyXiLpPNl|vWrQx=e}&lv>hi=Hx(eq+U;+S&`Fa@@1PE$UPz<mLQ)P01 z8;CR#3OYV`mwU=i)aokthSQM$KK(jbPxR~Dn!>M*eQ7r>_r@;&9^T|8jHMYXl7SkT z#`hU~qhNt%N5t;oAIpoW!<3=I-ZFS}+!*19z=J><MwnC1lF$HWf^_sV6mCvI)esDv z6ME>_5q4xuktJ1&?ts^Gq?H}xCMWxbjzPlxD9Qk_L>0cH`(Z+GzVq^oEQf(Ocfzf3 zl6xVHWb97-J`?UiV^o0OOO>0rPUEfUG^EgwDnsl%$$mrV$^<h_UOfEzQA0CE>zP~Z z#$5T9V3GbNe~riJGKAiyza=jJi~b1P@E39Iu=*Fa0bA5J&+%W#E97g)nn~JNo`oy{ z9Aq2xNB$~K53phNMSkh<OF_nlHFO^Bm5^)wjQos1c<vyNd_blPQr2i~!aTuBJt6Xe zgak!C?4!sBNHswVP?#(Qi13AIe8iFuk+58;gnLHX!+emlKEx}%i+H7X?=JB_9_}!D zaL*ogIzK$2U2f<QV{u8;E;!Cd+eNWKK#(amsA@vHoOZ}Bi-09Y#;U0?cs4pG1XPj3 z{Dfvv;>AfCbt0{@yiFB-)gTmsV4PVs3&S0q9$K<xYDN__!$~)XBNXmXL`+&jlN+(} z)g3!t-MJI*2X>s$mZp(2I6rax6k$S}jQBXCO;9W<Z9=%rNSnArdBS*svn=V!t=Yu< z?4f7hx!{DB+^)aP9{Tz_7Z7d0MWcK)1>V$4Id%HV>U6FP06B+x-ED9c3}wu<NLh^- zuq<fSkM>1qy@_{Yz3EU8f7CQ}8fUNcbR4E(RO5=;LRnx%r@Mm`?QTUg1HYU^S40y) zeeE|*g<eZRrxuqS%Js`Vzz!)>(uehGat~j*M|NAxqDi#LF4-sfg4U49oeo#ClF8fN zP@m|U-Bp)8eNO5wta21vH;!M$8qw^uTTBw-i#<W7hsmMnjFe<=&JJaBi<_#=)jjL= z4vIM&qYrs<r;TtlW*Qb`WXd9lCs?LfBVzChw5xeZZRb23B<=Xb?&jgeL;@h(n<wiS za@`Ea<B1Kw8wL?V1$O~jAB(xFhIjd5p$JD0_rpbbLX?mxx@zJC{xU>gC)&9mpp#UG zqN%=_@C`&|TOw(~H@Yy6KBy4;8WJ5DK73y6A*M_dC@d%3r!u7&X=>)ShtiWn`~@5t z5ix`gxR?cATtL`4sN*==n}>fEyEuqbxxn|McYeCmyJeI2M?b20eqHG^cSY7$U$Llk zfA=e;nvDxfi!QJJIefP_-CtWO`ImokPU(WZ@t0nzd*G%8msS7dC!Jp^Exe@q$3F^P zI=^J_>-bpD=vd5GC2r0Lr8h!5AzEl&li^1(Q#|I&Po9548x4-*aRC!KaWu+rT-3v< zLcbQ=dFN##|2d0|#&wPl-~6|cOK>fpbL0C^b3z}+ho@HhK#{0peK6wI#`<75H^)na zu|7atu~W5v(~h-2-l;!+%7*KS9c#-w^(Rhfb6us)V0^GYF}{%;YOFXEuL!#H<j|2= zJ2!<XB6cl^aiBHFRfqkFbVr~YqYy725AW(upU~=laZ2Hur#>ie*!<K7(<V2X?Z3Jp z=KDVwet+5rPi?OFVg%uQj#HR{JW<RYxnnCDohF*V*aF%BeF2eK3MCICe=osaA}_!G zOGC#Q_k972*SPPGVpWub4lT*}K56$r?x*PkteyCk2|tF8wGjRwGwHHO)&U9x$1q~B z5LOM<Qj@72tP)mD4f!#95w6>VMmqEGUdkz?-?<3F`puEwF^~KXmeY~n!P2F|69iS2 zekIN>VohjEi$2q68Bc%4?+C)ba@`v6Ne_%^YPw4@&%OIU9;W`EtA2G`>GoHjxzNho zMlZz1*`F9MYs`pmQ4DR7sjiIXuIP9nhJQZ1lz8YimfESme%sqSS?V@@Gb+MV4oEgS zf?de21|cEuly`zIXbBA6xB^>O;lI+r(sYsj8ryptOYhWQyG_Lree*W`HL-_&EWJa2 zZ5t%B5mWgfbT-O8UB<PxSQ*Yvf_VX~R3a-tBv?uwBOno|1w~ENz`}dZ<gAk8Wa9y{ zNI*{8Xt@d_X3JQf#^V;u7h$BflfMq8jG4stNMxlEV9C}@l@tD6e?p!rSNne&sP2UH z{#_-)()bYP>c8-Z!+zF*_u-cy!@&^T?ofd-v<RI-H&&Q#p_nE~-jyTgD0y$O7<ci? z3_z(-nPCRn-`$1C28YwvGnJYTF3trIErZ|~v<r^r45KW2q*z<9Nwdlggv5{42Att* zpd=7LS_;cYC<=TRttVG7No;V;NXNqe8T9%B@5RIE8TN!IUV-!Q%t;MC@2d#K*YEkE z$rbY=t=X^;3(VoOKArAVc2xzdox8jpDb4D)GhQ{|$okIAztEPxS-SltXY*S4DFxy9 zpAo}NxkFiuAGbP~nuE4MA+TCE=cYgpU>&S6{ieKMbjhfdVCfC!dz0YTeul6S!&fa^ zer>Z#fhirCi#LAZ?zb*#TX@lxpS<qIvsSv#_oip%*_62(Hl5iVl&uy&VvW8yV}^du zy5K$E>zRJ*dE2H<U!7}@^hLg-|M+JQt<KrZK6n0>s+EI#Q!~%Kbye1HGlgq%SI1&6 zVfr$}6FBAB@_zs;Ng#@C0oP*Zl+`&NZ90ZxAzstxfPJR+LP>*A^CLw+6f_zeVL<4h z%S4b|m+zPJy<$2T3Z~)n74y(=B9cqCm}#3`VY1Dg8y%cFrO6$0`IoIxOwpj-=9VO@ ztELg9A2!VzaHk&oYA}$V=k_jJY06c#T)42qEjnc@V-8QPH#Ie6adppR-x`cexurc| zPxjA<48EIQzPAux(B|{U+##!j$!353j9Hh@dYY}gtZnrpCX}G~)NA)!qZeHE#7gJ1 zy6(EBP>n~ncPv>G>$n^u=lJ)9o8))p98j>Ch+Uf{P=pN<ji(ynr1O!Od{E7owFMwT z9xC5}-Bwd;ZEou6=W$+uQl={2=LMy)qo;px9vAu;L~}M`LSmB3+|Xf4=Od;pC<73a z^uC5vPj}vo8X0*COqfw?uAjT?>Mft$_1P^~FPmF$uAO|~A<L}xGgsYk>$NM^was_1 ze0XYKq)Yu@wc~<2x-Pyrx!C6yhnnn7YgetGm&wdqziKUZChyzV&p2mFYg6v5X&1TJ zg5;d3H4E2K%KPdCYp>oq>*DJ5jg2%-K??!2P=Q5KM8j#qmxZF6W-3{tgBgkjReNi{ zJ>x(B^EX1E)vmfbT&nZCCe6kE=2EM^i}>z+4!6_Sy3fPkYxsLDe{baPNqR5hER~W; zm|>tHUK%md$oN9qW1s5i6P|ZCt2{NejmeJ69~-dakjp*cU`K~KP|LuJL~9D4&ang$ zIPWF0RtP*3G6JC=xB?kq`G`mZB99V${*39#&*?9JF1h0It1eF4ANs}f$xZigqGm#o zscsi*N(I|94V}IW+t8Yxbz4VOZLKAF#>UT%kz3jM;qrR|8!x<min~dFvv-I0iOUU& zX4clPsH+`*;$C+uo0?fYAl}k>U++Bw{-!2p_onm6Fp-Xb3Bu9Kb9%gx6GDo^8fi4y zLY6et=YUcNDC>&4q{)@63k=`vpW+|B`M=nA*mv|N$l)`4_Pm%JYcRz=JXjEaIoyt5 zH)PR3dnS=f@mc|_gDS>xzCgjF6dc`>QIlNGLa}jVi$NYG8LUPWL^4QG5R{{;wSv=w z2n*1{5wgi_5o`vNWY3V#H&5sT;T$Z&D5p4`RCsQ2h9xX!s<V(+Oy*P}h#;DwtwU^+ zJ6Nsg4;E^D=e%)_ueP8+s8lm^v%ky5=CGChLqq-gGx|Tdy8O-lD(BzyznvKz@GG{Z zOKpmOAb2LT{LM+LG5&adj%`vEhCEi2(U?=@9jwKgKY|azh&EzjC<+LMK9DF1qa2A$ z|3|k0Ga*vo!~OE&Z~(PwoCV-jh%fwzKkj=H-y69Qh|fZd8vl>==I`1f`xP(Kb*SxQ zN2Wpz<|LIBLexGyi#{H7W98)~s4&ZjaYmXOG*K+|4rQOE%FFX8Jh0MWV|R8T6d%|q zp`_q4nEHr*4jKDcAcy`+VHuAM@714T(hWPF)1ML_-*LkubnveLPKRD51ob6S*>2dm zfB62LHyQ_s-)M{|X2T0z)TpikG{i~H>2WC2ME4j&uuN(sT5R}f{bz_*V!J3H%!r>S zZk|Ro088`nPlB7<h4lg=+#r?UzP9mH4I5>G1+o<KgJK(i_*+4Z4vwX!s3-;%;*dO= z7vc*+R|qw2%W4^LxkL^;NFJ}EMWP^Ah=Sut!9;iqVmL!k)ceipZc1M8yG#(}BjuQ2 zqnee~>7L}Y=BVO;jg9^4^pcHV{O%VwE=gCLp_f8W7KchluZ*2l<8b)v6HRR$)r$3K zsb$5@mt46#ms@`2B{#2NYlyP+BJ#20zZ1SGUnIRjT9bq{_B@OHo~>saemDHj?4jQi zT=si$7SVdH@VfkCnQK>Y6hN<>E6x@Nf2Tj9?~%g8-w|j1o<KPIP4W0tp<vnq?9_^R z)FhB@P9p*k#==!=LSSS>I+2QQY`DNA63>7PL4(4JfOX|%*2>y`#BTc)D*1fwSL`O* zZ!IBiv`+scFGU0d9kr?c2sZ%Kd9)F*zKnD`XhCy@Vgrp=O-^kC?LEju;L*Y4d;v}c zHX+#r6{+!{3ez4Ti%0;Y>;ouETBsgvYv-eqLUE}$6ePk~31yXBVk_e-Djy-NtTUh! zVtJ*@;9g35O>X4W-kLJiDd!L}-1~}Xjd-KsmN25OTEba^VZ~7A@SU-Clk`-z*Y~Ir z!0}@<<*Fc`y;<Wu;tzyNEkRCCdgFX9K`S2@0Vk6-jx<@`m(h$wqyQ+0#xp`^0&z&> z50@i3geSZnq2yKRb|azH_-)K0#Q#!`hzDb3Al8`Z$a;jukBC&Flae7u9v4f1>_Qk8 zWA})I8!63k+?|e9Q*PPF)FPmPu@3OqHjIxAnh(#7<&~XaO2D*54JQMZlabJf34ts| z&ICDp?d6wQ3u}4#W&I#=IPor|g~7l0*$nK_ZTQW4o?S%ts6E3=LTRJnWZYd7Ckce$ z_R*ifPw^ksfA!K!L}DTcU%%XtdX!%Pf31_as22Df4|YL{5-1Mt@#8LV?bVH7cSwsM z*%0N$)S`&^<r!Kw0($uLo*c?l2i28An?gQv8bKH)Mr6{l>gH+Dr%jE1agQ%)dRo7S zi|v9jWROy9wfOsBx;-@9$iwK-WC`&gMy##_vMLX&hgVgDR|hrM%pR=;ZOihsX{`m0 zMa_w@I#Of6v<R*1kV8GwrGC>i)c#5)d_lx?HjrN_Ez+txl8@Ao+L*1WkzEb7!B<cV zPc~WPlK7S3vytL%ce+i|N`F|+OK*h(#Pd`zAX}ZSsyZrK0>Sv|qtK`AvPCk9?C7zt zm-Kg>4ptvvr|Z9yR&ck(*YPc~hZlnW7l1!nQSGRwl0}4M3q-U=b0kx%v&Ci}Q{9}T zytwX+QF^F3hhDWIf*4|yTq1eoGv(pIrb%lt2Vgk(LZbjEW-A$TrU)6H=7xoJe(xt{ zx^GzNHGBQ%`0>8-2KUS@iodSbYmF2xd1Tp5f1NtjTg#qsPMJH!(RnF5ClG#y&0BJ_ zKjy0q_!^n-mL>YPo<Yx>ERrJ}@HYGXmgax&nlYmbhyp{dN<e;Cewg$vUTTW6et>o3 zAK-5MLkdvfPfHKAKlD)hp{0M`zyHr8+ke`}zJo)5+P9CNez@)M(m(Cr|EHyg+mNnI zYc!2H<wZ2W<6Mg|hiGd$NIrA;m9=0KSkF)6Oj!%eKaG)x43;)H5nim(;w>mifJCX8 zEEhm2LMf3Z=Vf8WR`=14<a^;6Y5kk^Gt$|*PS^T-{e|5q7Q|jWdhjl+%EKQlD)h0T zXltSE^evX%ZKpTYzx;#Rq<%NM_SFN=9==Jxo9l$s&Jo!~?L^K7{N+3{7HF@KqhbJ9 zHG#~tEET(;niqzD9K((EQwHxMNhjgasJw}hu}ifA6r-0ZAPhxoQyW3xM!s&dS8c_r z(m^7;1q@LGIRdxoG)CMILP|1EjO8E1<*3k*k75d@<2_Qsl7Oo8aearzOQ6n8Y!?Wi z@10D51Fxd<>{{x)g!Qk0xTV#6j7}4-7bu#hkr#i1wTB38ASx_d?BdDvT|Cv($dQ}e z_jca*Vml8TZl4b6LP>J%==^@CQs<|PAwjEaM3)nNYO|tN_i27$8O6}_(>S`E2Z}+y z<C!dp8I5cKO38xsF;+B2aS{1Y9J2;AqG;|!yhWt=mmXNYX_K{7s7HeEB`$~Jyv*fT z%{o?Zx@^^^ZI(K>{*>i$*Z|2-n(N#@@_4--J<lAnO|r<cXtIBHjs6U=%HBm{m6EjE z-ZVQmyZm0)^^12c)t?EbAFW%*RtB0P0e_e=Q8GzRtE=kymG2PkAk#L2zt<qDhkPiY z9sEk59S|t2*Hb9JLY<l|PT}HUN*{>>_)@TxP%Z*5f)H(khK7Zm7zc#*d#G@PI^A%v zq#&91Tb%WBGpAjcXqTd>W5Ac1GzGL{Y2vERE)hb|WRL>13z<;nu2Nkh4JQi1-yy@} zc_nF~L^q4e)B<u+4B5s@iBJyLWmO)Bi(Ll1<Y}w^l&8+TZPP0I8}2&uCs}fn{<XFD z+D*&^g4tvT(;KBfmBd-Q7PIR;o<P-=PV<{`RazN-zv|0P0k*Qx?AM=J$Nu}>mEUx@ z9X1dQS|A+fpfF7{2^sIuSxqijEWL;coF^3XG}oqJPEE_G0bmML&#c%SAiJx1D#(+= z0T1b=RL_ramu7OZc!9ZSE+kzdt_uRB4#}Y-{_k`W>_M?8=@j5EGh|s1h|+Y*4(O#x z6%3gaOPq4ZHt?p4RaK8R1@vc@?pl1kJL%dSJagsq!5X9G*(`Nxoo=%NP5r5Uzu6ak z+``rnX)alH`KHzSFIG8O)#X9Qn)|#}qcmbAg3^9Sgw$V0e0!<l!w?0#^e!q~hk^A? zp$a-ZMh%!gUilRHdadPRD^I~`or0bt%^1n2l&1oOY$|%*O1?=aRC3LYOck|?dhRnv zVRFud$Ourb$qbg{c@UT%1pZ0Bct}CHND?Wj9%VXKm2}F@NRvnT#m!YI_w{VauBB|H zzxmOs;SVqa>|c0?{m(l6X+P?1NfvW;@SFFc>kFd6%d41Ub*|j8>e9<sT|$$It+6~_ z?{e$gFzWj2+syUu9|pbNAS*d69;;O4y-&Q7cU&aB9rNTV)B_1%%nf}7$Sm}?N_-jg z0FROEt9jr$(0C>|YV-*{2u+h0(4w($QcifKyoLxB9QCXMrgQiF=7vW{eSGiiVM!6{ z6T45pTwHy_Z}yzKM}LPL*zi^RnEjO(S&Fs1RPmubg*JJx>P@LwW|)EqxS=*-A|uoW zH7qEULGuHVq1sbH1r=-+66DBICqIV5v(%}oBvt$n3C@Ox4=uWW{GCheK57z>ecmA6 zV532g>94=|3h8wdY1Ch#k%E>OsnACB9a(CX=sSgsStne=WTlzlu2yZR7X&g9OYl~W z&<WLm@sFKIC#<80@Hv4<h%h5NZE~BIRN6Ea6o^4H;ugm>D=?v1aH#WUfn*>e1{UcW zIL39L@k5E=2dYPLk|vT@1qSxyfqaY#{Epa%@+g0K5Y6*>;R~oBZ&=!Z(U)b^&t#bT z5Vv{_5jzAbVq_o2gz}T6i-8?d23#(a4?cnE3s+xv`yF?G4kA~z1J$f*NOev-<H9Wu zet`?&Wi3E8gPpz8=gwcfmah4XGGMa{{-I0n*s+toG(!DRp75E27Jtx!m`zyD5iuVm zj1yT&B$Pyea+Cx_6@krA2FaV+3#1F%`CcG%z>}lMFTj~RP~}vfT;+LWIQ6D!#^cJg zIgN6r<`iMgxQ~k_e?FMSn?D%nkn%ZB((CywpfHYi_WaFSXKrB5V70Y+Rj|J=Z0(R* z+Re;#(I+Ae3CYz_<(jM5X2d!?S&s}rN*1j(wIQF+VfL7t>dek2m&+&1N!et#R0qu- zYt$RE*_#tHoeo>H*XgiiR=9m$cWZ6G)jh)<=$9nqEOjwSs+H`D!)s}<wbeI1%1)RE zY+d}?dfVI@hfj7!teJ@HUFe?&aNh2et`0Z$M^U=Y;&Cw1;YftUj96urf+=sfCR`u! zm>IL!eMxu(76d}Ac2|qP#^&`&Hb*EOh*{F6D#;`_CW1~$a(c~n25MQ-Zb!({aOIWG zMvL94$knTvXqKJl()t8TQxM^&xC4<<!gL@FAboGh6v{(MN734b3?h7n;!D?mb*Daj z?}t@iy>Z*{)9zOH75B7y#I+k=={;-X_P1_+_N=*?;io+w;OJ1Vh4qkqPjg=tRY)al z4mBoFSE9SD=DBqYCu(Pz41G)|=$BJaX#jvE=05yCJqNX}KAw}nYg!h2xb@aU)*IEj zB%csw{AAPZ<1z|>qsA$mhP+whjk;59!wN<88~6Mmck>5hhTgYMwh3GlKp^s{NrvE! zV^k8)*fR39DlS!Ipd$I%u&V`4pgL2OMn;PhiVq+a7J0A77D~74kCx=cKoqGW5EX#I z-<WMdc6w4+&k-D80{G2vjx>ep22d?&WPkzyb01V2c-29718EjeO;7-w7xG4#60)2r z`z=AIs;LU0n5A`B&|Fw?)hHTeKq;h!8dx0+Q!?Gcq@o5WH$9+$ma;mnnT%tCGNv^n zkCPA$5RU(G!<g+t0WZ3sKq;NjOOJ3HM5a!0TZ#OlerQJ{k$GPD80s_RRmV7YDbQvt zAwZL`%?P2)E6B73SgE8fx0QC5$m?o+h_6-lO5{?7qmLh#V*KOSgT_hmP2(E|p9=C` zd9UEW8Xbj=J}4{}eo?8|j_79~<qLBtTcgfFakPxu$LkVwXNygoW=*GoW>^^rLR&H} z*b8yumBjTpQrJ;xBW0NS{bjY^!~G`n%lq>4XIbI(<km)>*TJhqKP-iWPElO}yNj3A z(E1^Lwf5=IfATOLp0l}qa>j@{icp}nMQ|!4lWUZHE$!3$X|u@)!ch~7mO(*+&aP@U zR-tRG%1@AE_lUl3=;e3<ZG~Wqh#WN|BLr%+#c)$4jf4Q$=%*;@^}%J)j#w-dT!L3D z77VRuj^4m*#*WJkJ7<25MPeOMoQkpH#M)n@<%8}t&i|n;9_xsGJJw~onYmm++Ogk@ znpL^nieQXx1GZtue=SUtzYRNk8MG^kcL3B2D-P167o&zDS)QT#4T6@Yn1h*pYE0Sh zaM#wMHZqmL(y}>jM3}MM<g&CX!J9$;)-*YgEe!ltsb6oQvfVgbxr7Szz|To)W|Yx4 zupr?pkg%+-wllG1?#wCif#!6R!nP->-F0X9Z5^j2^cyX6*!6y2s4nI9G!Fl!dqMsT zo5|hTn5y=(v$|(&>a7W#yTxib^VqOuj%b=SMe$s)Y|hF}XEe>z1$OYCm-Y?Rd%9X$ z+vr!%%dAzzctXF%GK+m8=m|BZ=@$oQCi({&8w2!v`5sw$=)8?*{_VJ6na+;S+JE-i zPc_E#)%Y>`6CsOx<?qWwm~lPG%^)e<&T$+IuyT+ON{&%Yj1Vel4OA?n1%~@R$>KKR zaZnY^tD5-2PsSIAqbN@SWP!6cjaArB%XlyZ(-xJQV7bCS&q=%drQ7d0@4|a-doi(g z*1VV2E1uS?<_^xAwKnnOjQ)Y(*&9||=^U8VzrJtb)Gb%#=1)Ig@_h28+irX5lO1PV zI&bd3d@>Z8dfVL7=FYqHjE=fBr}YQVxZ<oUoc(i$>gR1(`PA2!pKtW9@A&)jwemls zPF4=+jvo!d7&Bh<9-)k=fRAyunE43^6@;KdJpq_Zl~8Cb5r#RqWA>S653;(!!5vn| z#Rv2o|L0t9M>s!tU~q@UdGP^u2lg|Oa3VjrWAN;A2lPJ<vJK}B>>Q-8e0y+*%}U?- z-*dg~Q}TmMJ{#Y%^KY$Jx^m&fC9OCzIH><|fZ8kZJZh>PNEKAV6bH{etq?r0su6Yv zM27McAdWCH*!LP$Uw8!#E^0Eo{7W5z6N_dOoIRuv16SbX+(xWo)LDpoE1CJF=@&fw z<QEE44c7{a6AbVD!HhLCW~?bl-wI?qB9V@4;MhD!?7xaH9D9vU%s@LyPcY<l^;lF) zO-4hZF%r{&_Tm`h?tE`Hgp&6bQXCj$G|T+-7f@*(3AfwT;$n6Dqf!6UfuFIhKRdue zjX3Id>u<X0BccD7e&82B6(p7xys*6wBbR;#Jn;_*l#vRL4x9x2*<!m)t5!Q92~ZmV zLZYmUcN!h@qMj2|XY&F%SnIMtau8SI(b`yRQT9%yP(T=*{%Akn@@NBKafpt3%DJyA zYjeQrS&A+a`_wiCdERh@v}3oqPo1WG1EE~$sodAEdMRR%&~WIu3gS;X5WNW%lp+P? zPy#|h2~j4#nc@X0>D}j#NZ>M5a`F+9gY=0{o7OHg`^1jHrJ4B9wq=FXoE6hsrAMs2 z3kMpeFV8m>A1Zu)byLk=kJ93=x5zUV{Q1eD6---lzMCy$W*3U04&~3fbCzZ4GTGNQ z^Wwqzi>map%i?RBzOnz)Pdb(?Rn|6b5+mWZ>VVk-K*DRCHr(pHV_+U0fq=0r2p347 zLrnE7VTVAN7wiV8C=u>WM2UGHe;|mDKM=&{s?Zc}qCQ@OzA;;@=G70YBXAg7IR0g! zdKyTZN01chB1Fk*IFt5?QwC>|&~+=%Iij(at{m;SylNY0+kz!cYbWDUP_#BIa-<36 zh+d#2mnz7or{WTTiy=`c1T%<j3qbl_n$sbwi$<0JqzeLQAdU-<SNrWYDbv2;@!Nj* z;Oym%$yNU5cqsDMm#l$6^VGz7f%s?Qi>GIsm!(@mzsRQ7gsSuAfF0rDwoYdw%5-$) zYp1O_r)j8oZTF)3aG<TPeq~FpklhxZ)(gC-A@bRpkTfXEwNA&qvddiMQ0)18=0T<+ z+DHC6<}m3ph<+pg1jUT0PAVosM9~~D230FJRt?+FCXxjxavuup<;o}b0#ea4!=rL+ zt8_bg_wf6?zNi_`VF&_!YY-l<)PymkA|@3g2Bd^SrWiQXix*@tdKG3t1(_>`xpy=i z!Wf~#8(bv7Y(<EB#E<c~I(pCmh3Hj<@I}ac{>T?paY2HMR!0TqfmJwave|uJPXL+= zGUae1Z<#7>01QUQ%zdg=!I}W0my}vO3!_Q_PK5zAY;i<u1yH#Ndah9j3B~PrQKURn zNb%(o`H*&@_7Lpw^9$z_*j-@wk1WY!TY1q}ItzUmk_1{gd@rR5G;u+9B%16o@>w*C zohlD;OcH$sS%AAhasq&<LvcGUQW5tsnE)1a#vMRs!M_SsmvVWy|0_%c08xA(&c0f^ z0|cPbM5snJkpLEh01W^!_o2cKWgBSq2)+aGi#$wtoW`h8={;3?nn0Ct)F2w5qZN{z zKSm9M0w@)OLk3ljZ3WsUa~`Bxc*G-KaLJ~T`lVzN5UK(~aHc3$xky-6DKxQB99SVN zYM;-epl87R;TT3q6?_G8gjA8q!Fx{+>EIP`_6wq9=2aqGh&9$sNZCZkDtHF(7`g?{ zCQGZr-NefnGh<AtM>MX`&@q&#^MjIqcu)iZhNtcW+Jx4_SB*$+FR!odrScx=lnZMk z`rsh!YM+mf4h2Q?CoZ86U}EZn!daO2!G|h7<NAO&-HClb;Tp8wV9@mVJ`lm%3Vb9+ z`al*MU>W@5TuDnLpQ{zS#t!_CMq&lG)zATyMnU8-xDl+#rz&r|`(V-H@X?Y4CZ)2I zys9li;xI@-NMHVd6wQH&wGX5>vRFn4jv2+>r~ES)7!fB(IHHyr<-52QTOm4mlEz;D z-`eXyd)>Uf5HJuvcD_#7z0_WN@MGGGif7~6JlbAr6R1ipKEk&Q9vN#YHJj)QNeD(+ z4Bt4#!nTa%?gCRFV+>{h$5x4Z$ruBAh`4yDC=(-2;9D7q531ykQ9|RR@4fpKN;f6X zJd#h1%tgZ89(&t3@%CwS)Hr9@<YR4V5P)JL#Fxv*N^2lsC%1-VW(Z<Iqf|>lt49X0 z7DMjr$G6be&fa^J+Cn+8UwL;zBTH<FzK>e^m3NJd+3_vaokx!n*$ltm2<`si_VNT@ zqrGVQ$G10BN9nwyEt=5Y0_w2x*1q>B5qx}W3+Tv_|J%0y!?cY{)Yg%4p4e7)gg4e8 zJa}a07!!bBml!;WTGf<aSPQ?{=yJ?qAIco?f-|vVKpj9d3xZl8N-5OF)HhNILRA!1 z;xy#}5kQ1SQX8>lJlh6~AEpQ3AcHa4E@}@Ev7|o=zzC-d&a9+NW4xL08ie&h`Aa~I z5b*<jgsOvKNv!7{Y2ZLwkX*7g;6ooF{%#WG!CV}+9Q>~+T_@y##U@O>-h40O`Wm2X z2^RBf))4D>$YiqFY%Zq*Ri|7wYe@ek`+_K1Y&N%DenJ0Wkw>)n^o9O_!|JXQFGlJ- zLt!_k+iCNdf2sd`jgR<|&t*=xYRqL+lLLctHO5Lg*_3L87!SmCKrB*dhcUIGPtk<d zYU!D46q%@cP%sM(H!`vFJwU9C(gpyRGYDW0FrZZkGNJL!^cV@_?1-y$_SuiUO)C=@ zIv}R|TL%5UC0j(1Cea9GD>8@t`e8gva8;$9z=*K^)S_Vk-9~LQM9dJt2mhw#fJydT zbxkB1Yb31~`auGO4g$D&&T0er%#YS89Bms-iBDT#HxTMZeL&Pin&K6cJZqpbo0i@% zl2QHemW2i6#v{G*es<)3{Yir*&RcNf=SCRxhNW*mW@Bsa*PZw4k6=!X&&R0~&fqy- z=m%I6!EjiSNP<FiK`Asci>RaoEYX_Ly3#z?1@6e_kzMI>19nEwP)r<{)$<6!N5rmj zVwUAdjt-o*yhPjy`7V{p@S&^rTy@o+$@wm$#o=`?oxW<E9HW>e4|G3Nhvzl@;WOgS z8vc++*v&}dvqE3sPp9(|fE?s20i0L}45L|P6JZxC6zt=2$kh(dv1&xszDS{sR4tQ= z%ew9QyHbp*5)+%CLKX4th#Vccf9s_CGcwvg_U6c@!9Sj#K6-aJe^^?d#Zc{T<nAcU z2u@^2K74b+y>CI^>3L)$eK#};^5lU8(CAQC6Ma{B-xcb+k*q$x?=V9rbiGSl^#y(I zZt;$BH~*ggQ*qTp`rHSGr)Dd$SfpdxIA&Xom>`4lK;Ga$q`PC%207V-{MJFbbp<0B zB|9oTq@|<}fi|J>4cKsC!)EbY($V`5+|Pb8)&}X{&wF(Pf(^xg`cItEt4`LA5h_e> z2O?uZg^y_pB7gugJH|C->w)uLmFRANW2Em@_&_Wi*l>WojrM)+UGZBV{)vwVJx>tN z<dC0*=4Yim4*=Uxt5JyonNQ|2)j5aqfuwrM`9X~f`9VFY|8SYOXLvn(MDl$23iIgK zvOQ(#$>Ax)TO<>a;|>~A7UmLxRu4QvLNSxduFx|#T-l;op*^#VJu8p*t;in;O~6BB zgF{MEDxDjlWkp*MH4@13G(-xxE*Ik2>7=bUq^RHFz)^5~DdOKfJR9-Mu!IY{rMLVM zE(DK#9i<Gw{bA|C66gJX{#*vCOd1vj1kz{GLN{-r8%9OZ%oW(t<{8ix7!>3{NS>gX zAp(nzkWt`eT%!WW?&VENB9|}3s5EY+Vfs7Q-K>9#S~lm#>)3`H_2l94Eqq;n_qtoq zKn*9?--v*XCoAy>!1+xs(2}0pmjFdaYGW9UL3-3As#wyPl@*%!;Bny22k>d785cf@ zbhYOz1S&lF<Sirr$B3nWz%Sy&`tVhL{?@P2g`;wV))6nK-KBg@2JKv&b}lk$%pNik zka_|<O14r?ltDf>D9o#Q8jc*kK%$I3rWQSt%9-ULU@es>@j)Ovv6^c{V2vNLV|g4$ zXL=wf^|IoHCNp$|&YN{7?;a!$6z<YEE`S{l3O~h#5ma@mRZ9G7$ilHcoq3Wzovb%t z26_yD(f;v`M_L-ic_2ugn8aB__z)J!$z7-nl;P{g>OR_q5{Bq<-UsgOM?B`Z!MU8y zj`jliV55DYnh1*_*N9Ul=MGS0333MFpb}N#`*69e8WjX#fgk0u!zl{xN5w!d|3UJB zB4SehI`l!Z0gcMow~?np3)TXg5E1%O4|@+Onhw<afQ&*eer2oyv)Q@bN}2>c)6+xC z7FJ<SBnRAc`$UsrfCoXMeX<0v0@MrmfV}<yxr2m}luxJ}8bgGHY9+2P!fgWxC?wc{ zzqnpRyC`;_Ff<{8S<o%A!Dx#%TL93A-{u}Y05$r-m$`oreKdTXH1?F2jW`#$kRkgz zxjF=_7N}AP#y7wPn<oTt0a3c})u3`YY%@Df0BGql#3LTMOwn+aH_K@4j3l1+5Jgdy zAdi7VsSo}nSVTNl{__eVyilOS&bJ$D^>=ELh(_N9+Z^lW==<g$>8H^Uv41Iqd*an* zlYTYr$}6Hi<r-xU@(2uElrZka@EjmQ21ihzI)}>QMbY6R`@AVrtgcT|ra4gKTFlLn zVAm!Jb~VSyD#GKBNO|K=J3_)qLx)5&Zzfsk+;K{)AZ<q^0_WYR`?YIP4Lee^2#+YH zNM1zr>YEqU=+2r&`sR@%Q=BQbUEh*&PMN|?wt!2zE?C3FDLAZeVcSO!AG?bVgX{2D zv5~70fgOXL+=2M}A}T8LBD2t22{Y%ZK3+e;K$(nD_{dB3fMltLYW$C=)MGVP5L1^+ zQoZI;8$KQi;DI)Afd4&7)cYmxFSOGGaQR|#T?}1jZ2>{2hDDF@Kmum^Vt$MiD&uOy zph4Z^^YnwbvSRY@DxG&;sW3eED|dVac8o{x$dAa6peKSCP<lklAsU1dK0!dh?ZAF1 zeAvxAEZTqH1sDGOfg7XIuP7GZcYWQSEjy2G+@hFWpLVr-AC>;ldiOmCF1YZ%8FBWg zx5IUpOIEgQJhpR-(&c~AXI361(s8?l^8u}InM!>nh-LVJDQ@qyj5bK?m=kKR7Q^$& z)Fx$LsyREriAJFbdAO7MB|J|DwV*2bQKZv@k>L_!Ggxmdgy1!}rVzf?A*1Yr>}CN3 zB#Ob*ip?uhsD8pOb3xpExZfWM`+w*U?_m8q_=dT*u=Vwu&wBh5g_&(OTlRoI=VF<x zTotPc`0MKJ_N@MMSI$r6{=}yOHF8{T2;5g)eP5sfn>B%wwdS<0=0LouDekb3&R@zi zs2TOYQ||Y;%Ds42M?6jCY~jloeJP;;J-y?&^o^S!BSxyu<9R?d?EDX|{tD&*cmJqt zCHu*ECb}P9eynULRZD0xP&&Slas7bi(8xpZ#!B4eFmWgVA)tUs5KTZCLi_`91$>8d z9v;F#pOoi7pTo0hJWcd0Dc%Osn4|pJz4I$rjiEP_-Ge}sQLKji@j#9c;;Si?KkX01 z5=|{!wgM-`er+t(L{X}U*dJAE4ZDq8ZAd;&AU_$3Rv=-5s3ol12LV@5w~8-NzUA=j zttzja#2KDyQGsqmNbIvCbcOE3J7sI^HG~+6;x<H9(p36?)Tf$%tWSK&FxUVp<45(0 z)(u)YPSqpy_6Q>J=;;NcJ(4GkQ603k*(Zz;9_cc9geb$EMrfZuz#kq7AcODK)>D<U zQ;iNvl3;Www~{_jIVvQfC}Qx$G2t!e?WeJr*!Cdi(ur+{4m7##yw-)$cK(>IO4|cL z{v4!JwB4it20Uqt(WVodsz17$4)3N?f0O0`)f`I$128a4%mWyX@CzlfRH8A-AN5l~ z1R(ZC+fMV;i1?@6tT<}Ud&mt$_yL~VP?<NzbAV1dGq5lwdHKdxCeyMGJ@h2KA-><% z+}oGh29Ig;wr!~shk*M*R&86eX4@(%nKgNiCwRW=Xx}P5LEh_VPbzIi_S)zik0YFd z^rw+I-jHhg2rim1$LTSKm=h=Ii@`(S`FjiGJpj=C5i^|dZ`6_<FRzTOr!=CICiiCi zxQtPr_vU$jptc^R{;2q((Vyr2)wOk~)|mR}9^qLUxd5d;eN=x68%b21qBE%IgZOU} zSG+UeyNUgw9IhmggNMfYgJ-=oG()RG5&_tcn+wE^sGAFeKAjywrp8NXJU9%G!Kg4G zv0|vauO?IvEfbg_egUWz_>rDyl;ri^DVhcO9nF+<Nco|Nupblh$kU*tFlf<!%F{Uc z)C)nLSG<=X5qUJBIm1<S(jkW%^Iu6wFnGNtjW_DQL$!u6We7>`LLxhAJT@1m+zLeY z0h>b<2zo@Y$|ypIb#oM<qxncZ9!2QrSwOX@Y4n`k<&*fs{(vnbatzM`q*62hPVrEi z{gx^KXV|63s^NipL6q`zD&*BeRfm&2(oyQk!)By^rvmT774ZWRbn2%&@&y6%l4K@g z?~LbI#-J1I8R;$RaQSl-xClrRV_%uJ09Yq<7^P3@vc(ur(TO1lL5+C`6jp1pl#LR? z`zSdGh>cOfCn5)R7)849424EK9m(yLIYAoY6@u{RUf?;(p=x9tP@vctQN~Bnjo_K^ z5r()@gjJp!RHq1!tDzN~l%m3^N%I9VSd2gDpU2-n{;>R_d>U4gm~a)3a03SJ^{7=8 zsRBnLWqE^CkY$FMMTK;YdS&op6Ziwh*JQ+c7Xu-x*RMrLRrSI^(Hw9*Xl`^+;14?8 zC)karE>|h2*$^<E3@CBQ4E2TT>;m@ZQ5eXCb}=Mw;U9Bdx$F(L>(=X@eDb=EwzlUk z|NO7T!PRUk`iSv=Z~6ae?P`Ofy3X)@*98F)Q4tXo*AGDD!+rOA0f{J5gTzwXM6lK% zB7zDS!4DdnrY5n}8f(?0CK^qnX%nj!t+B*9Hcf2DwvOo}*0lNPbexRikBsd&X{Y04 zpwGGYS;fSD{K)Q}ecyBLInQ~|-RIuD_uO;dv)26Q9KCTQW$A`@o*9#zva0VXlVYx1 zZnw?!`Ddd?2HpDEm(7w+#(&i~I2kxGJkzWXgRU9djznBB+k?mknBfebfE5X{Uv@3& zy3-6CappF{*s;H_HS@W~jYmIYiTTfP*0QN~x8nZ70>KC4LKk!5#g9%|@tYenS%TZL zz8i<l2j&}jes5vnUQ>g4;uf3l+66*~-Fxw$gAr%xqs`0|JU+pso4nyrFy<%EZUct4 znC^TGRmWb9?}|=$w^T(6Of5yBs+L4w$-{M-yOwkwbfqL#wYbg%Ye%J~SG8pKT`VjV zUv^7X#&}QDj75*d*FAKw(>=`XYB6mvq5Q@E8`~ZnR{9TXJnqKvdNVl@^LicGU);Yh z?gPxiF<#{DdmCsd7njlhxcyz+_jcR|Hj*h4dmWHoYl=Y|5HP#ZiMzI$lK43(1$WC* ziK2gIIEc78&gVMPY(rU7-X75G?!hQM8w;MI9Zb_tHyQzX`g@&lN8K?y#v#v2<~8|Q z#>#Zc8jrGeJ#Jv^gKo;1G{kM)$bsczcE#}TCS#cBCAwu(5ISr%-ZcAPft)a4+W?II zy+}9ZV`;k?UpF8vwk?L=jcrDc1#UO<x$Qb%b@xar^g;h2nEa-lu@J+*fV5_WSbQRM zvoB(Ctmo4I2EzfQoA$-F8HsrR7061+V#pEPj`ra`_EuiI&BhlP=DFW0pMWxEUo1s% zA;fW;k+ER8&)NAK9TH-kZ;cf-BP1~*uo2uH_;#|GZ^Jnhv%j4$^x@s{YBZzr%~1~7 z*uU@2w<(D;?hS0iag4qa=iOu-`fqRX%3P_D$K|kGls;F;wa0bAb$w95pz1*%yVu4w z#>3}Nd`0|~!PSF%2473qo#;)hPu!i9lvI(_opgQ314DKUxtd&-+%t6S(Dg$Prxd5u zr)*7mf7qW=t5dsEFAq-{o;!T^h_n&)Bi<dEK5~0na#};$=~20(cBVI^zdO2m^p?@r zG9nq9GtQ1F7_(>0Cz(~5n=(&jUe5e5D=o{LH9u=h)~T$&W_>(1W$dD{hsItX=NtEW zc53$4?2pD*j(>jqYvZqY;yu$mm7X@w4$qAVD<_<rIBVkhNsmlAHaTtb&dFDE(sH_U z_T`+&xt_Zyw>$T2?zOy>yp?$ur$nYSPU)Q*ntEwk+q94JoAXcP-z=yo*i(46@M=+0 z(axfq(~G?s-cy>ZkLX*z1YfVe-oGP|8F(S+4mJhPhSEceLnp&Y;rj5A@F$U)$jN9% zv^M&5^ipv~@si>##g|J8N;*saQaZD=x%B-R6*FEcOD&sQcBbt5J>Gkso#~ocKl5by z#PaU)zt7q{>tD0GXaBRJw4%OZzkT+457(5oj~MVo5a6gm;NSqisd){vPV*c$()gsn z6_>d2*w9*un4=4xl5e8!Lci@H>VwR+H+4692K%VTSsNupJ>Ck*G3p6cx_n4I5&BK) zL#)ZJRO-pl1Jp-Cucdz8N_WL<_^su2?cA_oL(z)WU2B?KmbJHa6fJ9S#i-48%-Qb3 zl|c*E^=!5}ah32gg3t0|#H=4$1GaiFbAPGT200J;*F!h?SD`1+1Me}b@ix~MF@z2~ zw%qE#>Q!rzdpVAVBFt8;#tH;AIE&wlTEA$`hi@GZVoOoF384k}D^O+u@~?mg`_*<W zijrR2mJ;iJ)V>hqO74pFS){^GVg0`rcs^C`0lOU?u&~|U2Lo-Yv0LF-c-zuu<m|*+ z+a~{dw9+Y2g!xNeSl^14tpcXW(}eb!wl`pp7hx2=2@&jfAI?>Gv-f|u^6tOX-BUMM z=3RvSy&Avr8vOn(w7LVS#{O12$LEn}AzIvk_L_ZSSmx}L`|S8_e)+JEJlIPSJOeNc zEXKYFAjRQh07s(z!pdFtBU2|f;QKusr!FxbXop%U7$*`Z@o;{XAc>MBLj==};nL6a z?GBd_*55FxH4UAr>3BexA!8&{vSch~`<fXC9(XjGD3fHe<Y3Zk9^67s#jskqtC2$V z4o}A!Td{__Ujh=85T?3CB#ITSOQaM%vSpZGI8(}HmdwTkl{r!=U%>hOUa69KQZ4t% ze2lxUkuS*t`LcXP?uWykg;FbZvPixvi{)#wL>@FAdZa;?p-X?cG|37$rfiXwvPxD< ztF%eGtdWOgt#nAItdsS!K{iU4d|e)vP4W$SM7}AH%C}^*Jcj?2CuEC!Te{^tvQ@q- z+vG{vF5g3U)b}w^c$e&!r{rn*f$WiI<XPD(`{X%X1|N{;<%jZu9F#-yqWnmHEHBB+ z_;>n=9Fe1POnxdoavaldekLd772JvZTzchIIW51CGZ^)7R(>h3$*<&fc|*?0ujMyb z+zv~>%J1a&asge!7v)X)16Cq<OWu}C@<+KW@5I}uB^|u3t;Os0RyeZUYoreel=gPS zeT@4l1C&9^5M`J$LK&qjccib<k-<v$oONs4?MSe4wk<<mr?RluDHQhFndf+&bV%C> zNZSZVyK+doa!9*!NV{@K8)uGJ?Z!ab_>ja=;;7viq!Ukxr^Hj@De-*7^AXQSJRk9V z#Pbo)M?4?#e8lq+&rdu*@%+T|6VFdPKk@v;^ApccJU{UQ#0wBFK)e9)0>ldtFF?Ei z@dCsP5HCo)An}643lc9#ydd#{#0wHHNW38NLc|LZCq$eOaYDoi5hp~P5OG4p2@@ww zyTZf^6E94>F!92~3llF)yfE=1#ETFwLc9p^BE*XjFG9Qs@gl^F5HCu+DDk4iixMwN zyeRRa#EUw3O5Q7ZujIXYopMV4EBUYFzmoq-{ww*f<iC>tO8zVPujIdy|4RNV`LE=^ zlK)EnEBUYFzmoq-{ww*f<iC>tO8zVPujIdy|4RNV`Hv+t&3R&ulK)EnEBUYFzmoq- z{ww*f<iC>tO8zVPujIXw_e$O?d9UO>y#F|MkoQX7D|xTvy^{Az-Ya>pA%_o2{ww*f z<iC>tO8zVPujIdy|4RNV`LE=^lK)EnV@(LhUh-ebe<lBw{8#c{$$usPmHb!oU&((Z z|CRh#@?Xh+CI6ND$GmXI4)R~ge<lAl#`~yq9BI@!j_~i(EB#OO$dlH*o`jm(<09MZ pj#tL#*G}k3t((`AwgAebb>n*C^B33F^`zzF+C&yytvzO0{|1%B6xsj) literal 0 HcmV?d00001 diff --git a/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.woff b/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.woff new file mode 100644 index 0000000000000000000000000000000000000000..8c54182aa5d4d1ab3c9171976b615c1dcb1dc187 GIT binary patch literal 23320 zcmY&<V{j&2v~_ITn%EQDwryvUOl&(7+qP}nwr%T)@#Xz))vdaxYSlh#^~UKsfBJOq zc9j<s0|Ey68QNGt$p6_qf&bzE&HwKZ6H}1|0s{8?QStu6AJzU_aS>6mA1(8T6a0V( z7zzkXUYUXEN9+9I!ap!DFOd#1wlTB=0s{G=z_>rwLFyJd-Ppy62nY!Dzg$rNAC#b> zW_IQ_KN{(eU)_(Nsd6JjiMgTUPb}E#|M~#|A(>mdoBe3JKtOVEKtTU^2nd*oEldqf zfPj=PfBaZ}zy@NZ@n!KN0s$!#{qX<lkisy5AzIitx&3H7KQ+*PYCQJ!AxB%=8vppI zDEw#@KWJr%QIoSVbo;5R`tcL@Upx^A7;x@iLmN{dAhn-dzyUw&^jfS*yRx%&bOHiW z&;8*7KerOpCRS`|=V1C1tF`+RNB<vc?`hCnO^trmtc~=;A^w9#jneUt1^xlhByaxA ze|82A<NkjvG`-upv4M$!!7iu~Gz5}?kpWo0w!kFF@oyj?_)=haAfW%Qn^~G<_V$kV z_D>Et`TP45!w50c8!{TL10RAG)dniu*zrR^LTrn}O+tRb0xd~0E&>H($0brSGJ*iX z8bUAs<d}-%mmV-c8osevmk6I%5UC7vh0-by)a@7&y&?k3<Z9wTgT)U|*lKsVAQ_rM z+&xXPgm8?(&&*sD4SGrU6V}DU^V<FD+WbVgCL;-D+8{ONP3x|b(K?Z}FqQyDA8lEK zfxcR(LOT*zcWBYweqCi%t<h2v=dH4k#a&-ac4;gT#=k%#pf1hx|HU#VgeV+oAC)04 z6<?!EWj}**203RT=#5@wm77PFeIX#u<?oLuhz~4>lphEzmTHiWB72`anLv4VuEY~_ za}WVZu^zT;R-~y&T~BYSiJ>00^O~gpl9q$zHI%Y>Lhsr-MaOrb%y%q|(42pX<4bce z&%S(EIYGx}q8~@4pX*EKdS?h=SI&tEv`GGM8)AScL0;U}brn10v;~p2;1NOn2Um$W z*U=i%VuwBRz@Z11qKr(qgO8vr*&X5{?12dd{6*l`Yp`?k3MDcih%qI+g!qV2n61L{ zS-80y9H-NmrN`sSUC*p$lut-w`?nyb*goYXni_zf3okCBA{zrCwXDq^$DQB5U?DQ* z61o2X9r4;yA!5sN`)f6pe9e8pguH(cK5%0-vMf9<azURFgB@qsO9$RyPqj}Vz6C7p z88I>zrWWth^A{_9wXmH0nW$}wo9hf@Mt&V*5m2_W0Zac{Bwl*3N0W}7D6V5mO|AbT zMePe7b5d1qntWOB)2(kfH3+1h@`qd<P;-YPKtLo%n{Oc<r-es;GO8GaLQcSg;XK+L z`zjQ8l|UKpl$7E=2x)>Cj$7%?Ws`6C=E;z?vBmFy(ZuU>?ZKAjdKnE_$3iyZHlp%_ z77-FteGS2x>7s==RC=EgNc20pi}B5ZYP?<*;Yn$7M)<7;<>9ljc|Q@}q1HAXA>?XX z{-<=FYU*8Yx_bmPn*eq|(6}#S=KV{`|BZ*Xn#BSEOxT0n<2%3UJglM<ldqm)p{Gvk zznudH0{;F6LUdd2>Vh`FJxT)N*_o6m(8iH0h%=F{CzZaZ8j3d^x{KT0bRC__^79ko z=tr+cA_{hBgbop+gr}pTjdh4lR9OGJYID{f-h7TdFVsTYrJ)sVL)@`Nes|mRJSCBQ z1vY;D{cTS=MK<Mm<GJ&`%?mft_#5sOZl&KYvbRt=XbdhHJlmT=n+fO3rgpNfb}W&D z$GUgGv~Lt2mll;L8@0fQgkpGOlooKs|D9&V`DBLsjvB%!T0F|Im%_-jFit5WR(FD? zq*|$&|H2%85^FR{eO*psA`Lu0CUbFjSWp%~dpsCGD^gTSTR7NCSqLNA&)akG3eyQy z61~KRD9@D}JvRXa5Aikku9YS#v)0d;<>u(Wy%|e~Iy~QIi?KJEB~oXKHbERbMSWb} zZ$4oLo6Q7!JY7E&nSn99sadal3PMV~{548>MpAHY2H1T`ZcmF;%7p*Gd@)Z2X$V%V z$1bYU`a7{N-&8b(7EKxaD_#{2yNI&{t3rygLIQh8i%wdtQ^A4QWPw@AUkIZjStyRy zt6gfVP}$xz$w}4TO!~910gWc?ujr|I`%rxo*~ZRJj0)|c2kf0tb<J$b#5f=4c81x( zZ%7)E;8Mka7RH<jgof8lMaE&{G8Renh!ku+hV5hxuca?UHbk792|7)*r{|fpGvXD@ zr9iQI*zKu>H}jLi*?h7#a}r#3UcIh%=Rq+9Oy<}9gOY2vy$@K}ixTio-4X=M1@9qI z^=K!qz=h?boc7!Dn&O<!kiOq#v5G#>o<J`XvhMyBD8Vy{aO<O>iZq*aBh4h7*kXhO z>pcXk->0DSLp`H8gAy`9imj3RrTwYMLn%~ax2R;y6z$S#bv?dXh$n!f{I%|F6CUzH zNglJr&iX(OdhO|M-zijiorLRikL!4b&v<-I;cb2U*9AhJqg6Km0|C@3UPi3VuIeHB zE<VAre{dbMO!g>vJkk^d768V;-U<9n39<fS4Z!%OE6P*)w|cf~z&NJ9q>OEzwHebV z^!;=ohVM{+SKmNmc(fHuOajOg)eZg4gP9Z?_0r_5C&wd<_hxoo_+<48kwZJ{Y3kdj z-euRxbNtS4ORoUDw~*0{d?YbybVf*Z&j3f0Df|p6wtg}#){z60vHIVDYyvXYiqt<E zv42ntRD|g6;QriC<grTFp5B)Lqd3|98*VJr$rST6j1b8XNyF5`p`cVWJdx#RkA#3e zK~fI0Lv34q9~2^ftGRpUzt2|_Cshs_!#Ws{m%d-|Pq~eGfxM2-tNOYQxA)ybo&tPr zy}D*~4m(FY$#qBh{JlV|hcVkn-@(3qcZ{-=R5EM+SZ&PVI;!a`!xqz&hp{B8=wre4 zg1>w5fLstI@;wPh+Bd5ldW?|#AJXDCfR%eUYew_;&(+g6-=ThC?S3>8w7??8cY@rx zXANRWBOACbA6cC_l4+aF!&NSKMmj<F50TeM^11=0$IbOguWx+Ry>mK4PZoF7UG%C5 zf)X%cLC&;>^$NdUhi>}OaeOh-03Qt>c;rBMl8FXlh6u#+T;)aNQAM7iYm9MwQAwQ$ zauN?iXC->xfF|9A>Yn3rfOkVpm+8&z?LmtUcZTECdVP6@K8N`=NVn%wvgYT?wv(~@ zRQi1syDn_w+iAw6*B2j_C#*4Oa=3>>HsxLFzfc-lqHiBWPsG=v_Rqfna_4v6=XxDj zbWvX=bCj4jf>-mGLa)^qT)yEMN*AOa6}Y=z5r^W#5+eB*=NMYFLlxp|l;Umkrykmm z>1Pb@=d7ZMXh-p<@vNTD{%C%$y%YYN-VTD)5%>5QvQP<I{bfuNJ!2gb6l~c^l`rwM zG@=4mWTj39^|f+JZJM_C@N;q3-yGkk&ndIcW8)lqt|q(bP^jigG875^*m;bm5S(E( z$scq?l);fG6I8|J^XaOU*kozS)~ZEx6&%b`;&S$?N!6A6W0Yr^`&HBn^<lmo8Nv=o zMJdt0^ta6G+d8Wp)b?~K^PkeL@`F0Q%ID#3aMVNUrKFwpt+ZEIc$W65Mfb)<JY5m5 z9hQ^`z!Rom0;pCOcWO9>lpLYJRS<O<9_~I0F{K1kixeF)9XlPIeCxgt2d7r`-nbZj zV)f_UpvRSv<VKp8V;I}L7M8^*W*G-2O~g{`@yk|{KpW#s@*<feBo|;ie@Dy@h^~n9 zcXmk8`Eejsb(PD^B+KP{f!^mKl2*&37|ImXnfS?UQsmh2f$0zh3&po%?~Jsp0Vuc< zY&a(MHfx!m`u|Nc67f<TbZ2r#v?aF1wZSg`kqVyQ73C}xE^A2@l}b#uo+74`a;y&e zyp}n8Wa#y=YHEB-rd2RUD^qqLUP$wQU9V3RS`bj0(gNQ2T$&F6yqr<n_!(!|23*0G z7g_zCF_U&x9^cc!B3idTC9Nw={eJO||Nee@i&YT}$l8sH{Mwl|zwkVqJFp>mulc?J zubo~#6g|MIS#tM^y?0~C`jU2#a#T$VEGW;6HZHFWLEd6C6gfhTw6Hw56Q8*V+~VWN z4AL!NdF6?QxaUpsR*ZThZ22BrG(+5-Ud8j`|8n^?HPZ7*MH$Y-GdTEy_<}Ip%UH`% zC_ybkuvZT`(*5-7zTSgt1y-AX_=4Vq{_y1PK|t=n8Jsz8N`x^1R#L(Hf(SZ(R}et= z20=K0`i!{GTB{~I3$HZ!fZ7PE0K3mgrlOj^=HLjmlzB{Q!INjU2`4JhvkVArhWI3g z2BFDRMNusx)0QK>n-{_BPLkO*tH<t6Dz(DCVw{(pWg4$U6mjW^M?!b)K>?}~b^*t2 zL|B8@3a#it1GzFLG>-jntCpno1TF0OMs-3&ICPgAm$awK{?_0%(W?W=|3Ym<2B399 z6?sOv=odFeFq-4ZH~dK}*A#W0I_F%hOcy3B(B=(oS9N?rZK6R)u8SFgYl67%j$Vzn zT2com)G;k5ej>5&f(ldAjf;DQ6!5hOSn{C{3@HGgJ<Y#}SD=GkOhxTYRR&WZgTQhx zH_d=VT<?t*N+>fyHHbCwb;JWINl)t_@@KmMH+bk8Q`tU&fRBnQ(#)4NSadxDOZI(w zdDV`IZHTev{l3e|YJOjG)!*{Qd3Bbc-oK>W2LbR{;`&r7v=uuYN}Q!j?bR6qQf6%Z zD|U^HaP=Duw&<9^4wcHPM`Vo0d8#?cwduvt)W!CY2}SzBBsBVDmS^qNq)C$4z-w!v zu|}GDNU(nCqGP?m2nGh>so7Y#2j<s;oMD)xzvzC@oAEg^IkE-H)aIAdPE&ddbR{Kv zz?P4Ls9REPf?_nP3Y37utt$xkK1mOG%TcYwRL-8$gEJXuB&z{Uq<|?HBo6KK(Wj?J zn7?lpO((?e@oqz1L?HE1V44tGAJ;Rlb*G73(-gvZ*QVV})sDeYktz#OLucHjCa`iz zj#G{XAhW@jqDko)(_*u1&v1QghF|w-!*B71m}pm0C9o7Ths?<4GzUCzkEOtcFd(N) zR-NK}WafFMD|Yn9UNLQQ#p?BeUtWHSIeazWv%Sn@qu9vfc(%jk;7a67g6}2v+3{N; zI#9U6dr!|U1?vC3mcwzx51E-7&71_sTc6<u*&Iv5&S5s0A3kjCeY4qE&Z)P-9ToDY z@_9tA!RpL?j<L!GKSn6V8){pIS^jF=rlmzMlWF_4kpk+RR|Z2(PK_Q-&yhW*(1AYr zzDum*tfgB7Ha$=|AChj#IVVPj1`4-zEaYA&14_4~dhTC!T{*9<db#Fci>SAF;UD3l zTWTJlAQB4XoWDz=q%Vn+jEY#AwT@9A52;uB*W>Xje?f=`^s2DJ+s}<wE);O8ttKAV zVVdi0E%z=EH;#44EW3V7YGseH0SU3b=c!pSV1J2X(*4xe=knCMiuVMhF)aRUm66^B z<_q!fn{|~)S7uEH;JoWOJ2Mrkpw6zyi(3XJqtBEoaErvHIYp}H*j`(3Nrw&~`l>6b zZHctO--vJs(vA6u2D!C~MMV%ZF_OWKERqY*L7bn~pu>emnX~};w>xKsx+HmlModD* zRe7jxvS`Tr6uHz_O`!|yld+VyK0FQd$icoJ&6I5J_C@tYl{!GM>wg8ezB^sMFG{SP z+~tO=8DM|68>>8kL{vLa+9stZVE2&^q(j<a=P=MIUQl<~6qs3Whk!U)8BaM7o#vWf zHIdjUw~C6@0W0r*n-~|yri;{}t?kwlaip!a)eiKO8x;G(J1BdM^qkFm{(cS&@ZJeE zxe6sLm!E`;yNen|^?a%|FO&BQD;ZHCIurauQ%lG@$_T+Qi*}@{)lwgXX9S0l#4L=D zD0l8gWM*QRXx!cyo`47GOFBNpDIXnyIo80RMDX+##KZlh_6}*oYs<#lM{_E`*&a|0 z9?IH-SaET>&WrimlxADG12>h3l$)M<qSLSC7+dyn!#^5>nnoG~F+Q9%u&_RYNWV-S zu8Zij1T3udO7yF++y7qK8?@Qy;j&>d29gBr(=CZ4lKGZq^?3#ajS1CkdX7~BF>3+> zYZVG#qpmz`T?l5}q@jYe4}&tAuC*{c-?JynbwY*R0wc+;hotR!1CBsHEV}H{pEV_Q zQbs{v@#pEsI<-g|xh#rQJeXH}di`N|kNqjL$UE~3So5<F@?4q5Mb!nL7@lG`&~&MU zulIpEtGc%l)tznBy7I1aI$su^HayiY>Z0bsl-UTxtBvq=J|gu+RP<bZ7mBGQ#%SN3 zgj~!&&tvvZGu|rTA0DRsV8TQU-kP&fwaU!0U7k$;vNuead<VU(pSX@nojEX>Erd8o zq%Cu)1CPBz7A=EEzAUR|YC=IU9%hvt-M5s$vP}yYbrS8_xEfnDFCI~k&{z?<!G1!E zK^iZQe+bHf`7!IHXQ83rJd#1}5)~%c_&+uxINN4BK3{JfWuezYs-XMRHwoBD>w$lx zkHl$$>l6w9E<=%h&m}p0DcU+fGPM`d($iGo+S3fJhaypcIE2yU{5H<0HCgoFK{GLe zCVD+P9e_etX_H9_t6xc?c?>7@pb;TOf<dm}8%_nHJ)`I(F}c!$ODTK9uZilbNw2u_ zeb8C*HyGMNBey@3QUre)`94+`W7q(zLbH@7+)X-{T$!=p$K>6%r&2oND`VL682Y@H zo9cs|v@$?BZbm;;TeI&1a|hDjryghe`LAHHYtRh=V`G;8&hH=u_R(Y1pv%n=LH^3^ zFkvIs>V~3aP^2c9bjt$HI!&KIsHF;<6GGV<&cs3&h&!7&F_0TJrW*V^F`?h4z4b9P z)shrVOIq;gnBtPE8xy|c?B+5Qhe9v=A{q0$_8i?gn>U-#3cMhdDV#r)gg$jBSHuwk zk}gryawT5)H|i8gP1CW0tGr3sKVvSH=C;mKYmExi&<#lKQbxbVfh72pcQ7oRvXB%= zj1OXzBoz0nqSwe)?dUE|N0dA`Jm0((=&k$p`<hR}4eiPswo$9aPyxLO4i~!g=mnTx zE>L1c)=>Mo*a}LJx~+>;2tcjSh+G1pg5Y6PO}pj8+;D<i%(EpdjDHzVa5^P(H!aRN zDG9aJ;;WOiOGzB8X)Nf8hRU|IOjcSDRn-2j)z^c-OzLsWd>LXc4La-kzxi{dPSiJ7 z8<GOI{i~RF1BpdCtTs;#S~FBa!Y7@=1{d(WZMJIG^D(UJx_Z+Vv+cN7VVIAJM38F` z&w!hdCl8g+wz9NpnB>JC>pyci_t`xsI3_*zD$W!<hdW6$Q9Ua-zyo25I&FrlHu{|_ zYp#0clvH2Ks-Oy?Lx!n}E7joN)Q~0cD}!}Wrbv<rv_aX<y%W!&1%8=}Vw|(??+{!< zGGpBE^MdtcpA><jqcoA=99>*$<4tXVP|Lyd;LAI{(?h2Cw%dD@_;lH-jHe9S+i*4E z4mm+=yxP3;fjmRcM+tj5WK$Q-9_(!w&4?Zu{~+v=o|o<F@{wDx{!G^tmVmkOV5uOB zh$QgAFD4CeDn>`vvKeY_m&uw>iUOhrn)3ws&_6vxHpM+hCYx}osCc0Y-Tyq0z<hZX zfpCQ-{8OvGpZwcW^f)}Lo+>_HH?lw9s=QM+-Q{gQx~FocK9j!8!mtbNX&zBR0Xt$l zvErya$XNJ@m2B@ie45(Z(19?S0|j@Eej=zw0gE??YVlwp4LSl7VHUHoo|LraFf00W znbw<}e@I<Hbw;);W7UCbDgM&wIGk*$E`08I8>Uzes(fu}n<{VdSNo|T`)7axnJ2E3 zGN-K>ywjN_qvqSYS+3(Tift}Ac+Th~V)w~#F13j;D~$iUE^?zyrm7R;K!FVAfwf4+ zgEe5#q65&2_@2P9Xi0@IzKK<kAr!<DPjQ=xFOaLN-rrtR7gc3RK{~fhjwdfH&csKj zaZe1M4|b616oGh|PlK!ylqSbV+%BkUfh6LMQBPDHedW1RPRNBs6bBoa-b;N6+{mbS z!$ND!ZmgFWmo}hTfxvinE|g{AU`~8Q0za+=Z8c0n=;zija<Evjk@?80M4rrT#ZQRO zrBy?VgD@Zjk%XQb5U2>B$Mr=t77zjDw^ry*`L~i%3hjv^6l}?gMTjnmHPNyRD!RE? zVzeC>gkFuW>V5P|ms&5GT4O@NM-mhCx+a!f0)LQsDAs{!i(cE9Ov8j9Ot~S$SX^Tu zbvv@~cen9fE3YI>r2~|YyQVnWpZ-X~m^M6OE$L`m&MG`G=33X8DprYlBgvrAjN>#) zf7F5}TO}Od#i%Pvr08HxB1L|F7Lms;vt;^z`LYoE^HAlcM$*80N!_Nc@Z0C)>z37! zB*8pC&7s#0b$L(fb6zzb_{hxyz+_iYonkQLn|M^r48oOlXXt>e7{zFo03wLhcxL@> zruxmZD;ZM5U?3RR7ni`br#{#)H87#K@FBbE7!;=-Y}c+8!h3d5JExlz2JatQJ+?rH zEiUGqC0jaoW>(Evnh`H^?>C|E?;wdM>7y!8D4dVkC<+|T0zP?LNZT4#$T22k5m50< zzoALNpZ84Yo=WEiK^k;g##y>nq*73%RqJFJOX%P{Sin)USV69lwgt`-QDJjC{IgNf zBW4`*siNB=F5h|FpHc}mY9&H}jGvvlX!|~~dIc_J`?;(WsSic(jU>39iqS|Q7u!DA zY&kA%G@cdsQv^FWgQ+Nx#A;({7tI>&nigS1N0T`xz+mg6@_{zT%;E%P(``j&bsETN zs(q(bWF8KI1M_eY6S%3}4I-pbgJgDL2EYIzP<M(+c_8ONwVQS94>p(Kd(4_CqWI0N zt8t_kb+H2&h#4kT$#q>Ac%Z2bj@0N+O;y@sWv$8hU9Zv@p#uT7sP~{kG6820-K~jc zzx+zAW+=CEi%kufkYzrAXi1hFg5D^8VfWJSQx~1y>x~0bBV$33&FY`a087m+i@@r# zv~L(PphOgimWm81wL^lXk96(eK$#U=hQ}pu<-Srb@X)RzEK4@vVL9cwNBv&D7`P0@ zqV@&7+T19`yV}oc>o1R%dLPHOtgykfkQ$mBKeZU*==5=O;{`t7RV`&nOFus5HWa@{ zXbhx+TZxRv=(Ko|DZe>7Tjhggvxn2ed0umrYSl8cq1^h1GLxv~Ovi$ld?|yHWQbL0 z!Ivh5s&TPz0K^%VfE05%mJqQKs?A%Hu%Xt@^>Aoa$L6|fp<>G;+%>slePPEnR_yRL zj;yc0lCyoP$Ic|g#bX(o<$00nsg*!S33aGHMx(FL1IZKmm2(3;)8v<UYB+5=P6wsg zSniF&#fPt2L{XsG-fQTT_#$ivPp_t^(ahKd(Rh(8Ou|TmUnGJfHU<g0KoA^t>{BEh zq+0};_3dYnO)g&8rn2p~Esgh&5iy4}Tc`s#l(NQVP*B`-s(Tsgb%=E*x!`vNJk-`k z+fm(7Qcae_0=zlj<0~2F)s}a7tknTT`cdo_)g;9@CX6}Sx(tZ<L{_8e_IXE&8e26V z;CLS(t^T)iM*3Q*+_UBMm!L%|#-JZ)!8T?7qZ1fd)9%>-vBXh9eV`-C^l3uT_&kk_ zy!QGr?i9qmGaJ`03`VTK^)eYd43pD#6!NwJr0B=zjQz5pDVIxqPspfGxc527cKuN} zM+02tzw?((Ojfsh0mh)!EsE8yz$@B*zv5LC{@~DSWie_CKtd_%3$Mw8a()p(IDD|g zE`aGjSXm`BggX|S0Iz8=DQwWq7Y>nH=l2gF6&gHY9=4{U@)*&>a5Lg$i6r`O!H}dD zW;VLr?c@ISTZz-X^w-r)NsJz*7Ik*4Ly0i!Bq{Zd;rF?m8fkO1OM@>WW%j&Gv#v`$ zQmZ$kLeIBScr38Jb@l%c_PQ|;xB~H7qh?jaoofQxl!Mou$divTfpW_5t{jt5n6rPK z!vRqg8v?Nc`M^e6lM(@2!!NA&BnKun1vVjc1z9YJv06oEUF=G;UtEZ%aSas1z8-O2 z9BC#xzszD?1bF!myHOXw5=A=9o9-@Lhm!h0YZ-|@A8@Y(+_Z-DK5aN{$p1>cump2t zD5Y<$oDGvcGH&@I&=`_@&z9%lM_#_W8iyXJa<&`Ydn;~#brX*PwN-j%3h<fB>f05d z4E%>Bj9t_c-iGDTJ%p5oMe%gVzvc6bd`PTb9cQF~$q=bA787VjPi04Chi`i>W<+{G zV&FRA7KPur^W&w!IseMOaI{i>RU}bnWQwl$BQA-{N7}-t4=-KVk!vbXQ}zLtKK~Vb zh}Ni+HS~8TjiAhC5SP%}5)++t1N`_`^O*%;^P^`Rj#KY=<U1<4iRfgcC$Gn}AMb1M zN?s6PT##cH6iIlsJTd~6{wMa#z>G1%z*MAySF&MiUH~wJ&BDU^kXcQH6%9!xbzqRA z*C;FT!ttCmLLmGAVU95En90d_(qX5~%fa`pstx}K4cq`D|L4WUM|^?pXIDSM7j{_` z3G3~Fb+5YFcta__mAzP+vqYM1(W%@8)d!*dz-)tf@tMWp!rn*|T0x9DwQmg`{~HF^ z(&{06L_~x$VO)QgY!}xSiz9L|mX<F;xlthCD7a~1a@Gs3cyPn{grQxByg1GOXdc~g zC&tNHba*q4{u+aEh4(Vc$rrXWAwRiwf_2gno6<9!ufwpdCfLD}U<ho-u{69IiT5KA z8$Az5fb@wbUgN&CY#$^xNtXax7fm*Q|0*Y)gFOLDY4DfWRy#SN)58U?zu(EJo@?!k z`g~m&={E0ikHy-t=>(gredtzS?t3cy_RjmTIU(u5dB$Pw+b^CLxKo!Kal-ql57<b| z#z$iOz*q>+p#JJ3zg*_!Lh#CTQlhLZaSdUpir$y9?7cH^D{5SFz4E4#R}~cZf9Y7m zo;9Cm&MV)C>%p+!bv-*M+$WJVT;|<w-@zHzJ>RqRPchoQ_7BbK-|yWM-<~FecpFY< z*+V%yqBEN@TuW|VvPKxu;wzn6PE#vLx(^m2Npl0_=R`(f{eE#>@hhO=C}MNbxWW_v z>i*?56p5poIt)%$`T(F>Fbvwm_u72fIj{*&-QjYl(EG&}&x2XCp-|gm&6LNw(*^~r z(;e^7)q{$HCsydP(lnZ{CMFoZw`Di*O0teoyeuOUSTp1qVs*`Z9<21;EeAe2nsvN~ zRC6*s$3cgHx807}TdF!K-J0iGN^SO{w>QZ;&Y$k3Kg?6j$YHFGxQg*a{%}-aq4xqy z&jBywOH07(H!X%N)*9k*pouLg-u)|*fP*&bSExgq7b56vts%pZKc$!0Wz)kTr{n^c zH0~1dFP!u<3h8{HY$Lt50id%$jqN@8k8{VALlSz2UVh`a-#R#>zHXSNNR|{7e9pN> z7TX5KSq#wFmVO-1xo)>HN)vR#Rlnv;&}%R75X^KT9xE{?m|>iz_BH-9O;l0+ZPl<= zgateSH#Dy&8cL!Z-sT5hq(D<^FoqY@mUzl=C-x$<T+(cfwtvuiXjK|(NH0Xn9A|_8 zN@Q$ctLyk|VnTqJ<NKw#hx8ix=C`ZQ=y`SN17CnncVUIa8w(jE!LoMo8}(k9DHQHI z-g&fb4KwDTDdi1#zx9j#%q^`6*=ori8}VKF8$0S2b`R=}fw6)b=D-v}<oUJtcxAX^ z5yb{cj{=L1IfI0%x5~<*u#%4nyRE74AKhkNb*K1%B>j>?y7nvAexvXwZ#MsHgqBZp zatbN4V_H3K-L2vU@+EGATIm6Ap`GU7lnAV|6g`8C(61y*zDel%2}VNAy1~`blPHN= zu~bPszDZI<LbFNp<XK!85Ox6XIee9uyf^$d&821GmFd;!#5u!KAcJ}-GvLVn{Rtzt z4zjdT6ugS_{As}g_ErL5f<PA_xGS&hN1g8BpwToJRatyg9x>*Nw<W)=hPmW`YgJD` z=B+8j-?sG+Thqq_vo3^H8CG)Xn#qUaQ;fyaV0>!P&qvtzvpA@&tGdJu;DIn1jLdX; z)t`xZwPI`TdB?s+nt}J71mU}hawwEbPnX$OL8-5nO5zHu%kT?MIW=*XjkB-H;p1>i zcVuPz(G&BP?D09Rzm-PH5sJ;n5|jQEen*(AWy!9%8%FrobT2yz?d&1r2KSS&4>U<6 zI`!cdm9dC1Hqn|R>+xX&B?|~3hd5zh)13!mfVsLczdYF0Z^iL|oZ=M%0c8`h0j{;h z%1hkP*~06j7+rI@eA;#HV5_3yPVSKp^*V2eP_Sfgqg3u-*%?R0LP3RyTYh<}z$74T zm;u}KQ$iP(LarIp;*m~l_iNZU>-f~@+~!>SGMv8xF)qs2Y$b}ymmJp+*51+kk=cjL zmrRQpnwbhoGj^9~t(5N((?x;Acs$~9zAnWpC^CsfbL2PPH_JB*;3Rr>5>gypdKu}@ z_u^!zU-oM)A~Rv>w@^Qe=A>t8Iv^I5(_hL|C*0994Dztje1-tP3-Ei}#z%jPDdt{8 zyj~NQD-NaTJp#iw;$eW^b71W?UD@s5BzgyHwZ@1vXRIB(t^Jc6R_Dv)Hs|F8qoLtu zkC$6KPc3aY4^Z{pf-Y8+AhHwBfE}WYF<334Vo!l}AXb%trV`AC8!T6My>xRvk#pm3 zHHM+JX=1+RLngN;k-3IQ<#A5MJ7DB2=>^LqD<l_g_~$luZN9^63q#scdK0@f)9IOw zA&(zw%*8yaBSL&uLmjAs8KwkiSI6xl=341jC97;R1@1QVV~D(vZNyy8Xl&h?Y?;E! z9Z1Dl3|0IWE(K{uonkZ1LcQK)G$v8J8#|F7>b1%kc#Q5A6%d%>IN;UIK4n-`2>D{q z6jHM}#0~z-%3!K9@Y#+aN0N<0nV7!}Yjdma*li{=yZCa<F`-5NNS&=0#|ERXw{Gy_ zeoZGR<(IJJ^nA8%&J>;H1McT5{GWCXe?F`+{8IZy5lj<y+5J1!-z#B+u2;#MN>QQS zrTFrqEl5LQ6y%wNh;`4Sr5J9RFfaH9Na!?n-M<k|Af+EbiZ7QA?2xsPhD^qz1z5x* zO2?bs*rPyYgwJ%?SXv5v2bAex_t4(hJro?l(T((Jv!`eG90#&V04Z296VLz}5!%p= z^(GEIK6V+H*Gx1sQ-NMVFsf|%1QmoudyaMWuoK5xSjasUxi`JT<{9<3W^0G<T}b~E z`7*D)r(1~cq6nI2K(`WfW=CoL3(B|r*xoq&GdK<UP58`oRb~tO+q|^w^G@xp(RYjw z%T+~^DCV2*3+QV;IC_*m?!z(30jGX;JG913#sV23j!!DHsAG3$-@h??7KUB0F?)DT zL<*@-Ew>FD%$2Vk4(|tbc=g}P52_RgNSWcn3t)I333gCka0q_DoXC$EE|u?la)3Hi z^Oqsl%8F|h!W<CC1cZi|dVYNdge6i>fxtA3&}E0KOg)%}(*;8p7JP~oIr7x~qr5ZS zt}-eG#D;|kb-q_a=YwMke!SFlTUXIIIyhgBr@r1$`M=v573zGUZ&Z;ovB#T+9BM0n zr7D53GV;cMPnitw@6~l#XLgD-r1|n4y?bO!UcEc(qc7(MCKr0=6j!>Gfu7UOSM}Wr zrxrvQMB^yRGbu2{3OLrjP=6`>V`nK;{YAu2$`B8FPF$7gZq2ZawtwRV0kK!LeuHJz zBRuR2nG8L&T7&sF(BmF^9-`K%l-a6BxnQhEsSCcMv@ca`7C+N|8~^)`NY6R>9&v-F zrSt9am3)7()<FA2XNl4(@>aGkIp=6JF|$3I0`=vgS2}W>J>gIe0La)`lZ<Dt$gm|Z zcmtk}6gR;1VHh5K&H9jg^Mu1{S46hfy;3(K4aO|1iR)rdSd;@aWuSB9|J|<c9zMPs zQQ}@)X*RZjpDOe6J72Ol<6K(TDwoQ9YY<M;G6T1Cf=OeoVA$=yl*-788E><ruYO zrdKCMK3(HqvlZkq4EVz}e4!vKUZ*=zxyU!Vj_tL%aT4{w?AG%<67P#6akCSh6N>1P z{l;udc}QmIM(7D`(wZl?Lb}i=W9(rVd}caMm3YX@2^XEe7&6ov>SA_Ul!YAv^tDYe z*R}KK;n3W|(DgTksHFp3@6t-fBvNI)YrjgMY^JK*K9SzP<OUBT4KSew8yLe$5W*qA zp;CX{?+b-;vd0|07I6=L94UCseOgaTWXHY;oyh|qfO@U_$}@a42Kz*l1%^?a25)hR z(!!u($BZqmb4dbO!itc^ir)ZkvFR6f%i`1~9mCrC3g8!^_anuZrWSW1{>;OKf3rVT zZIRx%tWtOEFkX+LaNh*i3kxphn^$o6AR{?)Vf=48wJF#hmJAL{4=%^PHvR5{s~IP{ zw@K5SuH&}_b<P?45;M%vM|WKItmW$i*#LIx;T|TI!fog9o9dfmNLwz?_uk!f9oJU= zkASy<oJ+j~W?bIs{-`I_U!DofGwqhn%T{bbAZ;{ST6%B9(`nM!xcs5th-Scc*oqiR z(dpW%$L&&qjA#+NtQ?rD=3<1hUG|=)8qnT2wT2+I0raTkVTk&t#>#waDN@Dr*1#;8 zj3>L`zy2mj!ymgpko;mUZsF9%+di@q6&^JI&CNM|2-W!Zeqx=@JCWw~Na&^Xr+cBx zD~Z_rhQn8JeQezgl~_%EHY<}DHhMelQ2W>38M}*g^5Ct4+hNyYc-PQrKYdKg5LHHH z5W7c4sF^;~J5~Mpel;s1wg&NA+sZYw=yb=+oocgx@pdsA=k7k;S&^0Ye2PKV+jA=J z%kv8!s;L>%L)sb~z5JD`X-KkMJ5d1~ffCHpybzHPuu8Wkh9i;1AKMAU1s;ZClWgMl z9P`0tCm%NxKJ+&MOk+0dFd)syx<+DEDBOC1G?twC@TmJP@Pf+(*wj=;G#0iQZJ(iJ zhG-xA3G|5*R@}e@#7hh_*PQ0J_Ka#hcc~Q+8mb_($57A2Z^ikOt#!vf@PA|k3?1E5 z^UZ$&A+KqZAMh0`O@?fzgWeM%dCVoQ%|~*CFOh+?GLu=z8cs0Doi&=R*WpzS47aux zHba&$jRt-gFb4(L@D#uGjmM|c$++VCtQCqFUas=KKW6lql}beIi}Ay+xI^LtKc@0l zdkQ#o-z()ZN*r?{x*<<JW4l}CpTW9Q_N*te=v;@R3~~W9{yt=@HH}X+|9pnlXLxLz z)^z<1tVpW9e>KqloOm<s7_-#Oz@ZD~a284&Nu$B&TjMIZ{LN9)-+<N8;u)c65uo%b zUIOy^2D{EDp2^ktTwcMcCa!aMb5@-&$^M8T%-C^BXwR=?{gZt#86BQpyv$g5GEk7n z^ti?x8Kb-AY2T+m+kB|Wy0%u{Ip5gx`9O)vPjjB4$p|ox*}0N2OJM$NSj8>bT5w&V zwbjn3a$Q(Enfrp$2j4p_eha~MoJ&}&iUWxSZ!8q_P97wWkI`RGWaL1RonK|Uak^P; z{w86F#atZuy~}Jq{ejU<W@f?ZQ9AnNRoM|10M`+?c;7@y?Yd#8W_(ZS;3zI8sla(L z5Y1sqI2Hf+I+b-4RHIg)bq*%?OlHs?+HaANHc)#etx)3C-BRPX4S5~|gZhYGh(ZFu zHj&U_G|CAMuwW#Q;G<Y;^tte;A3J-9I0qfdJ(*;megylO=I3B-bnzlErBveR_4sIb zYki7~$Fyu&wS3BcZdi6}>dkdpr)fS;-)D&h^{m;kRv&q0P&gY>_Wn_t;WSnIeQ`eb z%#)mE*~XX(4i>^EwvF2`&wtc>49nS`qmL5rVz_@uPo?s)>dW#p*sb5eNQ$qmB5fE7 zIKEk*|9H&Y!}-D<?r#-H;rn-P>4T&BI9rH|YQxZHIugY!WQFWiyQn?n9k3;PL8)U< z#A$~V3iae6z(8e(o%*Jz6x-yjLA3G>j@cDD{8TQFa@~$UQzl;@bJcoH%=3~W6|DQs z<e{K1lyude^*(aF;ojwvJEwmPp{rB@?BY+HmT_vDjz#dxh$p$yG$M+(=&LYn?J*Up z_-N)AJ0hc2Hah+{n4KeggFlt{?eo-9eOmIL)Za1k<3<QF;s{f3a=BvZZ%PTPXrQ?E zcGdA2vv7vk(gf1jyABAdI<Y)|>(HWs+Dv4k7d(U{^^k~iOA&FEyEHm?ov{QGSJr>~ zNBu!tDZKyZ{}g5cj*I*BSypu7bHuIB>1sJ{JNP717@@1r>7Y4r23)bUfoFRm^)9*) zCp9u|gQ?d{lA>+D7QCSr-=sytp!RCmlefdPbI3o?<*$WGQBXkp!Cmif{c*L*AGg&b z?7DWdx+ZbqK6&wh=w7UbYfJvH%6U0zyA-;}t7CBq?(%dq3th6bFl7)PLYI4xVL;II zyHxo?4$HrM`P6?8Tvl|24X-t54n_i-h0-n0Sl27fDZZL8HpAEcQr6*yVHCb~N7E27 zmK=cCh>pD6WTW;ikgkvgiM7ROCf}QC3cT(BH$oGu-0t^8PgZ6MX?z=8Lz0ne4T4^V z-thAcyiPMh&#zu3J_ES$FBkO~$SuMt-s!u@48@57H?*$e8Pwbi2Yrp3CQGtR8@!yj zUk8<?1<K6e*y=Nk6->vkyy#dDr0sf^D6wod7j5Ylf6w`wCmvcUyN^|w?dyUD_KL31 zE~V1>J!2e)z`E#xwN&7d0=DYa2DB6pQ4$wj;@8aSM@4AZA{vjr3qxAHqrY=7T1`94 z_r7;6x{PXo9hdnJ!N8{tBM9uaKE8=KN-T_n=P(rOra}Vi)`j2v%gIZ{7+g3|lAtj* zB}}a4stt3~a*NENyqPR5c(%njgkzR6v4J&RA53RN_zXRj1VRWa@ng<k!Qa@m6fFa` zYzyZkjpB6J>nMMCvLZvQ@+s}}=U?P|DLxeem<(Nuv7p63NlkA7!CE10D3wO$!ANw9 zObXX`YL=R6%2TeGd1?xrLK$VEwP`qN7HPlo`MM}dK3I_H9Mzu;W}$)%JINEGUpF90 z<gvB7E(zrOZxcP#6{UX~`yp&i;NQ9R%e4utineLnt8bPaovVl{U<?4W^;QtD0q6x4 zi@>#}mTOLB17SWhL}ZMRGTaFgmU`2O4g(>;@kprlF*Cp)kpy38(i>~14$R3s?6^?3 z(HgVQFov4jM7QWqadph`*vm$aIIXJNNcy|m2$G|ntBgb!GwWC48iMztD|o=(>;15q z{$%3Oyvm9@O`4JoB64cJ6IF%XU*;BiuoJW(Z#j^UH$l#9HR{Mm7GhSUp-f9TbS(>+ z=TBhELjbeJW#KE%-tr3Zh`nd{*Z|1O0F`(MTCf5%G2HfRAaIr0SmvO)Tb5xAR`)IS zDJQ*_aT_PknaBS3@{3I7may&O+zm8(y_ea0+%G2M5N-*A7TFy3Ev_pPhhj93^hy2p zsf~STscg0VHv6)-suJJ_HvfhYQrC_Zn#OPKnOTJx<X2^otW&`+!NnGf3aSt3yp|54 z+yQPf*!ss2Q(Kpt?XAz_dj6}O?~?T=!sj^5(-A(8x4!Bf+V_L6PhXv<jB3ax*7njB z(ZN)fN?(@hO&2KRV~x^%E70YK<#LQLS3d(0I9eOJyQ1uyeG@@(Wb^n;QV}xx?EYO- zdy9$(39dUI3(6v&26xINoAl#VyOx&L3aF5W2yuk1Xqz-X9i2;xi(gqo)d?+79qn>| zt$bef1E2v24uA^CoX;uvbNr#<^;$Bn%#1V#=IB2G9-e7<Y@mLs%DwUC)-Hx+BO`{b zhM$L)vLPrd>lqg49ji0~i?uStqONO;%fa+^ReCL3RZjio@nXo^g1nNPbwp1HNQV$> z1@gTfZyF)87$l6~%5yxJnEQ+ie9+G%;f-}&?6HbOe(kPIzzE$iqX`vfok4&ai`W-d zwC99WD{QBt=6MXVD;D962#XX?i!3ihIshIg{q>fXgAMys=@kLkS%9d+mfwd@#_C~~ zWK@5#ngAyP8WOs%@7M-tVjQG={`OIT#6O?~USMV}Aqz>h#^!wFb!x$Ak5eY`gw_Il z+T)(XzI$10nIxlz0YQ2v4bhDugbSQ_y@s>>rHp1+Svi2@-tSsqlpIzzPTyUJ4&6Wg z8t%*#w>(z0UiMXQELXctsZ9~k5wCOwHVp$8E;=11PHAtA3;??YDwCu|jO0#YA&u$Y zH5r8Whl=eb)AhDqcB?eTs5~8M?tF{1{8~NvkvAAqv1XpE@W8WAi4NlSL<2eyn*gM< z`9H|9_I|T^m{J0!3b3`LzciFAtd2LRu7s*s_Jsb0!7S+S7aJc*lt;`*gA-fKO8ArY zhA?VR7)jaRX;6nU@n|8Tf?%{mBM3tZ{xr8|dm^KZpSP}F*K>^y1+c#*N_x*PnQV4j zHXXs6C)_oV)=7T8wRg}#7y$*Oxzi|WxACj3t`$g+Hqob;^h}z0MYNO*)*)W%TP2K^ z8+E9AzoFgl+*G|4FIloWVp$TG!&6mGHAR&+;NTh5J^p6y6{5nltCkJrWQ|oU6qW*h zPfOY$qZTp;a(A%n4fddVdJyiB=7!MR^#1%L6Aw9d{;jcxYG!qJqe2pMrVyVhg_AWH zCaVB55F%KKa5^A)lmMTPG=x(hh32&U*SA$xDMyd3{ZPxizi!QSz5K)*82;WGBaTay zHDeWU8ME{rnLTO@q8U-xW(Oe4ST5z)w)yoW?X}$W+<N7V69>~i-yIXAq7T_olt03# zG2Gu}eml^<1&ha=qIj=`nCg>Wm_0+Cwd6oS*LRkQkSgAw;gvpLKW`3noP`D1=r5(` zPz>bAt@<5_%*bgTP#IghY!XJ=NFJ98zDt@(K^*}B$ts!PZjYpvq%tq5kYKLcJ@r)h zpjGeWgspjG<GafDL_GP^8o5K}%PZ<VzL7lT5HNT1e$4Cl)*p6*!d+KArn*qU&~5?< z=13dW+N(1QRo+4<sP69GTD|<}p1FF83s<#E<LG!Ncw!3Yh<M|eOrXGqtYl$!`uRHo zz|PwfS$tzTC9KQlG}_)o;2jyN7L+2h{pBIsO2B3y2#z@^!j#!`va-UfgP7FS5lX6| zkTc4APIj4o;nQ_e$$Q@60kkMgThl2KUwA;KtM83s;LumjuG=zc0Q1I@+Gq_Ckvy(& zZ*)V(e(an?7r9!aT2>$}U5I3;E(wFu-T*ttBj99nkVSJy04B*>3M>M=4CJBW{W+wr zmo8Lbm?dVE#ijL><;n9dCt|#Od|9HFF4#}Y<2rV})IKejs~q4`MWlQNc41Kjp$r;F zAUY8dDHmc{hLF%=Kik+j1W{WEZP4aaE0T_9G2k3)50J+n4@!F~;6Mm#3~zA2!(uNW zD?3~9!k5Ez<bEJKo|shg=HV_MzmL2RhEsG=wqr%^(7TYkCpz}~z1~}mY0ilUA<weS z)oL-t+Op{}(shbk+iI?PS$EjzuRODJ-<wi~q__QZ411Qnz|CwinBwX@hTW%a2)?WC zIbFu*zA5@EHzSgLi{%}#LSZt;N*lTsfT(My2Pv30h+)9h?|TVl4Q7f|Q08qJuo2uX zl$ta^3L?dsNd@N^YyvEN6wH!xF1;5SN~1iS2ue=X9E!fnhmiRJu8*<Z$wxJX?vPlx zqO@;G`k7HShV_drXXjA=3ilc@ZC*#bB@T<vQI!MZ1kbX=INO5Yk7P$ZeKyvH`!X8T zI6=(PDN{2mwv7!!Xy^%QXCKLnw^$0*e)3fE(~C^T65d&ZX7Hp`$;j0u970B>u$*P; z0Z-5cF&^e2ZT=G7;H2(U6=DL_gI^{}SNj?dg8|^Sxt0p`cq^jwVM;7!Xjm8d4}Ns& zKcd#kpeC&YrVPU?^63<(P>{Ui+6jp;gFDhm^1pecu3C8b+kR_Tdy{IMWKB?1fmzJA zRrWbi2iAWJf`OWX5*Mgp>n7+MnqV+8M&DPEmPa?H%ZJ7^zBIqoh9?*U3kCchz3T<( z{o=DphBZPs)&O&+xL<}PTrSUw@BBJF-j`J7B@go*T)LO-j{0ZZpPSq}+fSEg4@}1L zZ8|B8jgb2gyHh2Popw{~EdhN#pk1m(0#ygca8F4f!i2@Brzr~+t!U)sEME!yD(7c} zH<p^y$`^Do%eXFLgQ>IM`C5Sn4OHuPfASSw^KEK{5G&ZKT-udhQ|yIrv`02n2nEE6 zJaaj=cYtkxDp%*vn;v7!mw#(ERHUI8&%?XwWWwd<KpDk(zORy8V*vJGdJ4n9x6cKw zfd*LCF)T_bQsEZ^g)LOAC_~c&_(PViw7@Nx3OEp{ey=;vVhe)=`~fkT72CG2q9Dcy z8L~9Qav?TpXuW14gRE?o5^+S7io#dEAR}0`65pC{WVViSDYVM%n&<QLfgr;B6o)rv zTIb6}hLPs7#OGq}s~%}B#cV9lGRx);Rdk6gx7t&ilp$ilgyv0LB@Cu9KvHdOt8WNU zRKE)Jmffi^kZ1~E;OK3djWI^Fpjc~Zw8H9AKhg7Hm~#E+7sc04Yv@z#YVE2vr`%0h z0#-i0Nt+D*ywDBSwdR0Zq`4t^JgxPfRRm83TuXWye4%JX;j%9Ar})cG729R5bu8e# zyFXy9Sgt5k3m1GHQhvrqBSebv3B8uXLOW`nQDR5wndp=soDn~pnVZ*3Y=R5Minq-= ze;L<YU;KHO@o%%GB!`p^tto`v-d)0h^XuIi{>^?J-?@A*9kw-cvd2{8XJT$}8H$!5 z(CR70IjoaC>DD~Sdvbq8(GW$Ab&QVq<a+b~w99k=9&}6LFT3*KMEP01Q?{#*n~r?C zvt-+rN33S#(1B3y<PPt=Wu3o8HQ=_wp9MW85HGf%H?)vfFc0`js*U>s>5qM-s&(pM zPqqe9RFj;kYc-8w?^V+V%7{u54k`7Ve?+hh+r~`oRnKXVB3p_X{b-SP*}HtZ{G!PA zYJH&DPN4_-LI0Qq?XoMhMUDvc#~1H5z9hRdmx!A;m8^?6m~Y-#b1hlP<)Eq8U>?U? zbrG~tojEl{f3~|C?x{5NaaOUOJ;yJ2hOz;`4;z|OgBGHrpdB>_F3<8WI*%OHZMd3j zy2oRMzZ)xk)fy^F3L0R20hg0paZ$rdG{I|!)H%|BW%n4OCnFJO{@5hlKEt@{ZF)bo zm3&_P62l@ToZ9vsZl7rqgY|j&J=M}0aCXo$QWJ`uVjhB(*uS+H^UDM}9<dRkDnlc* znAM;mGTO}Ao1UY|3y&UBgw?_ap9soX+%OBoMMb88N+Y<dHS*nr(I!;0QO8(LisB$V z<!{@?<-<+;>(ER4+JpW&Q9Bny4m*?YQ~L|5@IZr?xwVdan$7a%9{gv7nROdai@`14 zG+-^|Z})4_OtE~I#aE~AS0(LCtNXU(!?C{8pLWYD$$@TV2HsDljoVJZ)B}69$9)?5 ziNy=R_Yv5a^;<rYaG7BE09?Qz657Ti2c;I2FS5a)kV2poDVF{gnp}ioiqH@FhH&lo zNh7nE#KPz(LINNl@EqXFJCTKeE`|_&iDZq5N7~ZwLyi}YDdrNHX}?ShK>THLpxNLO zy{q2MTR&jkfAcY;d3}8rjNG3Cyi-4GYlGzJkoOXtWoKd{@;N{&Tdn@M?Y}BW7UX`* zGLMt1)|BC45~;O<iG{uDYNd+R7zlyRioO0-GzLFjJh!_*Fra|clo*|^suLEj*rJ!F zkIi$_N71d5nHQ`UZc+L*F}t3Z*Ccwat;B|pP|`48_exav-A};rgp-YxJ}bS&pN)<> zYEbYSZ2{~+yv)QlkAVg?M_pjZ-!GCpjqn>zMaydQ%*lyE0`=2E_1o>1!sJ380i_My zB})!KN8vNL^sR*WbvXhjt`v!TIljZl+nd*r_Ksa?e3=XQf1O-aR2;mzg<{2Bixzj6 z!AsHN?hb=%ahKw5#bL1GFgQgEgBN$VL0hCa#pd##a~|%x_wD3M@@21Y<s~o4TG@Li zKvvuZRmC`t6i7fS^4={cls_z;u{+2QrjY^QMeFKzNuY5V$E^Or1}_&O4u*=0RhIMj zPfa1o)WSIp2R)SrIdRH~T%FOUx*gJk@uA7DqTX{|<N+71#BcK$WWROSv$&%-U8mg! z`C`id2GkcYkNkAQK`V~WxR)I#9w_!s5*&xmjKSJ1QZ`librtCu7f&f5*2so$+#Bf2 z4e;JKW4ueQbeXAH-j0<r^!2__bXa}kZ)_3OroSCU^l}_?!>V9+3{YvzBcTXYf<5#f zw@nazWj_=%=H(>O2QSy@P=u8`{8`_bk}x;!P%>I-jlqoScuG}=Yua=oBl+#ICF~F+ znS@$6yzx^4vw5R$n+4Gep@PYrOxf{U!b#0SW0W|~0Cd`pg<Rvo4*OxzaYeP0>H+d9 z<CT0ieN&>HF2Y}rq%oV6;IeW|n{J_U0dOcSD`AWh!D^dDYCb*c8^ladlx6e8v=7}U zpGCJ-DErivDK7O9PLYZ!KW$fh`Bl7Ghke)_A2^fB_mP3$@dtVOu4PdD;J9^%pt#r7 z9aUCSF@MAA8f69~*msmp;gomRMsbEyIuir9mRT;mS7@#2U>)4Yq%WOoTL5&hULy8K z>kDnMX|3fn-RNuw(0Sen*8dtIY+Cz>5U7I^6VXeO{2jLdd$q><>Xl&1Vu0p7fs&1| z$PbIJ`zdYzEI~m!7&#%G%tX&h5*}N*sl~^UqaR>nhk<lr{hTHXZ>NBS8AZM}wh=ZX zrjv;)`|w%_y2#qZAId_YsddV+wJ2*du<$W+5t&FUFZk{rEi3ntr&SUnt|%1C=Jd5_ ze_<yanX6@z147LHKx@j@TnwK7aynuRYD8{a33Sf1D$a1HOjlmEEBTsOo+Yh^|Ko^% z#z20MgXKL|1u#y|Zpseh+BP9sNZlb;3yv@~@Ov0{>CF4u9zeMdmT+erqTwwyjqRMS zXmyK_a6D!#O9m>R+q5u*q)F~4F&iq;iKuj7YDjg=gR!K0M@3p&cI+#a>do7bc+EFf zp}{hAArKj;X%SHZ6D9Rz4`|SSmahv#VAGy11cXaX)Mt;d8M1&}1|-hAvZVNiXA6o< z6cfy5!JL;QBlt}Ru*oAMLs~|FY5`ga72TPzIc9tZFpU~37kdem-*}k9(J*PIpJJ^J zsSU)i+YsOesy~Wy%t%w6zMqz(_qC;@@v>^vIJuyqXhxU}irkNHR{VlcZHy_J-_{`! z{(i{Z^`o?+;-T}NH3_eik^=@7nJ{&KH>NC>I8$+d06Es1h|Pqo^o{1;)^}_EW(|57 zyJj+53*y)m6e5F~AR#?Ia_O;t0+cCf@_;lqd9@>cWM%$cNkbgsDZ7Cp`OsmBv5a<U zjh^{aGIUo4i-y!0T=1g3w9$iB8CV261F0G%lg>=TQADA0^??l-fO1^j=fqzmv>$Ik zsF<+b%&B*pk!HX9Wifnau{En>S<+**we#g+tIq++C!fFshl@IZ%_AS&j%yNkj=w#j zV1zL4>BCBv?8m!_A8vU5w_+jRJAUa*K$Sh=>u;o)@%gZm(Hl#>>H9yA=VD<p@r1Rd z>eWW`zerl}&-1icy~%Cs2WRZT1JiK;)SUZQ>Vwq?HIZ#4y{7%`Ht@uU9-2mT?U8mz zC94OXy-c}dfYYZ@TnK!7OnYwUnU#=S)k-Tj1Py{Y_*g>!$igUn_8Hg?Yd`YAZ|<hh zk~N=8h?1_pr*6E4d9TU>zO)ET;+xY)CD|&4M8hSGJ5rwlLozN)`xJkphmTWhnkH7R zp|GN?8<bnBp;)ahkVscbCR7;QM!t_lE8kzXl={MGio#(UZs0#}ScXhYD&vDw7yAHy z;1Wl6l%nBSxH3Wb;2jNP!5@sLiaK}~M&FPvTgpw^zf?p2F<tcN!h2T<sXv6B_`}ck zq|uwu9pKSt;s+j3OlaNU+o2^T9))uOl5t=Y1ZbT<U@kEFYicx8UxzC<pXepzVaI}) z)n{JDWYpe$bp>6tSl;KdX2OoQGhRYBxMNYX@MpSn5D7F}DSPf1*q`Ib#*a4Jg@qHh z`7qyVkKaMCcRemWNY651aHvi)D<vKqkvwl1p<meSi&(~-=)zFH@IDQaI7VtC`hZoZ zq;&+xoxe4EbjNODw&HE8CRyV6QCTwD&RXY{f_q#{hWG;yvo%}$YL8BRA0h1o5KK*O zXD3rjd>t;N!*0nRH%gv3csv7=?{>O*|2rMzztJ4FC53iHh~I24S*ZN8u3B45qTO2k zV#a%<aCGQ#Wan|7k?*UJ|IW?bBFS}!^|`1$gTuL|(_JODa-|cXMJH)anre2(uEuqy z${k#Ws8<}?5mj|d-F)cVG`Qp8-~37TJ8B|MiCI&p^uZT?;hIgoU1@FM%YA>2-hio? zIFEIohf8EYWRDv0QIK6XdRv9JD+t>+-4?eH^&08HLs(EaIj}>ufdPG-&FK`ox(hP) zSX*Zqbos^?mzT7`kU=2R(_sFto#;e1-jS!3{wMk2OMcoJ>~6zIk%mvT-Jh7Kvbt$B z8|rO?J^g2Xr^H3M{Vu`P<)l*|Vr*E1X<+$j`p8kgt6ScMbN952xjmdzc;`Uu<QHf4 zl~+TX!1`0?ucVcQ&IRAQq=}Km!mS9OlBq@0VWTPwxEavR`#bgV!0ScvE>BmU19zH1 zdQm<7)we%}!ruutZS5wmd;bx?EJ416t*z8Mi{3Jr!!9It;_W3U$&c}W?2NupfPAbz zaEvS>tF=;!K5Ao~-wL{`AaKW`2vX9W!v);+3<v!_qH4;)NV~`;e`*3LWP>Ne%UcVx zb;L=lm)%rYtA=x^cwa@f^IsmG_fHBMF!yLCJ+BFOHR>7stJd)?=Nxz%<lP`F<7F6i zl(Ho9v=s6I2a&Xf0<qVjc%moSjV*_;&?jyU+`ZB>8iP-Ve6eSZD~t{%G|HvhpWj*; za3=~ov&HyCmD2vW$N+mUE$10$G3&6M?QY&iR^o`>Vh|lw=YCxOOE?w`X@(U<9Y7~6 z)Fcq!<`YOUk`P*#e17Azvnu6Onjf2;iYsll!t!`CbngkGOAaC^m4^RW((d+S-n)L~ zTM!mauKzQ?74*h_S1<vmr>@6)A_2|}RmHj8#A&~vV*Vg@W*Y<^Q_2%(ZD@hdlKyCe zl)xetJ8!pZ#}qf;Cj>*iNq*>30qx?euIoKYV8uSrbVuX;KB~UnQ#KvGL+w`BNcSS1 z;U~2{1T}vKDOh?GjZqA^@8P+OEsh={qVYmQ$vY&4jYp=IpNGGesr;aBWx6o41JoSQ z(}BH4cv2?sB~?BFm6;E1bvk7aC#n*P%Oi?dG5L^1-hlm5(P&r2+cnG+!{_XV`;L8< zl|p)Pedy^d3gl4Zq{eg%;hsN&<yB-qP%*JDx-dYQv_c*-)yQp|O~sa@A@qd80>VW1 z*YjjpggMwY-|~3Adr8jW^cl@Ov{4xMvHHP;dHlW{U@^uuI}B#!zEBT+oebadmu;(T zo?I5REG^zcKLB?tC^&z^j$_l$2Lu>djULQa(#{(k8C0@jcH@Y5plQC>XSdZR<%2Fn zC1CnY9?x1zI@i<LQ@m?QRaFCg8bH71r7>^uFuX5uMtLaq!#%??TkQR2I!ifI;x}j8 zfr`BP^Q6sA8vDu}yITqBe`9jn(s4p+U@XAi4YXGwT!~ej6K_%!Fo)U1FJx5?IX7s? znI|z&$~=$$T+LNGw@LY9(K6|S?R%;K9(2@!slJPxmJQWG-*CpPI!DGkfnTM3=U`@k zo*N7*koGrw`pli4^pJpjgSMLFVm&}>!aSM4cPn7hzsL14QkK>UK(EW*q=T~B>6G2r z3kc0PU=Gmf_i1!^$IwY;XsZc*z39uQZd1T0?3v{XK|jR#Tw@inoudHrzw!~8x`ZUL zP>9mhb4GJ95$7l35USY0dK*R}JR4u>ysHdTTaV{r`q%*N4gv7}Dp8PMMD8}ve;U>< zz?5tAj*Jp><IN%YdB8@cm3jxX9*mppISr~d;tk2{_{IB?(_%J4+iwPWLW7@J_VAYL zzdJ+ZteN4DN{i_VlbhK-Ppe=T&+r+1hx5qxl(|W?sBMQw=h7sewyaRI({(_eSk4<; z`Bh}Gu})Q+7wA<cBygT$NEPbl#?A3U^Fk9K3l<q4HRljayEgA*#Nkrbh%gU3hN$em zPucOG6oHlBnNr1wzDFxK_wh3}^r95;j<fX$*qk{H%6beur0}K?J%93#EZ#HsUUlmX zCvMC0cRVC&7=A1sW)c_WZlhXii{CUwErjM2`T8?jf1<sH=Tx>e1)7Dm#5|^+uIQ)R zX62|+|J^j_h#O};zES66?fadp5IKr-?2tmw=@pHfATcp)iM6Rfhw?q^hF;g%B>Ngy zio;8u$*OB7`R;LZ8jGhZ+?gbNu(sYs<hh|bmbY{K;N*kL<Od%8%}u=IF69X#MV;qL z+QUIFpOZ9=kfclQW6E9_B{Om^e5D0i-uxVg%-U+Pj$+`81*I#9GMEux<W9CsnlD1k zn7%enEHH*A&~I37UC<en1fA}f)b*k$QY{?{{&i4%_PJsMq9n4~{0rC1CGnHUPnuuK ziw|0M=%KfWDSpsigScFy!0PBq<YuYpAc7l;3G(_fS1<}+T`>cLxZ<bt%BXGvu)SmG znX2o;X+a%wa9G7({6BvKi{r!*K=hl7MV_>v$G)#thMhWlfXW2Q$W_rJ(Q!NDXH0+x zQ<!jQ;88~H34Bc(d2W+-QGOZ|#FCQ*l>3s->rPUy=JY3Vfy|$uMz(uPW}@g0hNlv$ z8ijAn!zVyZm6Y}Z3dOh3D#DU@xDFGReL@V#ku=QZMao^QT&DAIy!9<RP@~8U+%)@q zVkwJ4LLwV=RLDq9_{*r$_FzdGgK3W-h=qmW$65GyKEm5=t>xSy^UP-`SW&!tYS7JG zFuK6m-6-0VSp-+>X2;maXQ{4IlvcA2;7P8*nSegnv|P;nf$F9NvbhM?*;a6o)S^Gb z(#qjN-*PB$lw~&sFU;|DeLP1Jbw(%3@f$Qif%2~O;`X-ZWzTE(*kP+j%s0<2)Gc{o zZK-afhs+SDT!8Ina4zgiAp9*+$_7H7)cTEKJW8+e^gJKxMz$6cypGY^89fs|HazKi z9n3p~+HR|@$_yMOa9sUnF;{1K)uoFj5JlS{O;LE*{bHusUdI3Tf@H8^QTqikAog%~ zKpdW@gb&u4i17=8{|9yEsYL~NCnUb3#Jq@Qp#7zhik~?7U0OP-<_c7yiHiuw$`g5h z4Dk+W4~Sojj=p;}luTuL6Lg+6F>9i|YRt#X8cuo(eUrk>Z>~;aJ7ZEaCnWA`MdBc) zf<hNND~}u*o2Xd)Iri|0H9swb`LbSWn2cDSh0gA+o%>cc&Z3TO&v%@gFl5^ijq;B^ zvz8RN(2l6Y91W9g(>MrZChD2F_&#rCv~!<f45JT6M}OHkUN^WVXTJV^{V`r3C9l0( zr3a_1_2aelWao5ys`qZW$Sl%_pU=?0-NJS3ApDa`^LG;=z>t_Y<!og5^sFzg=y_9L z4Q*po6iL{|iHL<GG9-zr)%V!Mm$b;e2U>mXK2dn;Sfp`KiR*b4t{fjQf3Q%`r#62E zj5SJx>6Fh)rVp`o2&;!MR!DuBI_q1wKrBVwev-|v@UfT;AjKp)rCR(I^k*jgDeg(( zdIc?W4ny#lvCc_WrNwMjR|zJNNMLrso)T%|FFxc4pSXieYJ+Job9`0RJB;*H!b0G7 zyjcJul}ATXgRQD@Yuqc@Nx`3oT8^GKT7Y2wB1^J~i?05JS~|{5gv0O!nY8;jhq0iY zVPoNDo!<0;UZgQ{97H7O8$7r_f}$GyC*2ad(Cb5O_SsS6e2xlbCFI@169mKacNBKf zncO?#D0m>Z?KHU#0TyrHUQLXd?I=E6L`*<Nz{R)&V^|S@lZo6^n-eRj%x7Xwle&*T z{OEfJad==KTsS)DNLC@yY)&opBP2c#6`1|dhksAi^QACjV`HPU^3JTXqh9CSkNrs{ zbPLk~3wrTjRiiX&jsE@#R3YeFEL7@&5r7AT7_SxXaO&}Oqo1dq8G3{QL|mVl`#1}H z_i1Y&T}N+jC4;*6F4;S%YhEfkbFCo6Y?pEdlkbFYnuatv{P#X>jy4f<!LT_BWAOgt zr)Xy7YV-ipR2A)=&_(wBiYbX3c_o_X$Mw*=00Y!`>(hrAVIealGr`&NqObgCPsaV$ z8;05!V_^4BID!xGSMV_+$cnGE^*&HvV`wNmYWa_4B{2+)8oakTZumHz++1AiUv>v2 z#nF>*L#C+#6)*VlrjjSHLTcbM41+%nJ9?1D{^dNxjG)t8k0`ncWIu@OM^XynqfH0G z=WwG`Md9|NH0e)Y7u}<yL}vTGQ5YwnxeaDb))}a~gE>|NWi1mh^%BJSW&Nd4yG7L! zA@u}#ogp?Nh4ArWVO%kyr}loh$H1|nzQ_RWz(EfYHvCCq4=quN)z(Gd%sNZ1qRFGv z^hc><PfVFevc;BWBCr&^9Z-@SM<cY6>BnG`qrT+|>4Uw)fXDcX!5DHZN5M4o<qhsO zLzdMCJX{+|BxW;wB<dR2XEhr6LzpT|0)C$bUW2SI;Ggp{n-1&ei=@A&E`cvWv4pck zhq4TPj)!H9X92nL&HaXJASaNgh_Yz@h=e5Nn2Cr}+)nIA<Xd8LO(9Gne4%nzH@EMu zp03?cENH=x=lJ178-#ic7t(VUan>Hh9*!Q7CqcvjL}A1_)JxPVR25u2+)p?i^lS|4 zjQzB!bd8Ey${wkDsmttcR2Kpl#CSw_%6N}-o^&?yFDaL)RVk|sp31*snxmUTn+rX1 zuLX`#W=*Z`t%|L_j&!B*r;5=rQZLcp$!;nKg+9Uml|yqxGeC1j^F_la5N8H5Q>wdb z2p1WZcd5uoTc?ikYU3_oEdZ)=wYDl{Dm^PsHT{bw%L~eaR3K8cGL})_vJVJrMQa6D zNmp~5gOA&f#-}&RAC)+jT~aqW16dJJ!<{1SBRwNC<AvhANEk^}xl(xat;Q^JfE`mx z<7`8Yaez$Uu)kzi5=8JshHUg~v~1=2CJm|J*e3g?4q&aNu|?q2P#**2Ah9;?6iozP z1iMqr>-+@s#0J0xpc8U*({ev?ecGPiyM}y+{LPI^Pz?Ji3a8#5efn?b(KWc-fBU|^ znzO>c4x)cqC;rQm)MvF;V?w20k|d9a4=;gCLFjI~FAkIXegCKr4lG7?rbLS=Ln@|L z3$L)>=Fje6xLl#+7Nq=-S)MTw-AEsaotO9R?|`NzO}OzLB(ed{M5IYv+ZmE2)-yjn z2;LdNB6l201nn}Usb78XPvsv(=a!oOv=Mt%G*z0SZdP*I7d0QUxQDKO-T~4G=ztAc z@B5-Vu`Zg*ttfNbRp&NiZ?^jV+^<Um45H05gZ$*n6|^Cta*2GY^5zj0{cXrzuAxLr z#+M=kVOt@iW5`D0L&;&B-r9BAbrh4CR?Zg(hfGD$P6d9^2;^zHrC;O7qCN)ZiplM* zwVTW2rCQi%_%UyPDbHNdC8@sAwDXnz-G&vP(xd5%U3e~*-3KmDoj*G5srKYS&`aGS z^~lnL8cC*AVcMgqBxt+2N5tgnWzY_<&*{OS?8Cv87Yl0Q44uY7`vQR?V=Yrvk`uwu z^y5aU!(uWFo)z8f+vl?Elo8&ju5q3zHlA>p<pFxaXmrFs9<NRd+DqxyaI!lqA!eZ) z8?~Q%uNIfzUaf3wyon8AV)62RZRXzI!=V!Wg`oS1+wr?S6J7_P#8e-@gRrG=$<!9Q zu*@N>KthCKh^v*imA8R6#*MAthXKqK*C3<_ro+!3&|sV3VO#qfx35<~sF#wVm#wXr zv7ndFub0-Mm+PsQd81c|xtyG^oTa>+{`$UVUrwz(!b9^**P7>RzFx_3TK;;vTtKm$ zGI}yV@QugpOa4lP@k+wRO1RicT=z;;;7ZanAOryr9S->N5fBdngwX<GO8}9UfJ7)D z6dw>{r(}c7_!*5CkfA>g#46{`oCAdW=8fv-O$1Et7)?S0IJTuYb}cw|G&rE{b=#ln zcJ1qS4C<hM&fBuiyFlk19cQT5*|y5ruJhTB$r&_=a{B}2t~uq7IwjPtU|XSJ*REhk zzX0lMvMpn>Yi+WlZDI*ue}(LFN#t^cb$&^Ceg#i;iA!~bT6jrXc!gwoNoab7xphgg zb%h{ti7#=5-h273_iFgwj`wgXy8!hHIC13FsTn2m{qdX#eajU}<UGZ`F;=@V<h0Qv z;@dtr;#!^J7Vi7mCaI@F_FKI3sd<8_eMbourB6&~Cdum*g)JJey@P;F<#P|pt$Y2u zv|ucA;JmeX?e$>YW!4kITQvWO?tT;Vf8g(x{~xTU8MmMO%erSx?CP6!SO0-5{u$k4 zCf4<hx+~Qu+W&&9CQjw8nroG(^IrBME%~b|mgN^F3Ee{`mh}xw%MK^}w`Bgc-HRp; z^({-Q4yP@*2LFOvCjUEvm*dV#9*@K!R9pSE>#NV_{<R`qa@SPPa<G};|2}QV-OU7g zQ2n1&-dYYjl6XjZDfw>_?ECrJF}4UgOzZ`I+?ZFg9Uc||hEIS~1iw|&Yk-GO)NhbQ mX4Rts<LE1b2{c|8A^H?xWL6_ReJ}y*KfbXV2YPjIaQ_1m_8C<G literal 0 HcmV?d00001 From 26b6180f5047e965383553177cd5cd7938bbe63e Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 5 Nov 2014 10:28:34 +0000 Subject: [PATCH 196/249] Support None if initial part of dotted lookup returns None. Closes #1223. --- rest_framework/fields.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 8cc8e81ec..24ddb7a44 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -57,6 +57,9 @@ def get_attribute(instance, attrs): Also accepts either attribute lookup on objects or dictionary lookups. """ for attr in attrs: + if instance is None: + # Break out early if we get `None` at any point in a nested lookup. + return None try: instance = getattr(instance, attr) except ObjectDoesNotExist: From 0a5d088287be1bb56f37504cc75cee10fb4e74a0 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 5 Nov 2014 10:48:30 +0000 Subject: [PATCH 197/249] Fix failing copy of fields when RegexValidator is used. Closes #1954. --- rest_framework/fields.py | 16 ++++++++++++---- tests/test_validation.py | 20 +++++++++++++++++++- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 24ddb7a44..363b684f0 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1,7 +1,7 @@ from django.conf import settings -from django.core import validators from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ValidationError as DjangoValidationError +from django.core.validators import RegexValidator from django.forms import ImageField as DjangoImageField from django.utils import six, timezone from django.utils.datastructures import SortedDict @@ -392,7 +392,15 @@ class Field(object): originally created with, rather than copying the complete state. """ args = copy.deepcopy(self._args) - kwargs = copy.deepcopy(self._kwargs) + kwargs = dict(self._kwargs) + # Bit ugly, but we need to special case 'validators' as Django's + # RegexValidator does not support deepcopy. + # We treat validator callables as immutable objects. + # See https://github.com/tomchristie/django-rest-framework/issues/1954 + validators = kwargs.pop('validators', None) + kwargs = copy.deepcopy(kwargs) + if validators is not None: + kwargs['validators'] = validators return self.__class__(*args, **kwargs) def __repr__(self): @@ -531,7 +539,7 @@ class RegexField(CharField): def __init__(self, regex, **kwargs): super(RegexField, self).__init__(**kwargs) - validator = validators.RegexValidator(regex, message=self.error_messages['invalid']) + validator = RegexValidator(regex, message=self.error_messages['invalid']) self.validators.append(validator) @@ -543,7 +551,7 @@ class SlugField(CharField): def __init__(self, **kwargs): super(SlugField, self).__init__(**kwargs) slug_regex = re.compile(r'^[-a-zA-Z0-9_]+$') - validator = validators.RegexValidator(slug_regex, message=self.error_messages['invalid']) + validator = RegexValidator(slug_regex, message=self.error_messages['invalid']) self.validators.append(validator) diff --git a/tests/test_validation.py b/tests/test_validation.py index c278d90f3..3db825557 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -1,9 +1,10 @@ from __future__ import unicode_literals -from django.core.validators import MaxValueValidator +from django.core.validators import RegexValidator, MaxValueValidator from django.db import models from django.test import TestCase from rest_framework import generics, serializers, status from rest_framework.test import APIRequestFactory +import re factory = APIRequestFactory() @@ -174,3 +175,20 @@ class TestChoiceFieldChoicesValidate(TestCase): # f.to_native(value) # except ValidationError: # self.fail("Value %s does not validate" % str(value)) + + +class RegexSerializer(serializers.Serializer): + pin = serializers.CharField( + validators=[RegexValidator(regex=re.compile('^[0-9]{4,6}$'), + message='A PIN is 4-6 digits')]) + +expected_repr = """ +RegexSerializer(): + pin = CharField(validators=[<django.core.validators.RegexValidator object>]) +""".strip() + + +class TestRegexSerializer(TestCase): + def test_regex_repr(self): + serializer_repr = repr(RegexSerializer()) + assert serializer_repr == expected_repr From 571440e143870cf38230eea7c3a49df23d1eaa7c Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 5 Nov 2014 10:53:46 +0000 Subject: [PATCH 198/249] Stronger calling out of 'DjangoObjectPermissionsFilter'. Closes #1934. --- docs/api-guide/permissions.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index f3ae81717..446e362e1 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -146,7 +146,13 @@ As with `DjangoModelPermissions`, this permission must only be applied to views Note that `DjangoObjectPermissions` **does not** require the `django-guardian` package, and should support other object-level backends equally well. -As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoModelPermissions` and setting the `.perms_map` property. Refer to the source code for details. Note that if you add a custom `view` permission for `GET`, `HEAD` and `OPTIONS` requests, you'll probably also want to consider adding the `DjangoObjectPermissionsFilter` class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions. +As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoModelPermissions` and setting the `.perms_map` property. Refer to the source code for details. + +--- + +**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests, you'll want to consider also adding the `DjangoObjectPermissionsFilter` class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions. + +--- ## TokenHasReadWriteScope From 2daf085100b32fd4c13add0fcfa2dbb97722de4a Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 5 Nov 2014 11:08:32 +0000 Subject: [PATCH 199/249] Copy accepted_renderer and accepted_media_type when cloing a request. Closes #1950. --- rest_framework/request.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rest_framework/request.py b/rest_framework/request.py index d43527421..096b30424 100644 --- a/rest_framework/request.py +++ b/rest_framework/request.py @@ -103,6 +103,10 @@ def clone_request(request, method): ret._auth = request._auth if hasattr(request, '_authenticator'): ret._authenticator = request._authenticator + if hasattr(request, 'accepted_renderer'): + ret.accepted_renderer = request.accepted_renderer + if hasattr(request, 'accepted_media_type'): + ret.accepted_media_type = request.accepted_media_type return ret From 52507006595af4f9da34491e4211bf7ae447a457 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 5 Nov 2014 11:14:41 +0000 Subject: [PATCH 200/249] Add docs on request.accepted_renderer and .accepted_media_type --- docs/api-guide/requests.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md index 0696fedf6..87425ed1b 100644 --- a/docs/api-guide/requests.md +++ b/docs/api-guide/requests.md @@ -49,6 +49,20 @@ If a client sends a request with a content-type that cannot be parsed then a `Un --- +# Content negotiation + +The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialisation schemes for different media types. + +## .accepted_renderer + +The renderer instance what was selected by the content negotiation stage. + +## .accepted_media_type + +A string representing the media type that was accepted by the content negotiation stage. + +--- + # Authentication REST framework provides flexible, per-request authentication, that gives you the ability to: From d048d32876e4a2f4acb6848b809097b9b9d48e50 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 5 Nov 2014 13:40:21 +0000 Subject: [PATCH 201/249] Minor cleanup --- rest_framework/serializers.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index f00b685f4..9e5d0cabe 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -306,11 +306,7 @@ class Serializer(BaseSerializer): def get_initial(self): if self._initial_data is not None: - return ReturnDict([ - (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 - ], serializer=self) + return self.to_representation(self._initial_data) return ReturnDict([ (field.field_name, field.get_initial()) From 49fae230005bba4607f425d90de77363d6b8659e Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 5 Nov 2014 15:23:13 +0000 Subject: [PATCH 202/249] Pass through kwargs to both Serializer and ListSerializer --- rest_framework/relations.py | 14 ++++++++++---- rest_framework/serializers.py | 14 +++++++++++--- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 1665dd35e..f6ae30d05 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -13,6 +13,11 @@ class PKOnlyObject(object): def __init__(self, pk): self.pk = pk +MANY_RELATION_KWARGS = ( + 'read_only', 'write_only', 'required', 'default', 'initial', 'source', + 'label', 'help_text', 'style', 'error_messages' +) + class RelatedField(Field): def __init__(self, **kwargs): @@ -31,10 +36,11 @@ class RelatedField(Field): # We override this method in order to automagically create # `ManyRelation` classes instead when `many=True` is set. if kwargs.pop('many', False): - return ManyRelation( - child_relation=cls(*args, **kwargs), - read_only=kwargs.get('read_only', False) - ) + list_kwargs = {'child_relation': cls(*args, **kwargs)} + for key in kwargs.keys(): + if key in MANY_RELATION_KWARGS: + list_kwargs[key] = kwargs[key] + return ManyRelation(**list_kwargs) return super(RelatedField, cls).__new__(cls, *args, **kwargs) def run_validation(self, data=empty): diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 9e5d0cabe..dfac75fc5 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -43,6 +43,12 @@ import warnings from rest_framework.relations import * # NOQA from rest_framework.fields import * # NOQA +LIST_SERIALIZER_KWARGS = ( + 'read_only', 'write_only', 'required', 'default', 'initial', 'source', + 'label', 'help_text', 'style', 'error_messages', + 'instance', 'data', 'partial', 'context' +) + # BaseSerializer # -------------- @@ -52,7 +58,6 @@ class BaseSerializer(Field): The BaseSerializer class provides a minimal class which may be used for writing custom serializer implementations. """ - def __init__(self, instance=None, data=None, **kwargs): self.instance = instance self._initial_data = data @@ -65,8 +70,11 @@ class BaseSerializer(Field): # We override this method in order to automagically create # `ListSerializer` classes instead when `many=True` is set. if kwargs.pop('many', False): - kwargs['child'] = cls() - return ListSerializer(*args, **kwargs) + list_kwargs = {'child': cls(*args, **kwargs)} + for key in kwargs.keys(): + if key in LIST_SERIALIZER_KWARGS: + list_kwargs[key] = kwargs[key] + return ListSerializer(*args, **list_kwargs) return super(BaseSerializer, cls).__new__(cls, *args, **kwargs) def to_internal_value(self, data): From 73daf407150b4d0c456b529c4d9bba0e035fc370 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 5 Nov 2014 15:51:45 +0000 Subject: [PATCH 203/249] ModelField should support max_length. Closes #2018. --- rest_framework/fields.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 363b684f0..b554f2382 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1175,10 +1175,20 @@ class ModelField(Field): This is used by `ModelSerializer` when dealing with custom model fields, that do not have a serializer field to be mapped to. """ + default_error_messages = { + 'max_length': _('Ensure this field has no more than {max_length} characters.'), + } + def __init__(self, model_field, **kwargs): self.model_field = model_field kwargs['source'] = '*' + # The `max_length` option is supported by Django's base `Field` class, + # so we'd better support it here. + max_length = kwargs.pop('max_length', None) super(ModelField, self).__init__(**kwargs) + if max_length is not None: + message = self.error_messages['max_length'].format(max_length=max_length) + self.validators.append(MaxLengthValidator(max_length, message=message)) def to_internal_value(self, data): rel = getattr(self.model_field, 'rel', None) From ed541864e637681e1aca3a808be1f26202b4c271 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 6 Nov 2014 10:34:59 +0000 Subject: [PATCH 204/249] Support for bulk create. Closes #1965. --- rest_framework/fields.py | 2 +- rest_framework/serializers.py | 65 +++++++-- tests/test_fields.py | 2 +- tests/test_serializer_bulk_update.py | 202 +++++++++++++-------------- 4 files changed, 157 insertions(+), 114 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index b554f2382..a9e2e48bd 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -943,7 +943,7 @@ class ChoiceField(Field): 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}`.') } default_empty_html = [] diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index dfac75fc5..cbac39928 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -90,12 +90,10 @@ class BaseSerializer(Field): raise NotImplementedError('`create()` must be implemented.') def save(self, **kwargs): - validated_data = self.validated_data - if kwargs: - validated_data = dict( - list(validated_data.items()) + - list(kwargs.items()) - ) + validated_data = dict( + list(self.validated_data.items()) + + list(kwargs.items()) + ) if self.instance is not None: self.instance = self.update(self.instance, validated_data) @@ -210,9 +208,9 @@ class BoundField(object): class NestedBoundField(BoundField): """ - This BoundField additionally implements __iter__ and __getitem__ + This `BoundField` additionally implements __iter__ and __getitem__ in order to support nested bound fields. This class is the type of - BoundField that is used for serializer fields. + `BoundField` that is used for serializer fields. """ def __iter__(self): for field in self.fields.values(): @@ -460,6 +458,10 @@ class ListSerializer(BaseSerializer): child = None many = True + default_error_messages = { + 'not_a_list': _('Expected a list of items but got type `{input_type}`.') + } + 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.' @@ -485,7 +487,31 @@ class ListSerializer(BaseSerializer): """ if html.is_html_input(data): data = html.parse_html_list(data) - return [self.child.run_validation(item) for item in data] + + if not isinstance(data, list): + message = self.error_messages['not_a_list'].format( + input_type=type(data).__name__ + ) + raise ValidationError({ + api_settings.NON_FIELD_ERRORS_KEY: [message] + }) + + ret = [] + errors = ReturnList(serializer=self) + + for item in data: + try: + validated = self.child.run_validation(item) + except ValidationError, exc: + errors.append(exc.detail) + else: + ret.append(validated) + errors.append({}) + + if any(errors): + raise ValidationError(errors) + + return ret def to_representation(self, data): """ @@ -497,8 +523,25 @@ class ListSerializer(BaseSerializer): serializer=self ) - def create(self, attrs_list): - return [self.child.create(attrs) for attrs in attrs_list] + def save(self, **kwargs): + assert self.instance is None, ( + "Serializers do not support multiple update by default, because " + "it would be unclear how to deal with insertions, updates and " + "deletions. If you need to support multiple update, use a " + "`ListSerializer` class and override `.save()` so you can specify " + "the behavior exactly." + ) + + validated_data = [ + dict(list(attrs.items()) + list(kwargs.items())) + for attrs in self.validated_data + ] + + self.instance = [ + self.child.create(attrs) for attrs in validated_data + ] + + return self.instance def __repr__(self): return representation.list_repr(self, indent=1) diff --git a/tests/test_fields.py b/tests/test_fields.py index 96d09900e..5db381acc 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -859,7 +859,7 @@ class TestMultipleChoiceField(FieldValues): ('aircon', 'manual'): set(['aircon', 'manual']), } invalid_inputs = { - 'abc': ['Expected a list of items but got type `str`'], + 'abc': ['Expected a list of items but got type `str`.'], ('aircon', 'incorrect'): ['`incorrect` is not a valid choice.'] } outputs = [ diff --git a/tests/test_serializer_bulk_update.py b/tests/test_serializer_bulk_update.py index 3341ce590..85b6b2fa3 100644 --- a/tests/test_serializer_bulk_update.py +++ b/tests/test_serializer_bulk_update.py @@ -1,123 +1,123 @@ -# """ -# Tests to cover bulk create and update using serializers. -# """ -# from __future__ import unicode_literals -# from django.test import TestCase -# from rest_framework import serializers +""" +Tests to cover bulk create and update using serializers. +""" +from __future__ import unicode_literals +from django.test import TestCase +from rest_framework import serializers -# class BulkCreateSerializerTests(TestCase): -# """ -# Creating multiple instances using serializers. -# """ +class BulkCreateSerializerTests(TestCase): + """ + Creating multiple instances using serializers. + """ -# def setUp(self): -# class BookSerializer(serializers.Serializer): -# id = serializers.IntegerField() -# title = serializers.CharField(max_length=100) -# author = serializers.CharField(max_length=100) + def setUp(self): + class BookSerializer(serializers.Serializer): + id = serializers.IntegerField() + title = serializers.CharField(max_length=100) + author = serializers.CharField(max_length=100) -# self.BookSerializer = BookSerializer + self.BookSerializer = BookSerializer -# def test_bulk_create_success(self): -# """ -# Correct bulk update serialization should return the input data. -# """ + def test_bulk_create_success(self): + """ + Correct bulk update serialization should return the input data. + """ -# data = [ -# { -# 'id': 0, -# 'title': 'The electric kool-aid acid test', -# 'author': 'Tom Wolfe' -# }, { -# 'id': 1, -# 'title': 'If this is a man', -# 'author': 'Primo Levi' -# }, { -# 'id': 2, -# 'title': 'The wind-up bird chronicle', -# 'author': 'Haruki Murakami' -# } -# ] + data = [ + { + 'id': 0, + 'title': 'The electric kool-aid acid test', + 'author': 'Tom Wolfe' + }, { + 'id': 1, + 'title': 'If this is a man', + 'author': 'Primo Levi' + }, { + 'id': 2, + 'title': 'The wind-up bird chronicle', + 'author': 'Haruki Murakami' + } + ] -# serializer = self.BookSerializer(data=data, many=True) -# self.assertEqual(serializer.is_valid(), True) -# self.assertEqual(serializer.object, data) + serializer = self.BookSerializer(data=data, many=True) + self.assertEqual(serializer.is_valid(), True) + self.assertEqual(serializer.validated_data, data) -# def test_bulk_create_errors(self): -# """ -# Correct bulk update serialization should return the input data. -# """ + def test_bulk_create_errors(self): + """ + Incorrect bulk create serialization should return errors. + """ -# data = [ -# { -# 'id': 0, -# 'title': 'The electric kool-aid acid test', -# 'author': 'Tom Wolfe' -# }, { -# 'id': 1, -# 'title': 'If this is a man', -# 'author': 'Primo Levi' -# }, { -# 'id': 'foo', -# 'title': 'The wind-up bird chronicle', -# 'author': 'Haruki Murakami' -# } -# ] -# expected_errors = [ -# {}, -# {}, -# {'id': ['Enter a whole number.']} -# ] + data = [ + { + 'id': 0, + 'title': 'The electric kool-aid acid test', + 'author': 'Tom Wolfe' + }, { + 'id': 1, + 'title': 'If this is a man', + 'author': 'Primo Levi' + }, { + 'id': 'foo', + 'title': 'The wind-up bird chronicle', + 'author': 'Haruki Murakami' + } + ] + expected_errors = [ + {}, + {}, + {'id': ['A valid integer is required.']} + ] -# serializer = self.BookSerializer(data=data, many=True) -# self.assertEqual(serializer.is_valid(), False) -# self.assertEqual(serializer.errors, expected_errors) + serializer = self.BookSerializer(data=data, many=True) + self.assertEqual(serializer.is_valid(), False) + self.assertEqual(serializer.errors, expected_errors) -# def test_invalid_list_datatype(self): -# """ -# Data containing list of incorrect data type should return errors. -# """ -# data = ['foo', 'bar', 'baz'] -# serializer = self.BookSerializer(data=data, many=True) -# self.assertEqual(serializer.is_valid(), False) + def test_invalid_list_datatype(self): + """ + Data containing list of incorrect data type should return errors. + """ + data = ['foo', 'bar', 'baz'] + serializer = self.BookSerializer(data=data, many=True) + self.assertEqual(serializer.is_valid(), False) -# expected_errors = [ -# {'non_field_errors': ['Invalid data']}, -# {'non_field_errors': ['Invalid data']}, -# {'non_field_errors': ['Invalid data']} -# ] + expected_errors = [ + {'non_field_errors': ['Invalid data. Expected a dictionary, but got unicode.']}, + {'non_field_errors': ['Invalid data. Expected a dictionary, but got unicode.']}, + {'non_field_errors': ['Invalid data. Expected a dictionary, but got unicode.']} + ] -# self.assertEqual(serializer.errors, expected_errors) + self.assertEqual(serializer.errors, expected_errors) -# def test_invalid_single_datatype(self): -# """ -# Data containing a single incorrect data type should return errors. -# """ -# data = 123 -# serializer = self.BookSerializer(data=data, many=True) -# self.assertEqual(serializer.is_valid(), False) + def test_invalid_single_datatype(self): + """ + Data containing a single incorrect data type should return errors. + """ + data = 123 + serializer = self.BookSerializer(data=data, many=True) + self.assertEqual(serializer.is_valid(), False) -# expected_errors = {'non_field_errors': ['Expected a list of items.']} + expected_errors = {'non_field_errors': ['Expected a list of items but got type `int`.']} -# self.assertEqual(serializer.errors, expected_errors) + self.assertEqual(serializer.errors, expected_errors) -# def test_invalid_single_object(self): -# """ -# Data containing only a single object, instead of a list of objects -# should return errors. -# """ -# data = { -# 'id': 0, -# 'title': 'The electric kool-aid acid test', -# 'author': 'Tom Wolfe' -# } -# serializer = self.BookSerializer(data=data, many=True) -# self.assertEqual(serializer.is_valid(), False) + def test_invalid_single_object(self): + """ + Data containing only a single object, instead of a list of objects + should return errors. + """ + data = { + 'id': 0, + 'title': 'The electric kool-aid acid test', + 'author': 'Tom Wolfe' + } + serializer = self.BookSerializer(data=data, many=True) + self.assertEqual(serializer.is_valid(), False) -# expected_errors = {'non_field_errors': ['Expected a list of items.']} + expected_errors = {'non_field_errors': ['Expected a list of items but got type `dict`.']} -# self.assertEqual(serializer.errors, expected_errors) + self.assertEqual(serializer.errors, expected_errors) # class BulkUpdateSerializerTests(TestCase): From 4482be46ae8c9ed9864123903e114fcc833441ae Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 6 Nov 2014 11:10:36 +0000 Subject: [PATCH 205/249] More precise assertion error for bulk update --- rest_framework/serializers.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index cbac39928..68f9e362c 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -525,11 +525,11 @@ class ListSerializer(BaseSerializer): def save(self, **kwargs): assert self.instance is None, ( - "Serializers do not support multiple update by default, because " - "it would be unclear how to deal with insertions, updates and " - "deletions. If you need to support multiple update, use a " - "`ListSerializer` class and override `.save()` so you can specify " - "the behavior exactly." + "Serializers do not support multiple update by default, only " + "multiple create. For updates it is unclear how to deal with " + "insertions and deletions. If you need to support multiple update, " + "use a `ListSerializer` class and override `.save()` so you can " + "specify the behavior exactly." ) validated_data = [ From a919068c5df3677469064fa2e300d27ae4d6e39f Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 6 Nov 2014 11:35:34 +0000 Subject: [PATCH 206/249] Fix exception style for py3 --- rest_framework/serializers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 68f9e362c..7cd206c90 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -502,7 +502,7 @@ class ListSerializer(BaseSerializer): for item in data: try: validated = self.child.run_validation(item) - except ValidationError, exc: + except ValidationError as exc: errors.append(exc.detail) else: ret.append(validated) From 9923a6ce9013693ea1723e7895b3cab638d719fd Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 6 Nov 2014 11:51:10 +0000 Subject: [PATCH 207/249] Fix tests for py2/3 compat --- tests/test_serializer_bulk_update.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/test_serializer_bulk_update.py b/tests/test_serializer_bulk_update.py index 85b6b2fa3..2259ee317 100644 --- a/tests/test_serializer_bulk_update.py +++ b/tests/test_serializer_bulk_update.py @@ -3,6 +3,7 @@ Tests to cover bulk create and update using serializers. """ from __future__ import unicode_literals from django.test import TestCase +from django.utils import six from rest_framework import serializers @@ -82,10 +83,12 @@ class BulkCreateSerializerTests(TestCase): serializer = self.BookSerializer(data=data, many=True) self.assertEqual(serializer.is_valid(), False) + text_type_string = six.text_type.__name__ + message = 'Invalid data. Expected a dictionary, but got %s.' % text_type_string expected_errors = [ - {'non_field_errors': ['Invalid data. Expected a dictionary, but got unicode.']}, - {'non_field_errors': ['Invalid data. Expected a dictionary, but got unicode.']}, - {'non_field_errors': ['Invalid data. Expected a dictionary, but got unicode.']} + {'non_field_errors': [message]}, + {'non_field_errors': [message]}, + {'non_field_errors': [message]} ] self.assertEqual(serializer.errors, expected_errors) From 4e001dbb7ac0bc13d6d5fbb4524e905184610aa2 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 6 Nov 2014 12:00:30 +0000 Subject: [PATCH 208/249] Drop usage of SortedDict. Closes #2027. --- rest_framework/compat.py | 10 ++++++++++ rest_framework/fields.py | 7 +++---- rest_framework/metadata.py | 9 ++++----- rest_framework/routers.py | 6 +++--- rest_framework/serializers.py | 10 +++++----- rest_framework/utils/encoders.py | 11 +++++------ rest_framework/utils/model_meta.py | 12 ++++++------ 7 files changed, 36 insertions(+), 29 deletions(-) diff --git a/rest_framework/compat.py b/rest_framework/compat.py index 0201bd830..5bd85e743 100644 --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -26,6 +26,16 @@ except ImportError: from django.utils.encoding import force_unicode as force_text +# OrderedDict only available in Python 2.7. +# This will always be the case in Django 1.7 and above, as these versions +# no longer support Python 2.6. +# For Django <= 1.6 and Python 2.6 fall back to OrderedDict. +try: + from collections import OrderedDict +except: + from django.utils.datastructures import SortedDict as OrderedDict + + # HttpResponseBase only exists from 1.5 onwards try: from django.http.response import HttpResponseBase diff --git a/rest_framework/fields.py b/rest_framework/fields.py index a9e2e48bd..71377326f 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -4,14 +4,13 @@ from django.core.exceptions import ValidationError as DjangoValidationError from django.core.validators import RegexValidator from django.forms import ImageField as DjangoImageField from django.utils import six, timezone -from django.utils.datastructures import SortedDict from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.encoding import is_protected_type from django.utils.translation import ugettext_lazy as _ from rest_framework import ISO_8601 from rest_framework.compat import ( smart_text, EmailValidator, MinValueValidator, MaxValueValidator, - MinLengthValidator, MaxLengthValidator, URLValidator + MinLengthValidator, MaxLengthValidator, URLValidator, OrderedDict ) from rest_framework.exceptions import ValidationError from rest_framework.settings import api_settings @@ -917,9 +916,9 @@ class ChoiceField(Field): for item in choices ] if all(pairs): - self.choices = SortedDict([(key, display_value) for key, display_value in choices]) + self.choices = OrderedDict([(key, display_value) for key, display_value in choices]) else: - self.choices = SortedDict([(item, item) for item in choices]) + self.choices = OrderedDict([(item, item) for item in choices]) # Map the string representation of choices to the underlying value. # Allows us to deal with eg. integer choices while supporting either diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py index af4bc396b..b08d3ab67 100644 --- a/rest_framework/metadata.py +++ b/rest_framework/metadata.py @@ -10,9 +10,8 @@ from __future__ import unicode_literals from django.core.exceptions import PermissionDenied from django.http import Http404 -from django.utils.datastructures import SortedDict from rest_framework import exceptions, serializers -from rest_framework.compat import force_text +from rest_framework.compat import force_text, OrderedDict from rest_framework.request import clone_request from rest_framework.utils.field_mapping import ClassLookupDict @@ -54,7 +53,7 @@ class SimpleMetadata(BaseMetadata): }) def determine_metadata(self, request, view): - metadata = SortedDict() + metadata = OrderedDict() metadata['name'] = view.get_view_name() metadata['description'] = view.get_view_description() metadata['renders'] = [renderer.media_type for renderer in view.renderer_classes] @@ -97,7 +96,7 @@ class SimpleMetadata(BaseMetadata): Given an instance of a serializer, return a dictionary of metadata about its fields. """ - return SortedDict([ + return OrderedDict([ (field_name, self.get_field_info(field)) for field_name, field in serializer.fields.items() ]) @@ -107,7 +106,7 @@ class SimpleMetadata(BaseMetadata): Given an instance of a serializer field, return a dictionary of metadata about it. """ - field_info = SortedDict() + field_info = OrderedDict() field_info['type'] = self.label_lookup[field] field_info['required'] = getattr(field, 'required', False) diff --git a/rest_framework/routers.py b/rest_framework/routers.py index 169e6e8bc..6e99f14de 100644 --- a/rest_framework/routers.py +++ b/rest_framework/routers.py @@ -20,8 +20,8 @@ from collections import namedtuple from django.conf.urls import patterns, url from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import NoReverseMatch -from django.utils.datastructures import SortedDict from rest_framework import views +from rest_framework.compat import OrderedDict from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework.urlpatterns import format_suffix_patterns @@ -278,7 +278,7 @@ class DefaultRouter(SimpleRouter): """ Return a view to use as the API root. """ - api_root_dict = SortedDict() + api_root_dict = OrderedDict() list_name = self.routes[0].name for prefix, viewset, basename in self.registry: api_root_dict[prefix] = list_name.format(basename=basename) @@ -287,7 +287,7 @@ class DefaultRouter(SimpleRouter): _ignore_model_permissions = True def get(self, request, *args, **kwargs): - ret = SortedDict() + ret = OrderedDict() for key, url_name in api_root_dict.items(): try: ret[key] = reverse( diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 7cd206c90..0efa95241 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -14,8 +14,8 @@ from django.core.exceptions import ImproperlyConfigured from django.db import models from django.db.models.fields import FieldDoesNotExist from django.utils import six -from django.utils.datastructures import SortedDict from django.utils.translation import ugettext_lazy as _ +from rest_framework.compat import OrderedDict from rest_framework.exceptions import ValidationError from rest_framework.fields import empty, set_value, Field, SkipField from rest_framework.settings import api_settings @@ -159,7 +159,7 @@ class BaseSerializer(Field): # Serializer & ListSerializer classes # ----------------------------------- -class ReturnDict(SortedDict): +class ReturnDict(OrderedDict): """ Return object from `serialier.data` for the `Serializer` class. Includes a backlink to the serializer instance for renderers @@ -235,7 +235,7 @@ class BindingDict(object): """ def __init__(self, serializer): self.serializer = serializer - self.fields = SortedDict() + self.fields = OrderedDict() def __setitem__(self, key, field): self.fields[key] = field @@ -280,7 +280,7 @@ class SerializerMetaclass(type): if hasattr(base, '_declared_fields'): fields = list(base._declared_fields.items()) + fields - return SortedDict(fields) + return OrderedDict(fields) def __new__(cls, name, bases, attrs): attrs['_declared_fields'] = cls._get_declared_fields(bases, attrs) @@ -679,7 +679,7 @@ class ModelSerializer(Serializer): def get_fields(self): declared_fields = copy.deepcopy(self._declared_fields) - ret = SortedDict() + ret = OrderedDict() model = getattr(self.Meta, 'model') fields = getattr(self.Meta, 'fields', None) exclude = getattr(self.Meta, 'exclude', None) diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py index 486186c94..4d6bb3a34 100644 --- a/rest_framework/utils/encoders.py +++ b/rest_framework/utils/encoders.py @@ -4,9 +4,8 @@ Helper classes for parsers. from __future__ import unicode_literals from django.db.models.query import QuerySet from django.utils import six, timezone -from django.utils.datastructures import SortedDict from django.utils.functional import Promise -from rest_framework.compat import force_text +from rest_framework.compat import force_text, OrderedDict import datetime import decimal import types @@ -68,7 +67,7 @@ else: class SafeDumper(yaml.SafeDumper): """ Handles decimals as strings. - Handles SortedDicts as usual dicts, but preserves field order, rather + Handles OrderedDicts as usual dicts, but preserves field order, rather than the usual behaviour of sorting the keys. """ def represent_decimal(self, data): @@ -82,7 +81,7 @@ else: best_style = True if hasattr(mapping, 'items'): mapping = list(mapping.items()) - if not isinstance(mapping, SortedDict): + if not isinstance(mapping, OrderedDict): mapping.sort() for item_key, item_value in mapping: node_key = self.represent_data(item_key) @@ -104,7 +103,7 @@ else: SafeDumper.represent_decimal ) SafeDumper.add_representer( - SortedDict, + OrderedDict, yaml.representer.SafeRepresenter.represent_dict ) # SafeDumper.add_representer( @@ -112,7 +111,7 @@ else: # yaml.representer.SafeRepresenter.represent_dict # ) # SafeDumper.add_representer( - # SortedDictWithMetadata, + # OrderedDictWithMetadata, # yaml.representer.SafeRepresenter.represent_dict # ) SafeDumper.add_representer( diff --git a/rest_framework/utils/model_meta.py b/rest_framework/utils/model_meta.py index 7a95bcdd1..82361edf9 100644 --- a/rest_framework/utils/model_meta.py +++ b/rest_framework/utils/model_meta.py @@ -8,7 +8,7 @@ Usage: `get_field_info(model)` returns a `FieldInfo` instance. from collections import namedtuple from django.db import models from django.utils import six -from django.utils.datastructures import SortedDict +from rest_framework.compat import OrderedDict import inspect @@ -63,12 +63,12 @@ def get_field_info(model): pk = pk.rel.to._meta.pk # Deal with regular fields. - fields = SortedDict() + fields = OrderedDict() for field in [field for field in opts.fields if field.serialize and not field.rel]: fields[field.name] = field # Deal with forward relationships. - forward_relations = SortedDict() + forward_relations = OrderedDict() for field in [field for field in opts.fields if field.serialize and field.rel]: forward_relations[field.name] = RelationInfo( model_field=field, @@ -89,7 +89,7 @@ def get_field_info(model): ) # Deal with reverse relationships. - reverse_relations = SortedDict() + reverse_relations = OrderedDict() for relation in opts.get_all_related_objects(): accessor_name = relation.get_accessor_name() reverse_relations[accessor_name] = RelationInfo( @@ -114,14 +114,14 @@ def get_field_info(model): # Shortcut that merges both regular fields and the pk, # for simplifying regular field lookup. - fields_and_pk = SortedDict() + fields_and_pk = OrderedDict() fields_and_pk['pk'] = pk fields_and_pk[pk.name] = pk fields_and_pk.update(fields) # Shortcut that merges both forward and reverse relationships - relations = SortedDict( + relations = OrderedDict( list(forward_relations.items()) + list(reverse_relations.items()) ) From ea76dc18b6770aefcc53a6c5752674c2fff0ddcf Mon Sep 17 00:00:00 2001 From: Tymur Maryokhin <maryokhin@gmail.com> Date: Thu, 6 Nov 2014 18:20:55 +0100 Subject: [PATCH 209/249] Fixed base_url duplication in FileField.use_url Django already joins base_url when constructing FileField.url --- rest_framework/fields.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 71377326f..95cda2ced 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1007,7 +1007,7 @@ class FileField(Field): if self.use_url: if not value: return None - url = settings.MEDIA_URL + value.url + url = value.url request = self.context.get('request', None) if request is not None: return request.build_absolute_uri(url) From db1dd8e2406bf54a82d154babd360fba52a0d4bc Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 6 Nov 2014 17:32:33 +0000 Subject: [PATCH 210/249] Tests & fixes for list serialization --- rest_framework/utils/html.py | 4 +- tests/test_serializer_lists.py | 274 +++++++++++++++++++++++++++++++++ 2 files changed, 276 insertions(+), 2 deletions(-) create mode 100644 tests/test_serializer_lists.py diff --git a/rest_framework/utils/html.py b/rest_framework/utils/html.py index edc591e9c..15e83b3b4 100644 --- a/rest_framework/utils/html.py +++ b/rest_framework/utils/html.py @@ -2,6 +2,7 @@ Helpers for dealing with HTML input. """ import re +from django.utils.datastructures import MultiValueDict def is_html_input(dictionary): @@ -43,7 +44,6 @@ def parse_html_list(dictionary, prefix=''): {'foo': 'hij', 'bar': 'klm'} ] """ - Dict = type(dictionary) ret = {} regex = re.compile(r'^%s\[([0-9]+)\](.*)$' % re.escape(prefix)) for field, value in dictionary.items(): @@ -57,7 +57,7 @@ def parse_html_list(dictionary, prefix=''): elif isinstance(ret.get(index), dict): ret[index][key] = value else: - ret[index] = Dict({key: value}) + ret[index] = MultiValueDict({key: [value]}) return [ret[item] for item in sorted(ret.keys())] diff --git a/tests/test_serializer_lists.py b/tests/test_serializer_lists.py new file mode 100644 index 000000000..640067e3a --- /dev/null +++ b/tests/test_serializer_lists.py @@ -0,0 +1,274 @@ +from rest_framework import serializers +from django.utils.datastructures import MultiValueDict + + +class BasicObject: + """ + A mock object for testing serializer save behavior. + """ + def __init__(self, **kwargs): + self._data = kwargs + for key, value in kwargs.items(): + setattr(self, key, value) + + def __eq__(self, other): + if self._data.keys() != other._data.keys(): + return False + for key in self._data.keys(): + if self._data[key] != other._data[key]: + return False + return True + + +class TestListSerializer: + """ + Tests for using a ListSerializer as a top-level serializer. + Note that this is in contrast to using ListSerializer as a field. + """ + + def setup(self): + class IntegerListSerializer(serializers.ListSerializer): + child = serializers.IntegerField() + self.Serializer = IntegerListSerializer + + def test_validate(self): + """ + Validating a list of items should return a list of validated items. + """ + input_data = ["123", "456"] + expected_output = [123, 456] + serializer = self.Serializer(data=input_data) + assert serializer.is_valid() + assert serializer.validated_data == expected_output + + def test_validate_html_input(self): + """ + HTML input should be able to mock list structures using [x] style ids. + """ + input_data = MultiValueDict({"[0]": ["123"], "[1]": ["456"]}) + expected_output = [123, 456] + serializer = self.Serializer(data=input_data) + assert serializer.is_valid() + assert serializer.validated_data == expected_output + + +class TestListSerializerContainingNestedSerializer: + """ + Tests for using a ListSerializer containing another serializer. + """ + + def setup(self): + class TestSerializer(serializers.Serializer): + integer = serializers.IntegerField() + boolean = serializers.BooleanField() + + def create(self, validated_data): + return BasicObject(**validated_data) + + class ObjectListSerializer(serializers.ListSerializer): + child = TestSerializer() + + self.Serializer = ObjectListSerializer + + def test_validate(self): + """ + Validating a list of dictionaries should return a list of + validated dictionaries. + """ + input_data = [ + {"integer": "123", "boolean": "true"}, + {"integer": "456", "boolean": "false"} + ] + expected_output = [ + {"integer": 123, "boolean": True}, + {"integer": 456, "boolean": False} + ] + serializer = self.Serializer(data=input_data) + assert serializer.is_valid() + assert serializer.validated_data == expected_output + + def test_create(self): + """ + Creating from a list of dictionaries should return a list of objects. + """ + input_data = [ + {"integer": "123", "boolean": "true"}, + {"integer": "456", "boolean": "false"} + ] + expected_output = [ + BasicObject(integer=123, boolean=True), + BasicObject(integer=456, boolean=False), + ] + serializer = self.Serializer(data=input_data) + assert serializer.is_valid() + assert serializer.save() == expected_output + + def test_serialize(self): + """ + Serialization of a list of objects should return a list of dictionaries. + """ + input_objects = [ + BasicObject(integer=123, boolean=True), + BasicObject(integer=456, boolean=False) + ] + expected_output = [ + {"integer": 123, "boolean": True}, + {"integer": 456, "boolean": False} + ] + serializer = self.Serializer(input_objects) + assert serializer.data == expected_output + + def test_validate_html_input(self): + """ + HTML input should be able to mock list structures using [x] + style prefixes. + """ + input_data = MultiValueDict({ + "[0]integer": ["123"], + "[0]boolean": ["true"], + "[1]integer": ["456"], + "[1]boolean": ["false"] + }) + expected_output = [ + {"integer": 123, "boolean": True}, + {"integer": 456, "boolean": False} + ] + serializer = self.Serializer(data=input_data) + assert serializer.is_valid() + assert serializer.validated_data == expected_output + + +class TestNestedListSerializer: + """ + Tests for using a ListSerializer as a field. + """ + + def setup(self): + class TestSerializer(serializers.Serializer): + integers = serializers.ListSerializer(child=serializers.IntegerField()) + booleans = serializers.ListSerializer(child=serializers.BooleanField()) + + def create(self, validated_data): + return BasicObject(**validated_data) + + self.Serializer = TestSerializer + + def test_validate(self): + """ + Validating a list of items should return a list of validated items. + """ + input_data = { + "integers": ["123", "456"], + "booleans": ["true", "false"] + } + expected_output = { + "integers": [123, 456], + "booleans": [True, False] + } + serializer = self.Serializer(data=input_data) + assert serializer.is_valid() + assert serializer.validated_data == expected_output + + def test_create(self): + """ + Creation with a list of items return an object with an attribute that + is a list of items. + """ + input_data = { + "integers": ["123", "456"], + "booleans": ["true", "false"] + } + expected_output = BasicObject( + integers=[123, 456], + booleans=[True, False] + ) + serializer = self.Serializer(data=input_data) + assert serializer.is_valid() + assert serializer.save() == expected_output + + def test_serialize(self): + """ + Serialization of a list of items should return a list of items. + """ + input_object = BasicObject( + integers=[123, 456], + booleans=[True, False] + ) + expected_output = { + "integers": [123, 456], + "booleans": [True, False] + } + serializer = self.Serializer(input_object) + assert serializer.data == expected_output + + def test_validate_html_input(self): + """ + HTML input should be able to mock list structures using [x] + style prefixes. + """ + input_data = MultiValueDict({ + "integers[0]": ["123"], + "integers[1]": ["456"], + "booleans[0]": ["true"], + "booleans[1]": ["false"] + }) + expected_output = { + "integers": [123, 456], + "booleans": [True, False] + } + serializer = self.Serializer(data=input_data) + assert serializer.is_valid() + assert serializer.validated_data == expected_output + + +class TestNestedListOfListsSerializer: + def setup(self): + class TestSerializer(serializers.Serializer): + integers = serializers.ListSerializer( + child=serializers.ListSerializer( + child=serializers.IntegerField() + ) + ) + booleans = serializers.ListSerializer( + child=serializers.ListSerializer( + child=serializers.BooleanField() + ) + ) + + self.Serializer = TestSerializer + + def test_validate(self): + input_data = { + 'integers': [['123', '456'], ['789', '0']], + 'booleans': [['true', 'true'], ['false', 'true']] + } + expected_output = { + "integers": [[123, 456], [789, 0]], + "booleans": [[True, True], [False, True]] + } + serializer = self.Serializer(data=input_data) + assert serializer.is_valid() + assert serializer.validated_data == expected_output + + def test_validate_html_input(self): + """ + HTML input should be able to mock lists of lists using [x][y] + style prefixes. + """ + input_data = MultiValueDict({ + "integers[0][0]": ["123"], + "integers[0][1]": ["456"], + "integers[1][0]": ["789"], + "integers[1][1]": ["000"], + "booleans[0][0]": ["true"], + "booleans[0][1]": ["true"], + "booleans[1][0]": ["false"], + "booleans[1][1]": ["true"] + }) + expected_output = { + "integers": [[123, 456], [789, 0]], + "booleans": [[True, True], [False, True]] + } + serializer = self.Serializer(data=input_data) + assert serializer.is_valid() + assert serializer.validated_data == expected_output From b44def465054345b6099aae7bdd34b623fdc124c Mon Sep 17 00:00:00 2001 From: Brett Koonce <koonce@gmail.com> Date: Thu, 6 Nov 2014 23:19:26 -0800 Subject: [PATCH 211/249] minor spelling tweaks --- docs/api-guide/authentication.md | 2 +- docs/api-guide/generic-views.md | 2 +- docs/api-guide/relations.md | 2 +- docs/api-guide/settings.md | 6 +++--- docs/api-guide/throttling.md | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 3a5156fd1..01774c10d 100755 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -398,7 +398,7 @@ HTTP digest authentication is a widely implemented scheme that was intended to r ## Django OAuth Toolkit -The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by [Evonove][evonove] and uses the excelllent [OAuthLib][oauthlib]. The package is well documented, and comes as a recommended alternative for OAuth 2.0 support. +The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by [Evonove][evonove] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and comes as a recommended alternative for OAuth 2.0 support. ## Django OAuth2 Consumer diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index d2836fa6d..49a5e58f0 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -374,7 +374,7 @@ Using custom base classes is a good option if you have custom behavior that cons Prior to version 3.0 the REST framework mixins treated `PUT` as either an update or a create operation, depending on if the object already existed or not. -Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existance of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses. +Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses. Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious. diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index cc4f55851..d03a75ae5 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -202,7 +202,7 @@ This field is always read-only. **Arguments**: -* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this wil be a string with the format `<model_name>-detail`. **required**. +* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `<model_name>-detail`. **required**. * `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`. * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 2144a2ed3..48af30a52 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -154,13 +154,13 @@ Default: `None` ### SEARCH_PARAM -The name of a query paramater, which can be used to specify the search term used by `SearchFilter`. +The name of a query parameter, which can be used to specify the search term used by `SearchFilter`. Default: `search` #### ORDERING_PARAM -The name of a query paramater, which can be used to specify the ordering of results returned by `OrderingFilter`. +The name of a query parameter, which can be used to specify the ordering of results returned by `OrderingFilter`. Default: `ordering` @@ -321,7 +321,7 @@ When set to `False`, JSON responses will escape non-ascii characters, like so: {"unicode black star":"\u2605"} -Both styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. The unicode style is prefered as being more user-friendly when inspecting API responses. +Both styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses. Default: `True` diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index 16a7457b0..147c16ff7 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -74,7 +74,7 @@ If you need to strictly identify unique client IP addresses, you'll need to firs It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client. -Further context on how the `X-Forwarded-For` header works, and identifing a remote client IP can be [found here][identifing-clients]. +Further context on how the `X-Forwarded-For` header works, and identifying a remote client IP can be [found here][identifing-clients]. ## Setting up the cache @@ -85,7 +85,7 @@ If you need to use a cache other than `'default'`, you can do so by creating a c class CustomAnonRateThrottle(AnonRateThrottle): cache = get_cache('alternate') -You'll need to rememeber to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute. +You'll need to remember to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute. --- From 9b19b5a59485c9dad4a18538a8a86f1ae4ea2a55 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 7 Nov 2014 10:13:46 +0000 Subject: [PATCH 212/249] Serializer cleanup --- rest_framework/serializers.py | 128 +++++---------------- rest_framework/utils/serializer_helpers.py | 99 ++++++++++++++++ 2 files changed, 129 insertions(+), 98 deletions(-) create mode 100644 rest_framework/utils/serializer_helpers.py diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 0efa95241..68ea27ab6 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -25,6 +25,9 @@ from rest_framework.utils.field_mapping import ( get_relation_kwargs, get_nested_relation_kwargs, ClassLookupDict ) +from rest_framework.utils.serializer_helpers import ( + ReturnDict, ReturnList, BoundField, NestedBoundField, BindingDict +) from rest_framework.validators import ( UniqueForDateValidator, UniqueForMonthValidator, UniqueForYearValidator, UniqueTogetherValidator @@ -159,104 +162,6 @@ class BaseSerializer(Field): # Serializer & ListSerializer classes # ----------------------------------- -class ReturnDict(OrderedDict): - """ - Return object from `serialier.data` for the `Serializer` class. - Includes a backlink to the serializer instance for renderers - to use if they need richer field information. - """ - def __init__(self, *args, **kwargs): - self.serializer = kwargs.pop('serializer') - super(ReturnDict, self).__init__(*args, **kwargs) - - -class ReturnList(list): - """ - Return object from `serialier.data` for the `SerializerList` class. - Includes a backlink to the serializer instance for renderers - to use if they need richer field information. - """ - def __init__(self, *args, **kwargs): - self.serializer = kwargs.pop('serializer') - super(ReturnList, self).__init__(*args, **kwargs) - - -class BoundField(object): - """ - A field object that also includes `.value` and `.error` properties. - Returned when iterating over a serializer instance, - providing an API similar to Django forms and form fields. - """ - def __init__(self, field, value, errors, prefix=''): - self._field = field - self.value = value - self.errors = errors - self.name = prefix + self.field_name - - def __getattr__(self, attr_name): - return getattr(self._field, attr_name) - - @property - def _proxy_class(self): - return self._field.__class__ - - def __repr__(self): - return '<%s value=%s errors=%s>' % ( - self.__class__.__name__, self.value, self.errors - ) - - -class NestedBoundField(BoundField): - """ - This `BoundField` additionally implements __iter__ and __getitem__ - in order to support nested bound fields. This class is the type of - `BoundField` that is used for serializer fields. - """ - def __iter__(self): - for field in self.fields.values(): - yield self[field.field_name] - - def __getitem__(self, key): - field = self.fields[key] - value = self.value.get(key) if self.value else None - error = self.errors.get(key) if self.errors else None - if isinstance(field, Serializer): - return NestedBoundField(field, value, error, prefix=self.name + '.') - return BoundField(field, value, error, prefix=self.name + '.') - - -class BindingDict(object): - """ - This dict-like object is used to store fields on a serializer. - - This ensures that whenever fields are added to the serializer we call - `field.bind()` so that the `field_name` and `parent` attributes - can be set correctly. - """ - def __init__(self, serializer): - self.serializer = serializer - self.fields = OrderedDict() - - def __setitem__(self, key, field): - self.fields[key] = field - field.bind(field_name=key, parent=self.serializer) - - def __getitem__(self, key): - return self.fields[key] - - def __delitem__(self, key): - del self.fields[key] - - def items(self): - return self.fields.items() - - def keys(self): - return self.fields.keys() - - def values(self): - return self.fields.values() - - class SerializerMetaclass(type): """ This metaclass sets a dictionary named `base_fields` on the class. @@ -295,6 +200,12 @@ class Serializer(BaseSerializer): @property def fields(self): + """ + A dictionary of {field_name: field_instance}. + """ + # `fields` is evalutated lazily. We do this to ensure that we don't + # have issues importing modules that use ModelSerializers as fields, + # even if Django's app-loading stage has not yet run. if not hasattr(self, '_fields'): self._fields = BindingDict(self) for key, value in self.get_fields().items(): @@ -302,12 +213,19 @@ class Serializer(BaseSerializer): return self._fields def get_fields(self): + """ + Returns a dictionary of {field_name: field_instance}. + """ # Every new serializer is created with a clone of the field instances. # This allows users to dynamically modify the fields on a serializer # instance without affecting every other serializer class. return copy.deepcopy(self._declared_fields) def get_validators(self): + """ + Returns a list of validator callables. + """ + # Used by the lazily-evaluated `validators` property. return getattr(getattr(self, 'Meta', None), 'validators', []) def get_initial(self): @@ -551,6 +469,13 @@ class ListSerializer(BaseSerializer): # -------------------------------------------- class ModelSerializer(Serializer): + """ + A `ModelSerializer` is just a regular `Serializer`, except that: + + * A set of default fields are automatically populated. + * A set of default validators are automatically populated. + * Default `.create()` and `.update()` implementations are provided. + """ _field_mapping = ClassLookupDict({ models.AutoField: IntegerField, models.BigIntegerField: IntegerField, @@ -915,6 +840,13 @@ class ModelSerializer(Serializer): class HyperlinkedModelSerializer(ModelSerializer): + """ + A type of `ModelSerializer` that uses hyperlinked relationships instead + of primary key relationships. Specifically: + + * A 'url' field is included instead of the 'id' field. + * Relationships to other instances are hyperlinks, instead of primary keys. + """ _related_class = HyperlinkedRelatedField def _get_default_field_names(self, declared_fields, model_info): diff --git a/rest_framework/utils/serializer_helpers.py b/rest_framework/utils/serializer_helpers.py new file mode 100644 index 000000000..a861ca077 --- /dev/null +++ b/rest_framework/utils/serializer_helpers.py @@ -0,0 +1,99 @@ +from rest_framework.compat import OrderedDict + + +class ReturnDict(OrderedDict): + """ + Return object from `serialier.data` for the `Serializer` class. + Includes a backlink to the serializer instance for renderers + to use if they need richer field information. + """ + def __init__(self, *args, **kwargs): + self.serializer = kwargs.pop('serializer') + super(ReturnDict, self).__init__(*args, **kwargs) + + +class ReturnList(list): + """ + Return object from `serialier.data` for the `SerializerList` class. + Includes a backlink to the serializer instance for renderers + to use if they need richer field information. + """ + def __init__(self, *args, **kwargs): + self.serializer = kwargs.pop('serializer') + super(ReturnList, self).__init__(*args, **kwargs) + + +class BoundField(object): + """ + A field object that also includes `.value` and `.error` properties. + Returned when iterating over a serializer instance, + providing an API similar to Django forms and form fields. + """ + def __init__(self, field, value, errors, prefix=''): + self._field = field + self.value = value + self.errors = errors + self.name = prefix + self.field_name + + def __getattr__(self, attr_name): + return getattr(self._field, attr_name) + + @property + def _proxy_class(self): + return self._field.__class__ + + def __repr__(self): + return '<%s value=%s errors=%s>' % ( + self.__class__.__name__, self.value, self.errors + ) + + +class NestedBoundField(BoundField): + """ + This `BoundField` additionally implements __iter__ and __getitem__ + in order to support nested bound fields. This class is the type of + `BoundField` that is used for serializer fields. + """ + def __iter__(self): + for field in self.fields.values(): + yield self[field.field_name] + + def __getitem__(self, key): + field = self.fields[key] + value = self.value.get(key) if self.value else None + error = self.errors.get(key) if self.errors else None + if hasattr(field, 'fields'): + return NestedBoundField(field, value, error, prefix=self.name + '.') + return BoundField(field, value, error, prefix=self.name + '.') + + +class BindingDict(object): + """ + This dict-like object is used to store fields on a serializer. + + This ensures that whenever fields are added to the serializer we call + `field.bind()` so that the `field_name` and `parent` attributes + can be set correctly. + """ + def __init__(self, serializer): + self.serializer = serializer + self.fields = OrderedDict() + + def __setitem__(self, key, field): + self.fields[key] = field + field.bind(field_name=key, parent=self.serializer) + + def __getitem__(self, key): + return self.fields[key] + + def __delitem__(self, key): + del self.fields[key] + + def items(self): + return self.fields.items() + + def keys(self): + return self.fields.keys() + + def values(self): + return self.fields.values() From e399140031a0738a054f5f07e42ef7208f9e45f4 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 7 Nov 2014 10:51:08 +0000 Subject: [PATCH 213/249] Minor tweaks --- rest_framework/serializers.py | 6 ++++++ rest_framework/utils/field_mapping.py | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 68ea27ab6..b00f9b7a8 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -393,6 +393,9 @@ class ListSerializer(BaseSerializer): return ReturnList(serializer=self) def get_value(self, dictionary): + """ + Given the input dictionary, return the field value. + """ # We override the default field access in order to support # lists in HTML forms. if html.is_html_input(dictionary): @@ -442,6 +445,9 @@ class ListSerializer(BaseSerializer): ) def save(self, **kwargs): + """ + Save and return a list of object instances. + """ assert self.instance is None, ( "Serializers do not support multiple update by default, only " "multiple create. For updates it is unclear how to deal with " diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index 6db371469..246390853 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -219,9 +219,11 @@ def get_relation_kwargs(field_name, relation_info): kwargs['required'] = False if model_field.null: kwargs['allow_null'] = True + if model_field.validators: + kwargs['validators'] = model_field.validators if getattr(model_field, 'unique', False): validator = UniqueValidator(queryset=model_field.model._default_manager) - kwargs['validators'] = [validator] + kwargs['validators'] = kwargs.get('validators', []) + [validator] return kwargs From a16a8a10a9204e574ad912eeced535d70a385b37 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 7 Nov 2014 11:16:26 +0000 Subject: [PATCH 214/249] .copy() for serializer .data and .errors dictionaries --- rest_framework/utils/serializer_helpers.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/rest_framework/utils/serializer_helpers.py b/rest_framework/utils/serializer_helpers.py index a861ca077..92d19857e 100644 --- a/rest_framework/utils/serializer_helpers.py +++ b/rest_framework/utils/serializer_helpers.py @@ -11,6 +11,9 @@ class ReturnDict(OrderedDict): self.serializer = kwargs.pop('serializer') super(ReturnDict, self).__init__(*args, **kwargs) + def copy(self): + return ReturnDict(self, serializer=self.serializer) + class ReturnList(list): """ From eafb7e1e24c31f0a6795ef5b8ac52940569d5854 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 7 Nov 2014 11:44:16 +0000 Subject: [PATCH 215/249] ModelField fix. Closes #2018. --- rest_framework/fields.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 95cda2ced..4933d8db6 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1180,7 +1180,6 @@ class ModelField(Field): def __init__(self, model_field, **kwargs): self.model_field = model_field - kwargs['source'] = '*' # The `max_length` option is supported by Django's base `Field` class, # so we'd better support it here. max_length = kwargs.pop('max_length', None) @@ -1195,6 +1194,11 @@ class ModelField(Field): return rel.to._meta.get_field(rel.field_name).to_python(data) return self.model_field.to_python(data) + def get_attribute(self, obj): + # We pass the object instance onto `to_representation`, + # not just the field attribute. + return obj + def to_representation(self, obj): value = self.model_field._get_val_from_obj(obj) if is_protected_type(value): From bb21216a7c7f3435ece44462beb24275bb44551a Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 7 Nov 2014 12:16:25 +0000 Subject: [PATCH 216/249] Metadata API should examine child serializer if passed parent ListSerializer. Closes #2035. --- rest_framework/metadata.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py index b08d3ab67..90d3f2e01 100644 --- a/rest_framework/metadata.py +++ b/rest_framework/metadata.py @@ -96,6 +96,10 @@ class SimpleMetadata(BaseMetadata): Given an instance of a serializer, return a dictionary of metadata about its fields. """ + if hasattr(serializer, 'child'): + # If this is a `ListSerializer` then we want to examine the + # underlying child serializer instance instead. + serializer = serializer.child return OrderedDict([ (field_name, self.get_field_info(field)) for field_name, field in serializer.fields.items() From 73bebbba64ddd287b7eb7c27047abe889b69f67e Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 7 Nov 2014 12:53:01 +0000 Subject: [PATCH 217/249] Add font files --- MANIFEST.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MANIFEST.in b/MANIFEST.in index d407865fb..d202c86ea 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,4 +1,4 @@ -recursive-include rest_framework/static *.js *.css *.png +recursive-include rest_framework/static *.js *.css *.png *.eot *.svg *.ttf *.woff recursive-include rest_framework/templates *.html recursive-exclude * __pycache__ recursive-exclude * *.py[co] From 041435f4eeee80fbc805154977140cf42335c954 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 7 Nov 2014 14:08:20 +0000 Subject: [PATCH 218/249] Prevent re-running deserialization. Closes #1975. --- rest_framework/renderers.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index c950b4981..87fe4d29f 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -523,8 +523,10 @@ class BrowsableAPIRenderer(BaseRenderer): data = request.data except ParseError: data = None + existing_serializer = serializer else: data = None + existing_serializer = None with override_method(view, request, method) as request: if not self.show_form_for_method(view, method, request, instance): @@ -539,9 +541,12 @@ class BrowsableAPIRenderer(BaseRenderer): ): return - serializer = view.get_serializer(instance=instance, data=data) - if data is not None: - serializer.is_valid() + if existing_serializer is not None: + serializer = existing_serializer + else: + serializer = view.get_serializer(instance=instance, data=data) + if data is not None: + serializer.is_valid() form_renderer = self.form_renderer_class() return form_renderer.render(serializer.data, self.accepted_media_type, self.renderer_context) From 55c44fc92192f63867c6c7ebcb7f75bf0569c900 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 7 Nov 2014 14:13:50 +0000 Subject: [PATCH 219/249] Fix serializer initial data --- rest_framework/serializers.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index b00f9b7a8..833a4e486 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -230,7 +230,11 @@ class Serializer(BaseSerializer): def get_initial(self): if self._initial_data is not None: - return self.to_representation(self._initial_data) + return ReturnDict([ + (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 + ], serializer=self) return ReturnDict([ (field.field_name, field.get_initial()) From 02844a1507285b7146dede5023b784fe63678cf7 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 7 Nov 2014 15:22:17 +0000 Subject: [PATCH 220/249] Fix up fieldset templates. Closes #2039 --- .../templates/rest_framework/horizontal/fieldset.html | 4 +++- rest_framework/templates/rest_framework/inline/fieldset.html | 4 +++- .../templates/rest_framework/vertical/fieldset.html | 4 +++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/rest_framework/templates/rest_framework/horizontal/fieldset.html b/rest_framework/templates/rest_framework/horizontal/fieldset.html index f6d5dd9d2..ba3e3abae 100644 --- a/rest_framework/templates/rest_framework/horizontal/fieldset.html +++ b/rest_framework/templates/rest_framework/horizontal/fieldset.html @@ -6,6 +6,8 @@ </div> {% endif %} {% for nested_field in field %} - {% render_field nested_field template_pack=template_pack renderer=renderer %} + {% if not nested_field.read_only %} + {% render_field nested_field style=style %} + {% endif %} {% endfor %} </fieldset> diff --git a/rest_framework/templates/rest_framework/inline/fieldset.html b/rest_framework/templates/rest_framework/inline/fieldset.html index 5ee182a5b..e49b42fdf 100644 --- a/rest_framework/templates/rest_framework/inline/fieldset.html +++ b/rest_framework/templates/rest_framework/inline/fieldset.html @@ -1,4 +1,6 @@ {% load rest_framework %} {% for nested_field in field %} - {% render_field nested_field template_pack=template_pack renderer=renderer %} + {% if not nested_field.read_only %} + {% render_field nested_field style=style %} + {% endif %} {% endfor %} diff --git a/rest_framework/templates/rest_framework/vertical/fieldset.html b/rest_framework/templates/rest_framework/vertical/fieldset.html index 824e6098f..3eb5191c7 100644 --- a/rest_framework/templates/rest_framework/vertical/fieldset.html +++ b/rest_framework/templates/rest_framework/vertical/fieldset.html @@ -2,6 +2,8 @@ <fieldset> {% if field.label %}<legend {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %} {% for nested_field in field %} - {% render_field nested_field template_pack=template_pack renderer=renderer %} + {% if not nested_field.read_only %} + {% render_field nested_field style=style %} + {% endif %} {% endfor %} </fieldset> From 3e878a3207ba79785d41b4d6af5cd956156d45a3 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 7 Nov 2014 15:38:27 +0000 Subject: [PATCH 221/249] Fix initial data on serializers to reflect writable fields --- rest_framework/renderers.py | 5 ----- rest_framework/serializers.py | 3 ++- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 87fe4d29f..b56f99db9 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -581,12 +581,7 @@ class BrowsableAPIRenderer(BaseRenderer): # View has a serializer defined and parser class has a # corresponding renderer that can be used to render the data. - # Get a read-only version of the serializer serializer = view.get_serializer(instance=instance) - if instance is None: - for name, field in serializer.fields.items(): - if getattr(field, 'read_only', None): - del serializer.fields[name] # Render the raw data content renderer = renderer_class() diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 833a4e486..d83367f40 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -234,12 +234,13 @@ class Serializer(BaseSerializer): (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 + and not field.read_only ], serializer=self) return ReturnDict([ (field.field_name, field.get_initial()) for field in self.fields.values() - if not field.write_only + if not field.read_only ], serializer=self) def get_value(self, dictionary): From 51d86a65055491df3fe0533f8e2e89237a51e379 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 7 Nov 2014 16:05:07 +0000 Subject: [PATCH 222/249] Support dotted source on relational fields --- rest_framework/relations.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index f6ae30d05..48ddf41e0 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -56,8 +56,8 @@ class RelatedField(Field): queryset = queryset.all() return queryset - def get_iterable(self, instance, source): - relationship = get_attribute(instance, [source]) + def get_iterable(self, instance, source_attrs): + relationship = get_attribute(instance, source_attrs) return relationship.all() if (hasattr(relationship, 'all')) else relationship @property @@ -106,11 +106,12 @@ class PrimaryKeyRelatedField(RelatedField): # the related object. We return this directly instead of returning the # object itself, which would require a database lookup. try: - return PKOnlyObject(pk=instance.serializable_value(self.source)) + 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]) + return get_attribute(instance, self.source_attrs) - def get_iterable(self, instance, source): + 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-primative value for the pk otherwise. @@ -119,7 +120,7 @@ class PrimaryKeyRelatedField(RelatedField): # 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) + relationship = super(PrimaryKeyRelatedField, self).get_iterable(instance, source_attrs) return [ PKOnlyObject(pk=item.serializable_value('pk')) for item in relationship @@ -318,7 +319,7 @@ class ManyRelation(Field): ] def get_attribute(self, instance): - return self.child_relation.get_iterable(instance, self.source) + return self.child_relation.get_iterable(instance, self.source_attrs) def to_representation(self, iterable): return [ From 59b30307e80fb26f2c7caa82492c78fe265b537e Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 7 Nov 2014 20:10:15 +0000 Subject: [PATCH 223/249] Fixes to release notes --- docs/topics/3.0-announcement.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index e8428bc20..272b730c4 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -1,17 +1,11 @@ ## Pre-release notes: -The 3.0 release is now ready for some tentative testing and upgrades for super keen early adopters. You can install the development version directly from GitHub like so: +The 3.0 release is now ready for some tentative testing and upgrades for early adopters. You can install the development version directly from GitHub like so: - pip install https://github.com/tomchristie/django-rest-framework/archive/version-3.0.zip + pip install https://github.com/tomchristie/django-rest-framework/archive/master.zip See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-framework/pull/1800) for more details on remaining work. -The most notable outstanding issues still to be resolved on the `version-3.0` branch are as follows: - -* Finish forms support for serializers and in the browsable API. -* Optimisations for serializing primary keys. -* Refine style of validation errors in some cases, such as validation errors in `ListField`. - **Your feedback on the upgrade process and 3.0 changes is hugely important!** Please do get in touch via twitter, IRC, a GitHub ticket, or the discussion group. @@ -237,7 +231,7 @@ To use writable nested serialization you'll want to declare a nested field on th fields = ('username', 'email', 'profile') def create(self, validated_data): - profile_data = validated_data.pop['profile'] + profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(user=user, **profile_data) return user From 93633c297c69a1eefda5e153553c4f021cf10bd8 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Fri, 7 Nov 2014 20:44:12 +0000 Subject: [PATCH 224/249] Tweaks to release notes --- docs/topics/3.0-announcement.md | 43 +++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 272b730c4..d3da0607e 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -27,8 +27,8 @@ Notable features of this new release include: * Printable representations on serializers that allow you to inspect exactly what fields are present on the instance. * Simple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit `ModelSerializer` class and the explicit `Serializer` class. * A new `BaseSerializer` class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic. -* A cleaner fields API plus new `ListField` and `MultipleChoiceField` classes. -* Super simple default implementations for the generic views. +* A cleaner fields API including new classes such as `ListField` and `MultipleChoiceField`. +* [Super simple default implementations][mixins.py] for the generic views. * Support for overriding how validation errors are handled by your API. * A metadata API that allows you to customize how `OPTIONS` requests are handled by your API. * A more compact JSON output with unicode style encoding turned on by default. @@ -70,7 +70,7 @@ Previously the serializers used a two-step object creation, as follows: This style is in-line with how the `ModelForm` class works in Django, but is problematic for a number of reasons: * Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumented state on the object instance, or kept as state on the serializer instance so that it could be used when `.save()` is called. -* Instantiating model instances directly means that you cannot use model manager classes for instance creation, eg `ExampleModel.objects.create(...)`. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints. +* Instantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. `ExampleModel.objects.create(...)`. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints. * The two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save? We now use single-step object creation, like so: @@ -184,7 +184,7 @@ This ensures you can still write validation that compares all the input fields, #### Differences between ModelSerializer validation and ModelForm. -This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behaviour on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes. +This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes. It's important to note that this change also means that the model `.clean()` method will not be called as part of serializer validation, as it would be if using a `ModelForm`. Use the serializer `.validate()` method to perform a final validation step on incoming data where required. @@ -219,7 +219,7 @@ If you try to use a writable nested serializer without writing a custom `create( >>> >>> serializer = UserSerializer(data=data) >>> serializer.save() - AssertionError: The `.create()` method does not suport nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields. + AssertionError: The `.create()` method does not support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields. To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the `create()` and/or `update()` methods explicitly. @@ -274,7 +274,7 @@ The `write_only_fields` option on `ModelSerializer` has been moved to `PendingDe model = MyModel fields = ('id', 'email', 'notes', 'is_admin') extra_kwargs = { - 'is_admin': {'write_only': True} + 'is_admin': {'write_only': True} } Alternatively, specify the field explicitly on the serializer class: @@ -321,8 +321,8 @@ With `ModelSerializer` you can now specify field names in the `fields` option th to_email = models.EmailField() message = models.CharField(max_length=1000) - def expiry_date(self): - return self.created + datetime.timedelta(days=30) + def expiry_date(self): + return self.created + datetime.timedelta(days=30) You can include `expiry_date` as a field option on a `ModelSerializer` class. @@ -584,7 +584,7 @@ Previously relational fields that were explicitly declared on a serializer class This code *would be valid* in `2.4.3`: class AccountSerializer(serializers.ModelSerializer): - organisations = serializers.SlugRelatedField(slug_field='name') + organizations = serializers.SlugRelatedField(slug_field='name') class Meta: model = Account @@ -593,7 +593,7 @@ However this code *would not be valid* in `2.4.3`: # Missing `queryset` class AccountSerializer(serializers.Serializer): - organisations = serializers.SlugRelatedField(slug_field='name') + organizations = serializers.SlugRelatedField(slug_field='name') def restore_object(self, attrs, instance=None): # ... @@ -602,9 +602,9 @@ The queryset argument is now always required for writable relational fields. This removes some magic and makes it easier and more obvious to move between implicit `ModelSerializer` classes and explicit `Serializer` classes. class AccountSerializer(serializers.ModelSerializer): - organisations = serializers.SlugRelatedField( + organizations = serializers.SlugRelatedField( slug_field='name', - queryset=Organisation.objects.all() + queryset=Organization.objects.all() ) class Meta: @@ -637,7 +637,7 @@ The following usage will *now raise an error*: #### The `UniqueValidator` and `UniqueTogetherValidator` classes. -REST framework now provides two new validators that allow you to ensure field uniqueness, while still using a completely explicit `Serializer` class instead of using `ModelSerializer`. +REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit `Serializer` class instead of using `ModelSerializer`. The `UniqueValidator` should be applied to a serializer field, and takes a single `queryset` argument. @@ -645,11 +645,11 @@ The `UniqueValidator` should be applied to a serializer field, and takes a singl from rest_framework.validators import UniqueValidator class OrganizationSerializer(serializers.Serializer): - url = serializers.HyperlinkedIdentityField(view_name='organisation_detail') + url = serializers.HyperlinkedIdentityField(view_name='organization_detail') created = serializers.DateTimeField(read_only=True) name = serializers.CharField( max_length=100, - validators=UniqueValidator(queryset=Organisation.objects.all()) + validators=UniqueValidator(queryset=Organization.objects.all()) ) The `UniqueTogetherValidator` should be applied to a serializer, and takes a `queryset` argument and a `fields` argument which should be a list or tuple of field names. @@ -664,6 +664,10 @@ The `UniqueTogetherValidator` should be applied to a serializer, and takes a `qu fields=('category', 'position') )] +#### The `UniqueForDateValidator` classes. + +**TODO: Needs documenting.** + ## Generic views #### Simplification of view logic. @@ -700,7 +704,7 @@ I would personally recommend that developers treat view instances as immutable o #### PUT as create. -Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existance of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses. +Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses. Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but we've now opted for the 404 behavior as the default, due to it being simpler and more obvious. @@ -718,6 +722,10 @@ Behavior for dealing with `OPTIONS` requests was previously built directly into This makes it far easier to use a different style for `OPTIONS` responses throughout your API, and makes it possible to create third-party metadata policies. +## Serializers as HTML forms + +**TODO: Document this.** + ## API style There are some improvements in the default style we use in our API responses. @@ -817,6 +825,7 @@ The default JSON renderer will return float objects for uncoerced `Decimal` inst The 3.1 release is planned to address improvements in the following components: +* Public API for using serializers as HTML forms. * Request parsing, mediatypes & the implementation of the browsable API. * Introduction of a new pagination API. * Better support for API versioning. @@ -824,3 +833,5 @@ The 3.1 release is planned to address improvements in the following components: The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API. You can follow development on the GitHub site, where we use [milestones to indicate planning timescales](https://github.com/tomchristie/django-rest-framework/milestones). + +[mixins.py]: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py \ No newline at end of file From 058fea23d3a9776e5fb23b77e81c087d0d8d7e6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Padilla?= <jpadilla@webapplicate.com> Date: Fri, 7 Nov 2014 23:55:42 -0400 Subject: [PATCH 225/249] Fix csrf-ajax link. Closes #2045 --- docs/topics/ajax-csrf-cors.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/topics/ajax-csrf-cors.md b/docs/topics/ajax-csrf-cors.md index 97dd4710b..ad88810da 100644 --- a/docs/topics/ajax-csrf-cors.md +++ b/docs/topics/ajax-csrf-cors.md @@ -10,7 +10,7 @@ If you’re building a JavaScript client to interface with your Web API, you'll AJAX requests that are made within the same context as the API they are interacting with will typically use `SessionAuthentication`. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website. -AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as `TokenAuthentication`. +AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as `TokenAuthentication`. ## CSRF protection @@ -19,7 +19,7 @@ AJAX requests that are made on a different site from the API they are communicat To guard against these type of attacks, you need to do two things: 1. Ensure that the 'safe' HTTP operations, such as `GET`, `HEAD` and `OPTIONS` cannot be used to alter any server-side state. -2. Ensure that any 'unsafe' HTTP operations, such as `POST`, `PUT`, `PATCH` and `DELETE`, always require a valid CSRF token. +2. Ensure that any 'unsafe' HTTP operations, such as `POST`, `PUT`, `PATCH` and `DELETE`, always require a valid CSRF token. If you're using `SessionAuthentication` you'll need to include valid CSRF tokens for any `POST`, `PUT`, `PATCH` or `DELETE` operations. @@ -35,7 +35,7 @@ The best way to deal with CORS in REST framework is to add the required response [cite]: http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html [csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) -[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax +[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/csrf/#ajax [cors]: http://www.w3.org/TR/cors/ [ottoyiu]: https://github.com/ottoyiu/ [django-cors-headers]: https://github.com/ottoyiu/django-cors-headers/ From 440d61ab364da971973ae8d784e77e21e5cdaa7f Mon Sep 17 00:00:00 2001 From: Jochen Van de Velde <jochenvandevelde@gmail.com> Date: Sat, 8 Nov 2014 11:02:48 +0100 Subject: [PATCH 226/249] Fix some typos and other errors --- docs/topics/contributing.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/topics/contributing.md b/docs/topics/contributing.md index 96d9a98c0..6c289938f 100644 --- a/docs/topics/contributing.md +++ b/docs/topics/contributing.md @@ -10,9 +10,9 @@ There are many ways you can contribute to Django REST framework. We'd like it t The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case. -If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular Javascript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with. +If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with. -Other really great ways you can help move the community forward include helping answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag. +Other really great ways you can help move the community forward include helping to answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag. When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant. @@ -33,7 +33,7 @@ Some tips on good issue reporting: * When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing. * Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue. * If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one. -* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintainence overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation. +* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation. * Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened. ## Triaging issues @@ -52,7 +52,7 @@ To start developing on Django REST framework, clone the repo: git clone git@github.com:tomchristie/django-rest-framework.git -Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you setup your editor to automatically indicated non-conforming styles. +Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles. ## Testing @@ -117,7 +117,7 @@ GitHub's documentation for working on pull requests is [available here][pull-req Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django. -Once you've made a pull request take a look at the travis build status in the GitHub interface and make sure the tests are runnning as you'd expect. +Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect. ![Travis status][travis-status] @@ -131,7 +131,7 @@ Sometimes, in order to ensure your code works on various different versions of D The documentation for REST framework is built from the [Markdown][markdown] source files in [the docs directory][docs]. -There are many great markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended. +There are many great Markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended. ## Building the documentation @@ -153,7 +153,7 @@ Some other tips: * Keep paragraphs reasonably short. * Use double spacing after the end of sentences. -* Don't use the abbreviations such as 'e.g.' but instead use long form, such as 'For example'. +* Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'. ## Markdown style @@ -186,7 +186,7 @@ If you are hyperlinking to another REST framework document, you should use a rel [authentication]: ../api-guide/authentication.md -Linking in this style means you'll be able to click the hyperlink in your markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages. +Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages. ##### 3. Notes From f387cd89da55ef88fcac504f5795ea9b591f3fba Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 10 Nov 2014 12:21:27 +0000 Subject: [PATCH 227/249] Uniqueness constraints imply a forced 'required=True'. Refs #1945 --- docs/api-guide/validators.md | 10 ++++ rest_framework/validators.py | 97 +++++++++++++++++++++++++++++------- tests/test_validators.py | 11 ++++ 3 files changed, 101 insertions(+), 17 deletions(-) diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index 6a0ef4ff4..bb073f576 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -93,6 +93,12 @@ The validator should be applied to *serializer classes*, like so: ) ] +--- + +**Note**: The `UniqueTogetherValidation` class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input. + +--- + ## UniqueForDateValidator ## UniqueForMonthValidator @@ -146,6 +152,10 @@ If you want the date field to be entirely hidden from the user, then use `Hidden --- +**Note**: The `UniqueFor<Range>Validation` classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input. + +--- + # Writing custom validators You can use any of Django's existing validators, or write your own custom validators. diff --git a/rest_framework/validators.py b/rest_framework/validators.py index f3773f176..d7f847aaf 100644 --- a/rest_framework/validators.py +++ b/rest_framework/validators.py @@ -25,6 +25,10 @@ class UniqueValidator: self.message = message or self.message def set_context(self, serializer_field): + """ + This hook is called by the serializer instance, + prior to the validation call being made. + """ # 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] @@ -54,6 +58,7 @@ class UniqueTogetherValidator: Should be applied to the serializer class, not to an individual field. """ message = _('The fields {field_names} must make a unique set.') + missing_message = _('This field is required.') def __init__(self, queryset, fields, message=None): self.queryset = queryset @@ -62,17 +67,49 @@ class UniqueTogetherValidator: self.message = message or self.message def set_context(self, serializer): + """ + This hook is called by the serializer instance, + prior to the validation call being made. + """ # Determine the existing instance, if this is an update operation. self.instance = getattr(serializer, 'instance', None) - def __call__(self, attrs): - # Ensure uniqueness. + def enforce_required_fields(self, attrs): + """ + The `UniqueTogetherValidator` always forces an implied 'required' + state on the fields it applies to. + """ + missing = dict([ + (field_name, self.missing_message) + for field_name in self.fields + if field_name not in attrs + ]) + if missing: + raise ValidationError(missing) + + def filter_queryset(self, attrs, queryset): + """ + Filter the queryset to all instances matching the given attributes. + """ filter_kwargs = dict([ (field_name, attrs[field_name]) for field_name in self.fields ]) - queryset = self.queryset.filter(**filter_kwargs) + return queryset.filter(**filter_kwargs) + + def exclude_current_instance(self, attrs, queryset): + """ + If an instance is being updated, then do not include + that instance itself as a uniqueness conflict. + """ if self.instance is not None: - queryset = queryset.exclude(pk=self.instance.pk) + return queryset.exclude(pk=self.instance.pk) + return queryset + + def __call__(self, attrs): + self.enforce_required_fields(attrs) + queryset = self.queryset + queryset = self.filter_queryset(attrs, queryset) + queryset = self.exclude_current_instance(attrs, queryset) if queryset.exists(): field_names = ', '.join(self.fields) raise ValidationError(self.message.format(field_names=field_names)) @@ -87,6 +124,7 @@ class UniqueTogetherValidator: class BaseUniqueForValidator: message = None + missing_message = _('This field is required.') def __init__(self, queryset, field, date_field, message=None): self.queryset = queryset @@ -95,6 +133,10 @@ class BaseUniqueForValidator: self.message = message or self.message def set_context(self, serializer): + """ + This hook is called by the serializer instance, + prior to the validation call being made. + """ # 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] @@ -102,15 +144,36 @@ class BaseUniqueForValidator: # Determine the existing instance, if this is an update operation. self.instance = getattr(serializer, 'instance', None) - def get_filter_kwargs(self, attrs): - raise NotImplementedError('`get_filter_kwargs` must be implemented.') + def enforce_required_fields(self, attrs): + """ + The `UniqueFor<Range>Validator` classes always force an implied + 'required' state on the fields they are applied to. + """ + missing = dict([ + (field_name, self.missing_message) + for field_name in [self.field, self.date_field] + if field_name not in attrs + ]) + if missing: + raise ValidationError(missing) + + def filter_queryset(self, attrs, queryset): + raise NotImplementedError('`filter_queryset` must be implemented.') + + def exclude_current_instance(self, attrs, queryset): + """ + If an instance is being updated, then do not include + that instance itself as a uniqueness conflict. + """ + if self.instance is not None: + return queryset.exclude(pk=self.instance.pk) + return queryset def __call__(self, attrs): - filter_kwargs = self.get_filter_kwargs(attrs) - - queryset = self.queryset.filter(**filter_kwargs) - if self.instance is not None: - queryset = queryset.exclude(pk=self.instance.pk) + self.enforce_required_fields(attrs) + queryset = self.queryset + queryset = self.filter_queryset(attrs, queryset) + queryset = self.exclude_current_instance(attrs, queryset) if queryset.exists(): message = self.message.format(date_field=self.date_field) raise ValidationError({self.field: message}) @@ -127,7 +190,7 @@ class BaseUniqueForValidator: class UniqueForDateValidator(BaseUniqueForValidator): message = _('This field must be unique for the "{date_field}" date.') - def get_filter_kwargs(self, attrs): + def filter_queryset(self, attrs, queryset): value = attrs[self.field] date = attrs[self.date_field] @@ -136,30 +199,30 @@ class UniqueForDateValidator(BaseUniqueForValidator): 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 filter_kwargs + return queryset.filter(**filter_kwargs) class UniqueForMonthValidator(BaseUniqueForValidator): message = _('This field must be unique for the "{date_field}" month.') - def get_filter_kwargs(self, attrs): + def filter_queryset(self, attrs, queryset): value = attrs[self.field] date = attrs[self.date_field] filter_kwargs = {} filter_kwargs[self.field_name] = value filter_kwargs['%s__month' % self.date_field_name] = date.month - return filter_kwargs + return queryset.filter(**filter_kwargs) class UniqueForYearValidator(BaseUniqueForValidator): message = _('This field must be unique for the "{date_field}" year.') - def get_filter_kwargs(self, attrs): + def filter_queryset(self, attrs, queryset): value = attrs[self.field] date = attrs[self.date_field] filter_kwargs = {} filter_kwargs[self.field_name] = value filter_kwargs['%s__year' % self.date_field_name] = date.year - return filter_kwargs + return queryset.filter(**filter_kwargs) diff --git a/tests/test_validators.py b/tests/test_validators.py index e6e0b23a8..86614b109 100644 --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -134,6 +134,17 @@ class TestUniquenessTogetherValidation(TestCase): 'position': 1 } + def test_unique_together_is_required(self): + """ + In a unique together validation, all fields are required. + """ + data = {'position': 2} + serializer = UniquenessTogetherSerializer(data=data, partial=True) + assert not serializer.is_valid() + assert serializer.errors == { + 'race_name': ['This field is required.'] + } + def test_ignore_excluded_fields(self): """ When model fields are not included in a serializer, then uniqueness From fd7db776addbd5e30f132fe6846ec5c5caab5c40 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 10 Nov 2014 12:32:03 +0000 Subject: [PATCH 228/249] Bring UniqueValidator implementation in line with other uniquness validators. --- docs/api-guide/validators.md | 6 +++--- rest_framework/validators.py | 22 ++++++++++++++++++---- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index bb073f576..a50636bcc 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -16,9 +16,9 @@ Validation in Django REST framework serializers is handled a little differently With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons: -* It introduces a proper separation of concerns, making your code behaviour more obvious. -* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behaviour being used for `ModelSerializer` is simple to replicate. -* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behaviour being called on the model instance. +* It introduces a proper separation of concerns, making your code behavior more obvious. +* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate. +* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance. When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using a `Serializer` classes instead, then you need to define the validation rules explicitly. diff --git a/rest_framework/validators.py b/rest_framework/validators.py index d7f847aaf..fa4f18474 100644 --- a/rest_framework/validators.py +++ b/rest_framework/validators.py @@ -35,12 +35,26 @@ class UniqueValidator: # Determine the existing instance, if this is an update operation. self.instance = getattr(serializer_field.parent, 'instance', None) - def __call__(self, value): - # Ensure uniqueness. + def filter_queryset(self, value, queryset): + """ + Filter the queryset to all instances matching the given attribute. + """ filter_kwargs = {self.field_name: value} - queryset = self.queryset.filter(**filter_kwargs) + return queryset.filter(**filter_kwargs) + + def exclude_current_instance(self, queryset): + """ + If an instance is being updated, then do not include + that instance itself as a uniqueness conflict. + """ if self.instance is not None: - queryset = queryset.exclude(pk=self.instance.pk) + return queryset.exclude(pk=self.instance.pk) + return queryset + + def __call__(self, value): + queryset = self.queryset + queryset = self.filter_queryset(value, queryset) + queryset = self.exclude_current_instance(queryset) if queryset.exists(): raise ValidationError(self.message) From 62ce653c61bb596f7fca99db86280c497c71b7ac Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 10 Nov 2014 14:44:26 +0000 Subject: [PATCH 229/249] Update fields.py --- rest_framework/fields.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 4933d8db6..58482db55 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1106,7 +1106,7 @@ class HiddenField(Field): A hidden field does not take input from the user, or present any output, but it does populate a field in `validated_data`, based on its default value. This is particularly useful when we have a `unique_for_date` - constrain on a pair of fields, as we need some way to include the date in + constraint on a pair of fields, as we need some way to include the date in the validated data. """ def __init__(self, **kwargs): From 9521b697110f35187669e501c4fb89036c73c640 Mon Sep 17 00:00:00 2001 From: Kevin London <kevinlondon@gmail.com> Date: Mon, 10 Nov 2014 11:08:39 -0800 Subject: [PATCH 230/249] #2054: Update exceptions to allow custom detail This addresses the changes requested in #2054 and allows for custom messages that do not necessarily require a string formatter be present in the detail message. --- rest_framework/exceptions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py index 388d3dee9..0b06d6e60 100644 --- a/rest_framework/exceptions.py +++ b/rest_framework/exceptions.py @@ -70,7 +70,7 @@ class MethodNotAllowed(APIException): default_detail = "Method '%s' not allowed." def __init__(self, method, detail=None): - self.detail = (detail or self.default_detail) % method + self.detail = detail or (self.default_detail % method) class NotAcceptable(APIException): @@ -87,7 +87,7 @@ class UnsupportedMediaType(APIException): default_detail = "Unsupported media type '%s' in request." def __init__(self, media_type, detail=None): - self.detail = (detail or self.default_detail) % media_type + self.detail = detail or (self.default_detail % media_type) class Throttled(APIException): From 1838e18aeea1bfa5f033fb12adbd97e19231c8a1 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 12 Nov 2014 15:38:05 +0000 Subject: [PATCH 231/249] Update html.py --- rest_framework/utils/html.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/utils/html.py b/rest_framework/utils/html.py index 15e83b3b4..c7af22843 100644 --- a/rest_framework/utils/html.py +++ b/rest_framework/utils/html.py @@ -36,7 +36,7 @@ def parse_html_list(dictionary, prefix=''): '[0]foo': 'abc', '[0]bar': 'def', '[1]foo': 'hij', - '[2]bar': 'klm', + '[1]bar': 'klm', } --> [ From e70b82b6c890eed5088a8f1b2f3aa642d5218398 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Wed, 12 Nov 2014 15:38:39 +0000 Subject: [PATCH 232/249] Update html.py --- rest_framework/utils/html.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/utils/html.py b/rest_framework/utils/html.py index c7af22843..d773952dc 100644 --- a/rest_framework/utils/html.py +++ b/rest_framework/utils/html.py @@ -72,7 +72,7 @@ def parse_html_dict(dictionary, prefix): --> { 'profile': { - 'username': 'example, + 'username': 'example', 'email': 'example@example.com' } } From 03310cc33ae800a36f17a421c8114e0e6616ccb6 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 13 Nov 2014 12:06:45 +0000 Subject: [PATCH 233/249] Add PyPI version badge. --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 394d7fcf4..c86bb65ff 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # Django REST framework [![build-status-image]][travis] +[![pypi-version]][pypi] **Awesome web-browseable Web APIs.** @@ -181,6 +182,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master [travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master +[pypi-version]: https://pypip.in/version/djangorestframework/badge.svg +[pypi]: https://pypi.python.org/pypi/djangorestframework [twitter]: https://twitter.com/_tomchristie [group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework [0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X From e5cd693e7b76fe497d10f4bcd447c3a319466efc Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 13 Nov 2014 16:07:25 +0000 Subject: [PATCH 234/249] Remove test cruft --- tests/accounts/__init__.py | 0 tests/accounts/models.py | 8 -------- tests/accounts/serializers.py | 11 ----------- tests/conftest.py | 3 --- tests/put_as_create_workspace.txt | 33 ------------------------------- tests/records/__init__.py | 0 tests/records/models.py | 6 ------ tests/settings.py | 3 --- tests/test_serializer_import.py | 19 ------------------ tests/users/__init__.py | 0 tests/users/models.py | 6 ------ tests/users/serializers.py | 8 -------- 12 files changed, 97 deletions(-) delete mode 100644 tests/accounts/__init__.py delete mode 100644 tests/accounts/models.py delete mode 100644 tests/accounts/serializers.py delete mode 100644 tests/put_as_create_workspace.txt delete mode 100644 tests/records/__init__.py delete mode 100644 tests/records/models.py delete mode 100644 tests/test_serializer_import.py delete mode 100644 tests/users/__init__.py delete mode 100644 tests/users/models.py delete mode 100644 tests/users/serializers.py diff --git a/tests/accounts/__init__.py b/tests/accounts/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/accounts/models.py b/tests/accounts/models.py deleted file mode 100644 index 3bf4a0c3c..000000000 --- a/tests/accounts/models.py +++ /dev/null @@ -1,8 +0,0 @@ -from django.db import models - -from tests.users.models import User - - -class Account(models.Model): - owner = models.ForeignKey(User, related_name='accounts_owned') - admins = models.ManyToManyField(User, blank=True, null=True, related_name='accounts_administered') diff --git a/tests/accounts/serializers.py b/tests/accounts/serializers.py deleted file mode 100644 index 57a91b92c..000000000 --- a/tests/accounts/serializers.py +++ /dev/null @@ -1,11 +0,0 @@ -from rest_framework import serializers - -from tests.accounts.models import Account -from tests.users.serializers import UserSerializer - - -class AccountSerializer(serializers.ModelSerializer): - admins = UserSerializer(many=True) - - class Meta: - model = Account diff --git a/tests/conftest.py b/tests/conftest.py index 4b33e19c1..31142eaf9 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -33,9 +33,6 @@ def pytest_configure(): 'rest_framework', 'rest_framework.authtoken', 'tests', - 'tests.accounts', - 'tests.records', - 'tests.users', ), PASSWORD_HASHERS=( 'django.contrib.auth.hashers.SHA1PasswordHasher', diff --git a/tests/put_as_create_workspace.txt b/tests/put_as_create_workspace.txt deleted file mode 100644 index 6bc5218eb..000000000 --- a/tests/put_as_create_workspace.txt +++ /dev/null @@ -1,33 +0,0 @@ -# From test_validation... - -class TestPreSaveValidationExclusions(TestCase): - def test_pre_save_validation_exclusions(self): - """ - Somewhat weird test case to ensure that we don't perform model - validation on read only fields. - """ - obj = ValidationModel.objects.create(blank_validated_field='') - request = factory.put('/', {}, format='json') - view = UpdateValidationModel().as_view() - response = view(request, pk=obj.pk).render() - self.assertEqual(response.status_code, status.HTTP_200_OK) - - -# From test_permissions... - -class ModelPermissionsIntegrationTests(TestCase): - def setUp(...): - ... - - def test_has_put_as_create_permissions(self): - # User only has update permissions - should be able to update an entity. - request = factory.put('/1', {'text': 'foobar'}, format='json', - HTTP_AUTHORIZATION=self.updateonly_credentials) - response = instance_view(request, pk='1') - self.assertEqual(response.status_code, status.HTTP_200_OK) - - # But if PUTing to a new entity, permission should be denied. - request = factory.put('/2', {'text': 'foobar'}, format='json', - HTTP_AUTHORIZATION=self.updateonly_credentials) - response = instance_view(request, pk='2') - self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) diff --git a/tests/records/__init__.py b/tests/records/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/records/models.py b/tests/records/models.py deleted file mode 100644 index 769548074..000000000 --- a/tests/records/models.py +++ /dev/null @@ -1,6 +0,0 @@ -from django.db import models - - -class Record(models.Model): - account = models.ForeignKey('accounts.Account', blank=True, null=True) - owner = models.ForeignKey('users.User', blank=True, null=True) diff --git a/tests/settings.py b/tests/settings.py index 91c9ed09e..b6736199c 100644 --- a/tests/settings.py +++ b/tests/settings.py @@ -96,9 +96,6 @@ INSTALLED_APPS = ( 'rest_framework', 'rest_framework.authtoken', 'tests', - 'tests.accounts', - 'tests.records', - 'tests.users', ) # OAuth is optional and won't work if there is no oauth_provider & oauth2 diff --git a/tests/test_serializer_import.py b/tests/test_serializer_import.py deleted file mode 100644 index d029c3c55..000000000 --- a/tests/test_serializer_import.py +++ /dev/null @@ -1,19 +0,0 @@ -# from django.test import TestCase - -# from rest_framework import serializers -# from tests.accounts.serializers import AccountSerializer - - -# class ImportingModelSerializerTests(TestCase): -# """ -# In some situations like, GH #1225, it is possible, especially in -# testing, to import a serializer who's related models have not yet -# been resolved by Django. `AccountSerializer` is an example of such -# a serializer (imported at the top of this file). -# """ -# def test_import_model_serializer(self): -# """ -# The serializer at the top of this file should have been -# imported successfully, and we should be able to instantiate it. -# """ -# self.assertIsInstance(AccountSerializer(), serializers.ModelSerializer) diff --git a/tests/users/__init__.py b/tests/users/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/users/models.py b/tests/users/models.py deleted file mode 100644 index 128bac90b..000000000 --- a/tests/users/models.py +++ /dev/null @@ -1,6 +0,0 @@ -from django.db import models - - -class User(models.Model): - account = models.ForeignKey('accounts.Account', blank=True, null=True, related_name='users') - active_record = models.ForeignKey('records.Record', blank=True, null=True) diff --git a/tests/users/serializers.py b/tests/users/serializers.py deleted file mode 100644 index 4893ddb34..000000000 --- a/tests/users/serializers.py +++ /dev/null @@ -1,8 +0,0 @@ -from rest_framework import serializers - -from tests.users.models import User - - -class UserSerializer(serializers.ModelSerializer): - class Meta: - model = User From 502a86cedb2ed3844c61f0cb3a7663082395356f Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 13 Nov 2014 16:10:48 +0000 Subject: [PATCH 235/249] Remove tests/settings. Using conftest instead. --- tests/settings.py | 162 ---------------------------------------------- 1 file changed, 162 deletions(-) delete mode 100644 tests/settings.py diff --git a/tests/settings.py b/tests/settings.py deleted file mode 100644 index b6736199c..000000000 --- a/tests/settings.py +++ /dev/null @@ -1,162 +0,0 @@ -# Django settings for testproject project. - -DEBUG = True -TEMPLATE_DEBUG = DEBUG -DEBUG_PROPAGATE_EXCEPTIONS = True - -ALLOWED_HOSTS = ['*'] - -ADMINS = ( - # ('Your Name', 'your_email@domain.com'), -) - -MANAGERS = ADMINS - -DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. - 'NAME': 'sqlite.db', # Or path to database file if using sqlite3. - 'USER': '', # Not used with sqlite3. - 'PASSWORD': '', # Not used with sqlite3. - 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. - 'PORT': '', # Set to empty string for default. Not used with sqlite3. - } -} - -CACHES = { - 'default': { - 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', - } -} - -# Local time zone for this installation. Choices can be found here: -# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name -# although not all choices may be available on all operating systems. -# On Unix systems, a value of None will cause Django to use the same -# timezone as the operating system. -# If running in a Windows environment this must be set to the same as your -# system time zone. -TIME_ZONE = 'Europe/London' - -# Language code for this installation. All choices can be found here: -# http://www.i18nguy.com/unicode/language-identifiers.html -LANGUAGE_CODE = 'en-uk' - -SITE_ID = 1 - -# If you set this to False, Django will make some optimizations so as not -# to load the internationalization machinery. -USE_I18N = True - -# If you set this to False, Django will not format dates, numbers and -# calendars according to the current locale -USE_L10N = True - -# Absolute filesystem path to the directory that will hold user-uploaded files. -# Example: "/home/media/media.lawrence.com/" -MEDIA_ROOT = '' - -# URL that handles the media served from MEDIA_ROOT. Make sure to use a -# trailing slash if there is a path component (optional in other cases). -# Examples: "http://media.lawrence.com", "http://example.com/media/" -MEDIA_URL = '' - -# Make this unique, and don't share it with anybody. -SECRET_KEY = 'u@x-aj9(hoh#rb-^ymf#g2jx_hp0vj7u5#b@ag1n^seu9e!%cy' - -# List of callables that know how to import templates from various sources. -TEMPLATE_LOADERS = ( - 'django.template.loaders.filesystem.Loader', - 'django.template.loaders.app_directories.Loader', -) - -MIDDLEWARE_CLASSES = ( - 'django.middleware.common.CommonMiddleware', - 'django.contrib.sessions.middleware.SessionMiddleware', - 'django.middleware.csrf.CsrfViewMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'django.contrib.messages.middleware.MessageMiddleware', -) - -ROOT_URLCONF = 'tests.urls' - -TEMPLATE_DIRS = ( - # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". - # Always use forward slashes, even on Windows. - # Don't forget to use absolute paths, not relative paths. -) - -INSTALLED_APPS = ( - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', - 'django.contrib.sites', - 'django.contrib.messages', - 'django.contrib.staticfiles', - 'rest_framework', - 'rest_framework.authtoken', - 'tests', -) - -# OAuth is optional and won't work if there is no oauth_provider & oauth2 -try: - import oauth_provider # NOQA - import oauth2 # NOQA -except ImportError: - pass -else: - INSTALLED_APPS += ( - 'oauth_provider', - ) - -try: - import provider # NOQA -except ImportError: - pass -else: - INSTALLED_APPS += ( - 'provider', - 'provider.oauth2', - ) - -# guardian is optional -try: - import guardian # NOQA -except ImportError: - pass -else: - ANONYMOUS_USER_ID = -1 - AUTHENTICATION_BACKENDS = ( - 'django.contrib.auth.backends.ModelBackend', # default - 'guardian.backends.ObjectPermissionBackend', - ) - INSTALLED_APPS += ( - 'guardian', - ) - -STATIC_URL = '/static/' - -PASSWORD_HASHERS = ( - 'django.contrib.auth.hashers.SHA1PasswordHasher', - 'django.contrib.auth.hashers.PBKDF2PasswordHasher', - 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', - 'django.contrib.auth.hashers.BCryptPasswordHasher', - 'django.contrib.auth.hashers.MD5PasswordHasher', - 'django.contrib.auth.hashers.CryptPasswordHasher', -) - -AUTH_USER_MODEL = 'auth.User' - -import django - -if django.VERSION < (1, 3): - INSTALLED_APPS += ('staticfiles',) - - -# If we're running on the Jenkins server we want to archive the coverage reports as XML. -import os -if os.environ.get('HUDSON_URL', None): - TEST_RUNNER = 'xmlrunner.extra.djangotestrunner.XMLTestRunner' - TEST_OUTPUT_VERBOSE = True - TEST_OUTPUT_DESCRIPTIONS = True - TEST_OUTPUT_DIR = 'xmlrunner' From 9e75c4d8eab11d1637d65a8a7683f7970a41111b Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 13 Nov 2014 16:24:03 +0000 Subject: [PATCH 236/249] Reinstate OPTIONS tests --- tests/test_permissions.py | 96 +++++++++++++++++++-------------------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/tests/test_permissions.py b/tests/test_permissions.py index ac398f80d..97bac33db 100644 --- a/tests/test_permissions.py +++ b/tests/test_permissions.py @@ -95,59 +95,59 @@ class ModelPermissionsIntegrationTests(TestCase): response = instance_view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) - # def test_options_permitted(self): - # request = factory.options( - # '/', - # HTTP_AUTHORIZATION=self.permitted_credentials - # ) - # response = root_view(request, pk='1') - # self.assertEqual(response.status_code, status.HTTP_200_OK) - # self.assertIn('actions', response.data) - # self.assertEqual(list(response.data['actions'].keys()), ['POST']) + def test_options_permitted(self): + request = factory.options( + '/', + HTTP_AUTHORIZATION=self.permitted_credentials + ) + response = root_view(request, pk='1') + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertIn('actions', response.data) + self.assertEqual(list(response.data['actions'].keys()), ['POST']) - # request = factory.options( - # '/1', - # HTTP_AUTHORIZATION=self.permitted_credentials - # ) - # response = instance_view(request, pk='1') - # self.assertEqual(response.status_code, status.HTTP_200_OK) - # self.assertIn('actions', response.data) - # self.assertEqual(list(response.data['actions'].keys()), ['PUT']) + request = factory.options( + '/1', + HTTP_AUTHORIZATION=self.permitted_credentials + ) + response = instance_view(request, pk='1') + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertIn('actions', response.data) + self.assertEqual(list(response.data['actions'].keys()), ['PUT']) - # def test_options_disallowed(self): - # request = factory.options( - # '/', - # HTTP_AUTHORIZATION=self.disallowed_credentials - # ) - # response = root_view(request, pk='1') - # self.assertEqual(response.status_code, status.HTTP_200_OK) - # self.assertNotIn('actions', response.data) + def test_options_disallowed(self): + request = factory.options( + '/', + HTTP_AUTHORIZATION=self.disallowed_credentials + ) + response = root_view(request, pk='1') + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertNotIn('actions', response.data) - # request = factory.options( - # '/1', - # HTTP_AUTHORIZATION=self.disallowed_credentials - # ) - # response = instance_view(request, pk='1') - # self.assertEqual(response.status_code, status.HTTP_200_OK) - # self.assertNotIn('actions', response.data) + request = factory.options( + '/1', + HTTP_AUTHORIZATION=self.disallowed_credentials + ) + response = instance_view(request, pk='1') + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertNotIn('actions', response.data) - # def test_options_updateonly(self): - # request = factory.options( - # '/', - # HTTP_AUTHORIZATION=self.updateonly_credentials - # ) - # response = root_view(request, pk='1') - # self.assertEqual(response.status_code, status.HTTP_200_OK) - # self.assertNotIn('actions', response.data) + def test_options_updateonly(self): + request = factory.options( + '/', + HTTP_AUTHORIZATION=self.updateonly_credentials + ) + response = root_view(request, pk='1') + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertNotIn('actions', response.data) - # request = factory.options( - # '/1', - # HTTP_AUTHORIZATION=self.updateonly_credentials - # ) - # response = instance_view(request, pk='1') - # self.assertEqual(response.status_code, status.HTTP_200_OK) - # self.assertIn('actions', response.data) - # self.assertEqual(list(response.data['actions'].keys()), ['PUT']) + request = factory.options( + '/1', + HTTP_AUTHORIZATION=self.updateonly_credentials + ) + response = instance_view(request, pk='1') + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertIn('actions', response.data) + self.assertEqual(list(response.data['actions'].keys()), ['PUT']) class BasicPermModel(models.Model): From ea98de9b889173235a908ee2ce5a2aba5d8223c7 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 13 Nov 2014 19:28:57 +0000 Subject: [PATCH 237/249] Model fields with .blank or .null now map to required=False. Closes #2017. Closes #2021. --- docs/topics/3.0-announcement.md | 6 +++--- rest_framework/utils/field_mapping.py | 2 +- tests/test_model_serializer.py | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index d3da0607e..885fc183e 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -506,9 +506,9 @@ We now use the following: REST framework now has more explicit and clear control over validating empty values for fields. -Previously the meaning of the `required=False` keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be `None`. +Previously the meaning of the `required=False` keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be `None` or the empty string. -We now have a better separation, with separate `required` and `allow_none` arguments. +We now have a better separation, with separate `required`, `allow_none` and `allow_blank` arguments. The following set of arguments are used to control validation of empty values: @@ -519,7 +519,7 @@ The following set of arguments are used to control validation of empty values: Typically you'll want to use `required=False` if the corresponding model field has a default value, and additionally set either `allow_none=True` or `allow_blank=True` if required. -The `default` argument is there if you need it, but you'll more typically want defaults to be set on model fields, rather than serializer fields. +The `default` argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the `required` argument when a default is specified, and doing so will result in an error. #### Coercing output types. diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index 246390853..ce339971f 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -88,7 +88,7 @@ def get_field_kwargs(field_name, model_field): kwargs['read_only'] = True return kwargs - if model_field.has_default(): + if model_field.has_default() or model_field.blank or model_field.null: kwargs['required'] = False if model_field.flatchoices: diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index b8b621be8..3aec0da0c 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -90,7 +90,7 @@ class TestRegularFieldMappings(TestCase): email_field = EmailField(max_length=100) float_field = FloatField() integer_field = IntegerField() - null_boolean_field = NullBooleanField() + null_boolean_field = NullBooleanField(required=False) positive_integer_field = IntegerField() positive_small_integer_field = IntegerField() slug_field = SlugField(max_length=100) @@ -112,8 +112,8 @@ class TestRegularFieldMappings(TestCase): id = IntegerField(label='ID', read_only=True) value_limit_field = IntegerField(max_value=10, min_value=1) length_limit_field = CharField(max_length=12, min_length=3) - blank_field = CharField(allow_blank=True, max_length=10) - null_field = IntegerField(allow_null=True) + blank_field = CharField(allow_blank=True, max_length=10, required=False) + 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')]) From fd97d9bff82b96b9362930686b9008ba78326115 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 13 Nov 2014 19:35:03 +0000 Subject: [PATCH 238/249] Use select inputs for relationships. Closes #2058. --- rest_framework/relations.py | 12 ++++++------ rest_framework/renderers.py | 5 ++++- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 48ddf41e0..6dc02a11b 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -34,13 +34,13 @@ class RelatedField(Field): def __new__(cls, *args, **kwargs): # We override this method in order to automagically create - # `ManyRelation` classes instead when `many=True` is set. + # `ManyRelatedField` classes instead when `many=True` is set. if kwargs.pop('many', False): list_kwargs = {'child_relation': cls(*args, **kwargs)} for key in kwargs.keys(): if key in MANY_RELATION_KWARGS: list_kwargs[key] = kwargs[key] - return ManyRelation(**list_kwargs) + return ManyRelatedField(**list_kwargs) return super(RelatedField, cls).__new__(cls, *args, **kwargs) def run_validation(self, data=empty): @@ -286,12 +286,12 @@ class SlugRelatedField(RelatedField): return getattr(obj, self.slug_field) -class ManyRelation(Field): +class ManyRelatedField(Field): """ Relationships with `many=True` transparently get coerced into instead being - a ManyRelation with a child relationship. + a ManyRelatedField with a child relationship. - The `ManyRelation` class is responsible for handling iterating through + The `ManyRelatedField` class is responsible for handling iterating through the values and passing each one to the child relationship. You shouldn't need to be using this class directly yourself. @@ -302,7 +302,7 @@ class ManyRelation(Field): def __init__(self, child_relation=None, *args, **kwargs): self.child_relation = child_relation assert child_relation is not None, '`child_relation` is a required argument.' - super(ManyRelation, self).__init__(*args, **kwargs) + super(ManyRelatedField, self).__init__(*args, **kwargs) self.child_relation.bind(field_name='', parent=self) def get_value(self, dictionary): diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index b56f99db9..eb04e81e1 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -383,7 +383,10 @@ class HTMLFormRenderer(BaseRenderer): serializers.MultipleChoiceField: { 'base_template': 'select_multiple.html', # Also valid: 'checkbox_multiple.html' }, - serializers.ManyRelation: { + serializers.RelatedField: { + 'base_template': 'select.html', # Also valid: 'radio.html' + }, + serializers.ManyRelatedField: { 'base_template': 'select_multiple.html', # Also valid: 'checkbox_multiple.html' }, serializers.Serializer: { From 78a741be27f5007d6fa2f73c6cedf04bfe638f9c Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 13 Nov 2014 20:24:48 +0000 Subject: [PATCH 239/249] Split out .create and .update on ListSerializer --- rest_framework/serializers.py | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index d83367f40..a4aeeeb79 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -449,26 +449,39 @@ class ListSerializer(BaseSerializer): serializer=self ) + def update(self, instance, validated_data): + raise NotImplementedError( + "Serializers with many=True do not support multiple update by " + "default, only multiple create. For updates it is unclear how to " + "deal with insertions and deletions. If you need to support " + "multiple update, use a `ListSerializer` class and override " + "`.update()` so you can specify the behavior exactly." + ) + + def create(self, validated_data): + return [ + self.child.create(attrs) for attrs in validated_data + ] + def save(self, **kwargs): """ Save and return a list of object instances. """ - assert self.instance is None, ( - "Serializers do not support multiple update by default, only " - "multiple create. For updates it is unclear how to deal with " - "insertions and deletions. If you need to support multiple update, " - "use a `ListSerializer` class and override `.save()` so you can " - "specify the behavior exactly." - ) - validated_data = [ dict(list(attrs.items()) + list(kwargs.items())) for attrs in self.validated_data ] - self.instance = [ - self.child.create(attrs) for attrs in validated_data - ] + if self.instance is not None: + self.instance = self.update(self.instance, validated_data) + assert self.instance is not None, ( + '`update()` did not return an object instance.' + ) + else: + self.instance = self.create(validated_data) + assert self.instance is not None, ( + '`create()` did not return an object instance.' + ) return self.instance From 992330055eeb5d787ddd7d62dfc9121a2256fd9b Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 13 Nov 2014 21:11:13 +0000 Subject: [PATCH 240/249] Refactor many --- rest_framework/relations.py | 22 +++++++++++++++++----- rest_framework/serializers.py | 25 ++++++++++++++++++++----- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 6dc02a11b..79c8057b6 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -10,9 +10,17 @@ from django.utils.translation import ugettext_lazy as _ class PKOnlyObject(object): + """ + This is a mock object, used for when we only need the pk of the object + instance, but still want to return an object with a .pk attribute, + in order to keep the same interface as a regular model instance. + """ def __init__(self, pk): self.pk = pk + +# We assume that 'validators' are intended for the child serializer, +# rather than the parent serializer. MANY_RELATION_KWARGS = ( 'read_only', 'write_only', 'required', 'default', 'initial', 'source', 'label', 'help_text', 'style', 'error_messages' @@ -36,13 +44,17 @@ class RelatedField(Field): # We override this method in order to automagically create # `ManyRelatedField` classes instead when `many=True` is set. if kwargs.pop('many', False): - list_kwargs = {'child_relation': cls(*args, **kwargs)} - for key in kwargs.keys(): - if key in MANY_RELATION_KWARGS: - list_kwargs[key] = kwargs[key] - return ManyRelatedField(**list_kwargs) + return cls.many_init(*args, **kwargs) return super(RelatedField, cls).__new__(cls, *args, **kwargs) + @classmethod + def many_init(cls, *args, **kwargs): + list_kwargs = {'child_relation': cls(*args, **kwargs)} + for key in kwargs.keys(): + if key in MANY_RELATION_KWARGS: + list_kwargs[key] = kwargs[key] + return ManyRelatedField(**list_kwargs) + def run_validation(self, data=empty): # We force empty strings to None values for relational fields. if data == '': diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index a4aeeeb79..70bba8ab2 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -46,6 +46,9 @@ import warnings from rest_framework.relations import * # NOQA from rest_framework.fields import * # NOQA + +# We assume that 'validators' are intended for the child serializer, +# rather than the parent serializer. LIST_SERIALIZER_KWARGS = ( 'read_only', 'write_only', 'required', 'default', 'initial', 'source', 'label', 'help_text', 'style', 'error_messages', @@ -73,13 +76,25 @@ class BaseSerializer(Field): # We override this method in order to automagically create # `ListSerializer` classes instead when `many=True` is set. if kwargs.pop('many', False): - list_kwargs = {'child': cls(*args, **kwargs)} - for key in kwargs.keys(): - if key in LIST_SERIALIZER_KWARGS: - list_kwargs[key] = kwargs[key] - return ListSerializer(*args, **list_kwargs) + return cls.many_init(*args, **kwargs) return super(BaseSerializer, cls).__new__(cls, *args, **kwargs) + @classmethod + def many_init(cls, *args, **kwargs): + """ + This method implements the creation of a `ListSerializer` parent + class when `many=True` is used. You can customize it if you need to + control which keyword arguments are passed to the parent, and + which are passed to the child. + """ + child_serializer = cls(*args, **kwargs) + list_kwargs = {'child': child_serializer} + list_kwargs.update(dict([ + (key, value) for key, value in kwargs.items() + if key in LIST_SERIALIZER_KWARGS + ])) + return ListSerializer(*args, **list_kwargs) + def to_internal_value(self, data): raise NotImplementedError('`to_internal_value()` must be implemented.') From 7394dcec9e625e7eee5c041276f81745359ed7c4 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 13 Nov 2014 23:05:44 +0000 Subject: [PATCH 241/249] ReturnList and ReturnDict wrapped at nicer point --- rest_framework/serializers.py | 53 ++++++++++++++++++++++++++--------- 1 file changed, 40 insertions(+), 13 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 70bba8ab2..e7e93f380 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -245,18 +245,18 @@ class Serializer(BaseSerializer): def get_initial(self): if self._initial_data is not None: - return ReturnDict([ + return OrderedDict([ (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 and not field.read_only - ], serializer=self) + ]) - return ReturnDict([ + return OrderedDict([ (field.field_name, field.get_initial()) for field in self.fields.values() if not field.read_only - ], serializer=self) + ]) def get_value(self, dictionary): # We override the default field access in order to support @@ -319,8 +319,8 @@ class Serializer(BaseSerializer): """ Dict of native values <- Dict of primitive datatypes. """ - ret = {} - errors = ReturnDict(serializer=self) + ret = OrderedDict() + errors = OrderedDict() fields = [ field for field in self.fields.values() if (not field.read_only) or (field.default is not empty) @@ -349,7 +349,7 @@ class Serializer(BaseSerializer): """ Object instance -> Dict of primitive datatypes. """ - ret = ReturnDict(serializer=self) + ret = OrderedDict() fields = [field for field in self.fields.values() if not field.write_only] for field in fields: @@ -388,6 +388,19 @@ class Serializer(BaseSerializer): return NestedBoundField(field, value, error) return BoundField(field, value, error) + # Include a backlink to the serializer class on return objects. + # Allows renderers such as HTMLFormRenderer to get the full field info. + + @property + def data(self): + ret = super(Serializer, self).data + return ReturnDict(ret, serializer=self) + + @property + def errors(self): + ret = super(Serializer, self).errors + return ReturnDict(ret, serializer=self) + # There's some replication of `ListField` here, # but that's probably better than obfuscating the call hierarchy. @@ -410,7 +423,7 @@ class ListSerializer(BaseSerializer): def get_initial(self): if self._initial_data is not None: return self.to_representation(self._initial_data) - return ReturnList(serializer=self) + return [] def get_value(self, dictionary): """ @@ -438,7 +451,7 @@ class ListSerializer(BaseSerializer): }) ret = [] - errors = ReturnList(serializer=self) + errors = [] for item in data: try: @@ -459,10 +472,9 @@ class ListSerializer(BaseSerializer): List of object instances -> List of dicts of primitive datatypes. """ iterable = data.all() if (hasattr(data, 'all')) else data - return ReturnList( - [self.child.to_representation(item) for item in iterable], - serializer=self - ) + return [ + self.child.to_representation(item) for item in iterable + ] def update(self, instance, validated_data): raise NotImplementedError( @@ -503,6 +515,21 @@ class ListSerializer(BaseSerializer): def __repr__(self): return representation.list_repr(self, indent=1) + # Include a backlink to the serializer class on return objects. + # Allows renderers such as HTMLFormRenderer to get the full field info. + + @property + def data(self): + ret = super(ListSerializer, self).data + return ReturnList(ret, serializer=self) + + @property + def errors(self): + ret = super(ListSerializer, self).errors + if isinstance(ret, dict): + return ReturnDict(ret, serializer=self) + return ReturnList(ret, serializer=self) + # ModelSerializer & HyperlinkedModelSerializer # -------------------------------------------- From 4e035184384db8ed1227fdcb1dad2ea6ddb1cf68 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Thu, 13 Nov 2014 23:30:42 +0000 Subject: [PATCH 242/249] required=False for nullable relationships --- rest_framework/utils/field_mapping.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index ce339971f..9c187176d 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -215,7 +215,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(): + if model_field.has_default() or model_field.null: kwargs['required'] = False if model_field.null: kwargs['allow_null'] = True From b001a146d73348af18cfc4c943d87f2f389349c9 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 17 Nov 2014 09:56:20 +0000 Subject: [PATCH 243/249] Add django master to build matrix. Closes #2075. --- .travis.yml | 10 ++++++++++ tox.ini | 24 +++++++++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index a5b6d7d91..4c06acf59 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,6 +20,16 @@ env: - TOX_ENV=py2.6-django1.5 - TOX_ENV=py2.7-django1.4 - TOX_ENV=py2.6-django1.4 + - TOX_ENV=py3.4-djangomaster + - TOX_ENV=py3.3-djangomaster + - TOX_ENV=py2.7-djangomaster + +matrix: + fast_finish: true + allow_failures: + - env: TOX_ENV=py3.4-djangomaster + - env: TOX_ENV=py3.3-djangomaster + - env: TOX_ENV=py2.7-djangomaster install: - "pip install tox --download-cache $HOME/.pip-cache" diff --git a/tox.ini b/tox.ini index d52dd1558..493712a1b 100644 --- a/tox.ini +++ b/tox.ini @@ -5,7 +5,8 @@ envlist = py3.4-django1.7,py3.3-django1.7,py3.2-django1.7,py2.7-django1.7, py3.4-django1.6,py3.3-django1.6,py3.2-django1.6,py2.7-django1.6,py2.6-django1.6, py3.4-django1.5,py3.3-django1.5,py3.2-django1.5,py2.7-django1.5,py2.6-django1.5, - py2.7-django1.4,py2.6-django1.4 + py2.7-django1.4,py2.6-django1.4, + py3.4-djangomaster,py3.3-djangomaster,py2.7-djangomaster [testenv] commands = ./runtests.py --fast @@ -157,3 +158,24 @@ deps = django==1.4.11 django-oauth2-provider==0.2.3 django-guardian==1.2.3 pytest-django==2.6.1 + +[testenv:py3.4-djangomaster] +basepython = python3.4 +deps = https://github.com/django/django/zipball/master + django-filter==0.7 + defusedxml==0.3 + pytest-django==2.6.1 + +[testenv:py3.3-djangomaster] +basepython = python3.3 +deps = https://github.com/django/django/zipball/master + django-filter==0.7 + defusedxml==0.3 + pytest-django==2.6.1 + +[testenv:py2.7-djangomaster] +basepython = python3.2 +deps = https://github.com/django/django/zipball/master + django-filter==0.7 + defusedxml==0.3 + pytest-django==2.6.1 From d08cfb0559033acaefbc23863c43ef858c2c0e1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Padilla?= <jpadilla@webapplicate.com> Date: Mon, 17 Nov 2014 08:17:40 -0400 Subject: [PATCH 244/249] Fix runtests examples Correctly rename runtests examples to work with current runtests.py file. --- docs/topics/contributing.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/topics/contributing.md b/docs/topics/contributing.md index 6c289938f..52f6e287d 100644 --- a/docs/topics/contributing.md +++ b/docs/topics/contributing.md @@ -71,31 +71,31 @@ To run the tests, clone the repository, and then: Run using a more concise output style. - ./runtests -q + ./runtests.py -q Run the tests using a more concise output style, no coverage, no flake8. - ./runtests --fast + ./runtests.py --fast Don't run the flake8 code linting. - ./runtests --nolint + ./runtests.py --nolint Only run the flake8 code linting, don't run the tests. - ./runtests --lintonly + ./runtests.py --lintonly Run the tests for a given test case. - ./runtests MyTestCase + ./runtests.py MyTestCase Run the tests for a given test method. - ./runtests MyTestCase.test_this_method + ./runtests.py MyTestCase.test_this_method Shorter form to run the tests for a given test method. - ./runtests test_this_method + ./runtests.py test_this_method Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input. From 5f580cad523a4133e9805a7dfac4bf239d295a1e Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 17 Nov 2014 18:17:44 +0000 Subject: [PATCH 245/249] Remove class='form-control' for file inputs. Closes #2065. --- rest_framework/templates/rest_framework/horizontal/input.html | 2 +- rest_framework/templates/rest_framework/inline/input.html | 2 +- rest_framework/templates/rest_framework/vertical/input.html | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/rest_framework/templates/rest_framework/horizontal/input.html b/rest_framework/templates/rest_framework/horizontal/input.html index df4aa40fc..c41cd523a 100644 --- a/rest_framework/templates/rest_framework/horizontal/input.html +++ b/rest_framework/templates/rest_framework/horizontal/input.html @@ -3,7 +3,7 @@ <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label> {% endif %} <div class="col-sm-10"> - <input name="{{ field.name }}" class="form-control" type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> + <input name="{{ field.name }}" {% if style.input_type != "file" %}class="form-control"{% endif %} type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> {% if field.errors %} {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} {% endif %} diff --git a/rest_framework/templates/rest_framework/inline/input.html b/rest_framework/templates/rest_framework/inline/input.html index f8ec4faf2..de85ba485 100644 --- a/rest_framework/templates/rest_framework/inline/input.html +++ b/rest_framework/templates/rest_framework/inline/input.html @@ -2,5 +2,5 @@ {% if field.label %} <label class="sr-only">{{ field.label }}</label> {% endif %} - <input name="{{ field.name }}" class="form-control" type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> + <input name="{{ field.name }}" {% if style.input_type != "file" %}class="form-control"{% endif %} type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> </div> diff --git a/rest_framework/templates/rest_framework/vertical/input.html b/rest_framework/templates/rest_framework/vertical/input.html index e1e21ca1f..43cccd3ea 100644 --- a/rest_framework/templates/rest_framework/vertical/input.html +++ b/rest_framework/templates/rest_framework/vertical/input.html @@ -2,7 +2,7 @@ {% if field.label %} <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label> {% endif %} - <input name="{{ field.name }}" class="form-control" type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> + <input name="{{ field.name }}" {% if style.input_type != "file" %}class="form-control"{% endif %} type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}> {% if field.errors %} {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %} {% endif %} From 0f508c58211051c873aae5a2d1c65a0c595e732a Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Mon, 17 Nov 2014 18:36:32 +0000 Subject: [PATCH 246/249] Docs for advanced default argument usage. Closes #1945 --- docs/api-guide/validators.md | 32 ++++++++++++++++++++++++++++++++ rest_framework/fields.py | 11 +++++++++++ 2 files changed, 43 insertions(+) diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index a50636bcc..ac2f32485 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -156,6 +156,38 @@ If you want the date field to be entirely hidden from the user, then use `Hidden --- +# Advanced 'default' argument usage + +Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that *is* available as input to the validator. + +Two patterns that you may want to use for this sort of validation include: + +* Using `HiddenField`. This field will be present in `validated_data` but *will not* be used in the serializer output representation. +* Using a standard field with `read_only=True`, but that also includes a `default=…` argument. This field *will* be used in the serializer output representation, but cannot be set directly by the user. + +REST framework includes a couple of defaults that may be useful in this context. + +#### CurrentUserDefault + +A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer. + + owner = serializers.HiddenField( + default=CurrentUserDefault() + ) + +#### CreateOnlyDefault + +A default class that can be used to *only set a default argument during create operations*. During updates the field is omitted. + +It takes a single argument, which is the default value or callable that should be used during create operations. + + created_at = serializers.DateTimeField( + read_only=True, + default=CreateOnlyDefault(timezone.now) + ) + +--- + # Writing custom validators You can use any of Django's existing validators, or write your own custom validators. diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 58482db55..36afe7a99 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -117,6 +117,17 @@ class CreateOnlyDefault: return '%s(%s)' % (self.__class__.__name__, repr(self.default)) +class CurrentUserDefault: + def set_context(self, serializer_field): + self.user = serializer_field.context['request'].user + + def __call__(self): + return self.user + + def __repr__(self): + return '%s()' % self.__class__.__name__ + + class SkipField(Exception): pass From 5e74f02d61e05d38bf4e22c6227144def2a96128 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Tue, 18 Nov 2014 14:49:00 +0000 Subject: [PATCH 247/249] Note removal of 'save_object' and fail loudly if it exists --- docs/topics/3.0-announcement.md | 2 ++ rest_framework/serializers.py | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 885fc183e..90cbda4d6 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -84,6 +84,8 @@ The resulting API changes are further detailed below. The `.restore_object()` method is now replaced with two separate methods, `.create()` and `.update()`. +These methods also replace the optional `.save_object()` method, which no longer exists. + When using the `.create()` and `.update()` methods you should both create *and save* the object instance. This is in contrast to the previous `.restore_object()` behavior that would instantiate the object but not save it. The following example from the tutorial previously used `restore_object()` to handle both creating and updating object instances. diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index e7e93f380..84282cdb2 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -108,6 +108,13 @@ class BaseSerializer(Field): raise NotImplementedError('`create()` must be implemented.') def save(self, **kwargs): + assert not hasattr(self, 'save_object'), ( + 'Serializer `%s.%s` has old-style version 2 `.save_object()` ' + 'that is no longer compatible with REST framework 3. ' + 'Use the new-style `.create()` and `.update()` methods instead.' % + (self.__class__.__module__, self.__class__.__name__) + ) + validated_data = dict( list(self.validated_data.items()) + list(kwargs.items()) From 084354d3ebf3949f8c1664d68da4a568da0b10fa Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Tue, 18 Nov 2014 15:11:40 +0000 Subject: [PATCH 248/249] Only pass instance to form for PUT and PATCH. Closes #2073. --- rest_framework/renderers.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index eb04e81e1..7c2b51566 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -547,7 +547,10 @@ class BrowsableAPIRenderer(BaseRenderer): if existing_serializer is not None: serializer = existing_serializer else: - serializer = view.get_serializer(instance=instance, data=data) + if method in ('PUT', 'PATCH'): + serializer = view.get_serializer(instance=instance, data=data) + else: + serializer = view.get_serializer(data=data) if data is not None: serializer.is_valid() form_renderer = self.form_renderer_class() @@ -584,7 +587,10 @@ class BrowsableAPIRenderer(BaseRenderer): # View has a serializer defined and parser class has a # corresponding renderer that can be used to render the data. - serializer = view.get_serializer(instance=instance) + if method in ('PUT', 'PATCH'): + serializer = view.get_serializer(instance=instance) + else: + serializer = view.get_serializer() # Render the raw data content renderer = renderer_class() From 080bd3d24e1866df2acc3aae0ec0f97ebe3a8c36 Mon Sep 17 00:00:00 2001 From: Tom Christie <tom@tomchristie.com> Date: Tue, 18 Nov 2014 15:38:31 +0000 Subject: [PATCH 249/249] Add comment ref #2089 --- rest_framework/renderers.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 7c2b51566..6596fc44c 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -515,6 +515,7 @@ class BrowsableAPIRenderer(BaseRenderer): In the absence of the View having an associated form then return None. """ + # See issue #2089 for refactoring this. serializer = getattr(data, 'serializer', None) if serializer and not getattr(serializer, 'many', False): instance = getattr(serializer, 'instance', None) @@ -562,6 +563,7 @@ class BrowsableAPIRenderer(BaseRenderer): via standard HTML forms. (Which are typically application/x-www-form-urlencoded) """ + # See issue #2089 for refactoring this. serializer = getattr(data, 'serializer', None) if serializer and not getattr(serializer, 'many', False): instance = getattr(serializer, 'instance', None)