From 213981cef394c6f7603c24b9a51096ffb56f6024 Mon Sep 17 00:00:00 2001 From: Mark Aaron Shirley Date: Fri, 4 Jan 2013 21:11:03 +0100 Subject: [PATCH 01/40] Handle ObjectDoesNotExist exceptions when serializing null reverse one-to-one --- rest_framework/relations.py | 10 ++++++++-- rest_framework/serializers.py | 17 ++++++++++------- rest_framework/tests/models.py | 5 +++++ rest_framework/tests/relations_nested.py | 22 +++++++++++++++++++++- 4 files changed, 44 insertions(+), 10 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 686dcf04e..6c1d4f5ba 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -100,7 +100,10 @@ class RelatedField(WritableField): ### Regular serializer stuff... def field_to_native(self, obj, field_name): - value = getattr(obj, self.source or field_name) + try: + value = getattr(obj, self.source or field_name) + except ObjectDoesNotExist: + return None return self.to_native(value) def field_from_native(self, data, files, field_name, into): @@ -202,7 +205,10 @@ class PrimaryKeyRelatedField(RelatedField): pk = obj.serializable_value(self.source or field_name) except AttributeError: # RelatedObject (reverse relationship) - obj = getattr(obj, self.source or field_name) + try: + obj = getattr(obj, self.source or field_name) + except ObjectDoesNotExist: + return None return self.to_native(obj.pk) # Forward relationship return self.to_native(pk) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index bd54db4ca..3391a262d 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -293,15 +293,18 @@ class BaseSerializer(Field): Override default so that we can apply ModelSerializer as a nested field to relationships. """ - if self.source: - for component in self.source.split('.'): - obj = getattr(obj, component) + try: + if self.source: + for component in self.source.split('.'): + obj = getattr(obj, component) + if is_simple_callable(obj): + obj = obj() + else: + obj = getattr(obj, field_name) if is_simple_callable(obj): obj = obj() - else: - obj = getattr(obj, field_name) - if is_simple_callable(obj): - obj = value() + except ObjectDoesNotExist: + return None # If the object has an "all" method, assume it's a relationship if is_simple_callable(getattr(obj, 'all', None)): diff --git a/rest_framework/tests/models.py b/rest_framework/tests/models.py index 59c350740..34cdbff31 100644 --- a/rest_framework/tests/models.py +++ b/rest_framework/tests/models.py @@ -205,3 +205,8 @@ class NullableForeignKeySource(RESTFrameworkModel): name = models.CharField(max_length=100) target = models.ForeignKey(ForeignKeyTarget, null=True, blank=True, related_name='nullable_sources') + +class NullableOneToOneSource(RESTFrameworkModel): + name = models.CharField(max_length=100) + target = models.OneToOneField(ForeignKeyTarget, null=True, blank=True, + related_name='nullable_source') diff --git a/rest_framework/tests/relations_nested.py b/rest_framework/tests/relations_nested.py index 5710c1ef4..808399f74 100644 --- a/rest_framework/tests/relations_nested.py +++ b/rest_framework/tests/relations_nested.py @@ -1,7 +1,7 @@ from django.db import models from django.test import TestCase from rest_framework import serializers -from rest_framework.tests.models import ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource +from rest_framework.tests.models import ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, NullableOneToOneSource class ForeignKeySourceSerializer(serializers.ModelSerializer): @@ -28,6 +28,13 @@ class NullableForeignKeySourceSerializer(serializers.ModelSerializer): model = NullableForeignKeySource +class NullableForeignKeyTargetSerializer(serializers.ModelSerializer): + nullable_source = serializers.PrimaryKeyRelatedField() + + class Meta: + model = ForeignKeyTarget + + class ReverseForeignKeyTests(TestCase): def setUp(self): target = ForeignKeyTarget(name='target-1') @@ -67,6 +74,10 @@ class NestedNullableForeignKeyTests(TestCase): def setUp(self): target = ForeignKeyTarget(name='target-1') target.save() + new_target = ForeignKeyTarget(name='target-2') + new_target.save() + one_source = NullableOneToOneSource(name='one-source-1', target=target) + one_source.save() for idx in range(1, 4): if idx == 3: target = None @@ -82,3 +93,12 @@ class NestedNullableForeignKeyTests(TestCase): {'id': 3, 'name': u'source-3', 'target': None}, ] self.assertEquals(serializer.data, expected) + + def test_reverse_foreign_key_retrieve_with_null(self): + queryset = ForeignKeyTarget.objects.all() + serializer = NullableForeignKeyTargetSerializer(queryset) + expected = [ + {'id': 1, 'name': u'target-1', 'nullable_source': 1}, + {'id': 2, 'name': u'target-2', 'nullable_source': None}, + ] + self.assertEquals(serializer.data, expected) From 4bb504732d045fb7db0fc1ddc1fc926197dd2c91 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 7 Jan 2013 21:08:55 +0000 Subject: [PATCH 02/40] Respect blank=True on relational fields. Fixes #537 --- 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 fa92838b6..19a955b85 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -430,7 +430,7 @@ class ModelSerializer(Serializer): # TODO: filter queryset using: # .using(db).complex_filter(self.rel.limit_choices_to) kwargs = { - 'null': model_field.null, + 'null': model_field.null or model_field.blank, 'queryset': model_field.rel.to._default_manager } From 31b585f26a8fc72e5b527b7672c7691e374dc494 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 7 Jan 2013 21:13:10 +0000 Subject: [PATCH 03/40] Note paginate_by=None usage. Fixes #555. --- docs/api-guide/pagination.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index ab335e6e2..71253afb0 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -97,6 +97,8 @@ You can also set the pagination style on a per-view basis, using the `ListAPIVie paginate_by = 10 paginate_by_param = 'page_size' +Note that using a `paginate_by` value of `None` will turn off pagination for the view. + For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods. --- From 4e8f55887d6ce86a2293f8b8cbb255bc58995336 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 7 Jan 2013 21:37:44 +0000 Subject: [PATCH 04/40] Clean up test slightly. Refs #552 --- rest_framework/tests/pagination.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rest_framework/tests/pagination.py b/rest_framework/tests/pagination.py index 81d297a1f..3b5508779 100644 --- a/rest_framework/tests/pagination.py +++ b/rest_framework/tests/pagination.py @@ -181,10 +181,10 @@ class UnitTestPagination(TestCase): """ Ensure context gets passed through to the object serializer. """ - serializer = PassOnContextPaginationSerializer(self.first_page) + serializer = PassOnContextPaginationSerializer(self.first_page, context={'foo': 'bar'}) serializer.data results = serializer.fields[serializer.results_field] - self.assertTrue(serializer.context is results.context) + self.assertEquals(serializer.context, results.context) class TestUnpaginated(TestCase): From a897eb5480348838b11fdb428ce0d110e8bc8da1 Mon Sep 17 00:00:00 2001 From: Mark Aaron Shirley Date: Mon, 7 Jan 2013 16:27:31 -0800 Subject: [PATCH 05/40] Create separate *NullableOneToOneTests TestCase --- rest_framework/tests/models.py | 8 ++++- rest_framework/tests/relations_hyperlink.py | 40 ++++++++++++++++----- rest_framework/tests/relations_nested.py | 33 +++++++++++------ rest_framework/tests/relations_pk.py | 29 ++++++++++++++- 4 files changed, 89 insertions(+), 21 deletions(-) diff --git a/rest_framework/tests/models.py b/rest_framework/tests/models.py index 34cdbff31..93f097615 100644 --- a/rest_framework/tests/models.py +++ b/rest_framework/tests/models.py @@ -206,7 +206,13 @@ class NullableForeignKeySource(RESTFrameworkModel): target = models.ForeignKey(ForeignKeyTarget, null=True, blank=True, related_name='nullable_sources') + +# OneToOne +class OneToOneTarget(RESTFrameworkModel): + name = models.CharField(max_length=100) + + class NullableOneToOneSource(RESTFrameworkModel): name = models.CharField(max_length=100) - target = models.OneToOneField(ForeignKeyTarget, null=True, blank=True, + target = models.OneToOneField(OneToOneTarget, null=True, blank=True, related_name='nullable_source') diff --git a/rest_framework/tests/relations_hyperlink.py b/rest_framework/tests/relations_hyperlink.py index a7f8a0351..ef57dc83c 100644 --- a/rest_framework/tests/relations_hyperlink.py +++ b/rest_framework/tests/relations_hyperlink.py @@ -2,7 +2,7 @@ from django.db import models from django.test import TestCase from rest_framework import serializers from rest_framework.compat import patterns, url -from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource +from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource def dummy_view(request, pk): pass @@ -13,6 +13,8 @@ urlpatterns = patterns('', url(r'^foreignkeysource/(?P[0-9]+)/$', dummy_view, name='foreignkeysource-detail'), url(r'^foreignkeytarget/(?P[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'), url(r'^nullableforeignkeysource/(?P[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'), + url(r'^onetoonetarget/(?P[0-9]+)/$', dummy_view, name='onetoonetarget-detail'), + url(r'^nullableonetoonesource/(?P[0-9]+)/$', dummy_view, name='nullableonetoonesource-detail'), ) class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer): @@ -40,18 +42,19 @@ class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): # Nullable ForeignKey - -class NullableForeignKeySource(models.Model): - name = models.CharField(max_length=100) - target = models.ForeignKey(ForeignKeyTarget, null=True, blank=True, - related_name='nullable_sources') - - class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = NullableForeignKeySource +# OneToOne +class NullableOneToOneTargetSerializer(serializers.HyperlinkedModelSerializer): + nullable_source = serializers.HyperlinkedRelatedField(view_name='nullableonetoonesource-detail') + + class Meta: + model = OneToOneTarget + + # TODO: Add test that .data cannot be accessed prior to .is_valid class HyperlinkedManyToManyTests(TestCase): @@ -409,3 +412,24 @@ class HyperlinkedNullableForeignKeyTests(TestCase): # {'id': 2, 'name': u'target-2', 'sources': []}, # ] # self.assertEquals(serializer.data, expected) + + +class HyperlinkedNullableOneToOneTests(TestCase): + urls = 'rest_framework.tests.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) + expected = [ + {'url': '/onetoonetarget/1/', 'name': u'target-1', 'nullable_source': '/nullableonetoonesource/1/'}, + {'url': '/onetoonetarget/2/', 'name': u'target-2', 'nullable_source': None}, + ] + self.assertEquals(serializer.data, expected) diff --git a/rest_framework/tests/relations_nested.py b/rest_framework/tests/relations_nested.py index 808399f74..225fee882 100644 --- a/rest_framework/tests/relations_nested.py +++ b/rest_framework/tests/relations_nested.py @@ -1,7 +1,7 @@ from django.db import models from django.test import TestCase from rest_framework import serializers -from rest_framework.tests.models import ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, NullableOneToOneSource +from rest_framework.tests.models import ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource class ForeignKeySourceSerializer(serializers.ModelSerializer): @@ -28,11 +28,16 @@ class NullableForeignKeySourceSerializer(serializers.ModelSerializer): model = NullableForeignKeySource -class NullableForeignKeyTargetSerializer(serializers.ModelSerializer): - nullable_source = serializers.PrimaryKeyRelatedField() +class NullableOneToOneSourceSerializer(serializers.ModelSerializer): + class Meta: + model = NullableOneToOneSource + + +class NullableOneToOneTargetSerializer(serializers.ModelSerializer): + nullable_source = NullableOneToOneSourceSerializer() class Meta: - model = ForeignKeyTarget + model = OneToOneTarget class ReverseForeignKeyTests(TestCase): @@ -74,10 +79,6 @@ class NestedNullableForeignKeyTests(TestCase): def setUp(self): target = ForeignKeyTarget(name='target-1') target.save() - new_target = ForeignKeyTarget(name='target-2') - new_target.save() - one_source = NullableOneToOneSource(name='one-source-1', target=target) - one_source.save() for idx in range(1, 4): if idx == 3: target = None @@ -94,11 +95,21 @@ class NestedNullableForeignKeyTests(TestCase): ] self.assertEquals(serializer.data, expected) + +class NestedNullableOneToOneTests(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=target) + source.save() + def test_reverse_foreign_key_retrieve_with_null(self): - queryset = ForeignKeyTarget.objects.all() - serializer = NullableForeignKeyTargetSerializer(queryset) + queryset = OneToOneTarget.objects.all() + serializer = NullableOneToOneTargetSerializer(queryset) expected = [ - {'id': 1, 'name': u'target-1', 'nullable_source': 1}, + {'id': 1, 'name': u'target-1', 'nullable_source': {'id': 1, 'name': u'source-1', 'target': 1}}, {'id': 2, 'name': u'target-2', 'nullable_source': None}, ] self.assertEquals(serializer.data, expected) diff --git a/rest_framework/tests/relations_pk.py b/rest_framework/tests/relations_pk.py index af6da2c0b..589b3646c 100644 --- a/rest_framework/tests/relations_pk.py +++ b/rest_framework/tests/relations_pk.py @@ -1,7 +1,7 @@ from django.db import models from django.test import TestCase from rest_framework import serializers -from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource +from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource class ManyToManyTargetSerializer(serializers.ModelSerializer): @@ -33,6 +33,14 @@ class NullableForeignKeySourceSerializer(serializers.ModelSerializer): model = NullableForeignKeySource +# OneToOne +class NullableOneToOneTargetSerializer(serializers.ModelSerializer): + nullable_source = serializers.PrimaryKeyRelatedField() + + class Meta: + model = OneToOneTarget + + # TODO: Add test that .data cannot be accessed prior to .is_valid class PKManyToManyTests(TestCase): @@ -383,3 +391,22 @@ class PKNullableForeignKeyTests(TestCase): # {'id': 2, 'name': u'target-2', 'sources': []}, # ] # self.assertEquals(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=target) + source.save() + + def test_reverse_foreign_key_retrieve_with_null(self): + queryset = OneToOneTarget.objects.all() + serializer = NullableOneToOneTargetSerializer(queryset) + expected = [ + {'id': 1, 'name': u'target-1', 'nullable_source': 1}, + {'id': 2, 'name': u'target-2', 'nullable_source': None}, + ] + self.assertEquals(serializer.data, expected) From 4df1172665f6df3d4c4df53b4836e2c6ed462da5 Mon Sep 17 00:00:00 2001 From: Marc Tamlyn Date: Tue, 8 Jan 2013 11:45:55 +0000 Subject: [PATCH 06/40] Fix reference to BasicAuthentication in settings. --- docs/api-guide/settings.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 8c87f2ca5..a422e5f61 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -65,7 +65,7 @@ Default: ( 'rest_framework.authentication.SessionAuthentication', - 'rest_framework.authentication.UserBasicAuthentication' + 'rest_framework.authentication.BasicAuthentication' ) ## DEFAULT_PERMISSION_CLASSES From 49cd5e59a8679004a067e2db72f8ba1d9ac5b69c Mon Sep 17 00:00:00 2001 From: Marc Tamlyn Date: Tue, 8 Jan 2013 12:20:01 +0000 Subject: [PATCH 07/40] ObtainAuthToken pluggable Serializer. It should have serializer_class in the same way as any other API view. --- rest_framework/authtoken/views.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/rest_framework/authtoken/views.py b/rest_framework/authtoken/views.py index d318c7233..7c03cb766 100644 --- a/rest_framework/authtoken/views.py +++ b/rest_framework/authtoken/views.py @@ -12,10 +12,11 @@ class ObtainAuthToken(APIView): permission_classes = () parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) renderer_classes = (renderers.JSONRenderer,) + serializer_class = AuthTokenSerializer model = Token def post(self, request): - serializer = AuthTokenSerializer(data=request.DATA) + serializer = self.serializer_class(data=request.DATA) if serializer.is_valid(): token, created = Token.objects.get_or_create(user=serializer.object['user']) return Response({'token': token.key}) From c1f194b0a592c88c7de512958f62c43695df018f Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 8 Jan 2013 15:03:14 +0000 Subject: [PATCH 08/40] Fix inconsistent view_name logic. Fixes #567. --- rest_framework/relations.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 0d93f4480..adc478000 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -367,13 +367,13 @@ class HyperlinkedRelatedField(RelatedField): kwargs = {self.slug_url_kwarg: slug} try: - return reverse(self.view_name, kwargs=kwargs, request=request, format=format) + return reverse(view_name, kwargs=kwargs, request=request, format=format) except: pass kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug} try: - return reverse(self.view_name, kwargs=kwargs, request=request, format=format) + return reverse(view_name, kwargs=kwargs, request=request, format=format) except: pass @@ -490,13 +490,13 @@ class HyperlinkedIdentityField(Field): kwargs = {self.slug_url_kwarg: slug} try: - return reverse(self.view_name, kwargs=kwargs, request=request, format=format) + return reverse(view_name, kwargs=kwargs, request=request, format=format) except: pass kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug} try: - return reverse(self.view_name, kwargs=kwargs, request=request, format=format) + return reverse(view_name, kwargs=kwargs, request=request, format=format) except: pass From b298bf53f310fae48083d87408d69e2d46e60671 Mon Sep 17 00:00:00 2001 From: Mark Aaron Shirley Date: Tue, 8 Jan 2013 08:35:41 -0800 Subject: [PATCH 09/40] Update release notes --- docs/topics/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md index edd948ac8..d883571ad 100644 --- a/docs/topics/release-notes.md +++ b/docs/topics/release-notes.md @@ -21,6 +21,7 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi * Deprecate django.utils.simplejson in favor of Python 2.6's built-in json module. * Bugfix: Validation errors instead of exceptions when serializers receive incorrect types. * Bugfix: Validation errors instead of exceptions when related fields receive incorrect types. +* Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one ### 2.1.15 From cb235977f654ce6c385cf5245cfa086c2ed54780 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 9 Jan 2013 09:22:17 +0000 Subject: [PATCH 10/40] Include CSRF note in SessionAuthentication docs. --- docs/api-guide/authentication.md | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 43fc15d2d..c089e4e1a 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -125,17 +125,6 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' } - - ## SessionAuthentication This policy uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website. @@ -145,6 +134,8 @@ If successfully authenticated, `SessionAuthentication` provides the following cr * `request.user` will be a Django `User` instance. * `request.auth` will be `None`. +If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details. + # Custom authentication To implement a custom authentication policy, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise. @@ -154,3 +145,4 @@ To implement a custom authentication policy, subclass `BaseAuthentication` and o [oauth]: http://oauth.net/2/ [permission]: permissions.md [throttling]: throttling.md +[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax From 268f60999cdca46e6541f5acc35fbbe08b85f477 Mon Sep 17 00:00:00 2001 From: Juan Riaza Date: Thu, 10 Jan 2013 15:48:22 +0100 Subject: [PATCH 11/40] unused imports --- rest_framework/tests/decorators.py | 1 - rest_framework/tests/relations_hyperlink.py | 1 - rest_framework/tests/relations_nested.py | 1 - rest_framework/tests/relations_pk.py | 1 - 4 files changed, 4 deletions(-) diff --git a/rest_framework/tests/decorators.py b/rest_framework/tests/decorators.py index bc44a45b0..5e6bce4ef 100644 --- a/rest_framework/tests/decorators.py +++ b/rest_framework/tests/decorators.py @@ -1,5 +1,4 @@ from django.test import TestCase -from django.test.client import RequestFactory from rest_framework import status from rest_framework.response import Response from rest_framework.renderers import JSONRenderer diff --git a/rest_framework/tests/relations_hyperlink.py b/rest_framework/tests/relations_hyperlink.py index ef57dc83c..579136704 100644 --- a/rest_framework/tests/relations_hyperlink.py +++ b/rest_framework/tests/relations_hyperlink.py @@ -1,4 +1,3 @@ -from django.db import models from django.test import TestCase from rest_framework import serializers from rest_framework.compat import patterns, url diff --git a/rest_framework/tests/relations_nested.py b/rest_framework/tests/relations_nested.py index 225fee882..0e129fae2 100644 --- a/rest_framework/tests/relations_nested.py +++ b/rest_framework/tests/relations_nested.py @@ -1,4 +1,3 @@ -from django.db import models from django.test import TestCase from rest_framework import serializers from rest_framework.tests.models import ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource diff --git a/rest_framework/tests/relations_pk.py b/rest_framework/tests/relations_pk.py index 589b3646c..548358603 100644 --- a/rest_framework/tests/relations_pk.py +++ b/rest_framework/tests/relations_pk.py @@ -1,4 +1,3 @@ -from django.db import models from django.test import TestCase from rest_framework import serializers from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource From 674c9029c1b0f3680bfc04dd87b58f9bd21988de Mon Sep 17 00:00:00 2001 From: Richard Wackerbarth Date: Fri, 4 Jan 2013 05:46:30 -0600 Subject: [PATCH 12/40] Imply an additional element in infinite lists This is to allow the addition of elements without having to change existing lines of code --- docs/tutorial/1-serialization.md | 4 ++-- docs/tutorial/2-requests-and-responses.md | 2 +- docs/tutorial/3-class-based-views.md | 2 +- docs/tutorial/4-authentication-and-permissions.md | 4 ++-- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index e61fb9469..c8db8f24c 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -60,7 +60,7 @@ We'll also need to add our new `snippets` app and the `rest_framework` app to `I INSTALLED_APPS = ( ... 'rest_framework', - 'snippets' + 'snippets', ) We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs. @@ -288,7 +288,7 @@ Finally we need to wire these views up. Create the `snippets/urls.py` file: urlpatterns = patterns('snippets.views', url(r'^snippets/$', 'snippet_list'), - url(r'^snippets/(?P[0-9]+)/$', 'snippet_detail') + url(r'^snippets/(?P[0-9]+)/$', 'snippet_detail'), ) It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now. diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 08cf91cdb..cdf6c13f3 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -117,7 +117,7 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter urlpatterns = patterns('snippets.views', url(r'^snippets/$', 'snippet_list'), - url(r'^snippets/(?P[0-9]+)$', 'snippet_detail') + url(r'^snippets/(?P[0-9]+)$', 'snippet_detail'), ) urlpatterns = format_suffix_patterns(urlpatterns) diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index b115b0229..290ea5e9d 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -70,7 +70,7 @@ We'll also need to refactor our URLconf slightly now we're using class based vie urlpatterns = patterns('', url(r'^snippets/$', views.SnippetList.as_view()), - url(r'^snippets/(?P[0-9]+)/$', views.SnippetDetail.as_view()) + url(r'^snippets/(?P[0-9]+)/$', views.SnippetDetail.as_view()), ) urlpatterns = format_suffix_patterns(urlpatterns) diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 9576a7f0b..5793d38eb 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -77,7 +77,7 @@ We'll also add a couple of views. We'd like to just use read-only views for the Finally we need to add those views into the API, by referencing them from the URL conf. url(r'^users/$', views.UserList.as_view()), - url(r'^users/(?P[0-9]+)/$', views.UserInstance.as_view()) + url(r'^users/(?P[0-9]+)/$', views.UserInstance.as_view()), ## Associating Snippets with Users @@ -134,7 +134,7 @@ And, at the end of the file, add a pattern to include the login and logout views urlpatterns += patterns('', url(r'^api-auth/', include('rest_framework.urls', - namespace='rest_framework')) + namespace='rest_framework')), ) The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the `'rest_framework'` namespace. diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 216ca4338..c4c034956 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -116,7 +116,7 @@ After adding all those names into our URLconf, our final `'urls.py'` file should url(r'^snippets/(?P[0-9]+)/$', views.SnippetDetail.as_view(), name='snippet-detail'), - url(r'^snippets/(?P[0-9]+)/highlight/$' + url(r'^snippets/(?P[0-9]+)/highlight/$', views.SnippetHighlight.as_view(), name='snippet-highlight'), url(r'^users/$', @@ -130,7 +130,7 @@ After adding all those names into our URLconf, our final `'urls.py'` file should # Login and logout views for the browsable API urlpatterns += patterns('', url(r'^api-auth/', include('rest_framework.urls', - namespace='rest_framework')) + namespace='rest_framework')), ) ## Adding pagination From 8efd9563a6d207619ebbd066292fa910023189ae Mon Sep 17 00:00:00 2001 From: Richard Wackerbarth Date: Fri, 4 Jan 2013 05:47:27 -0600 Subject: [PATCH 13/40] Some comment on the tutorial repository --- docs/tutorial/1-serialization.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index c8db8f24c..d12f7935f 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -8,7 +8,7 @@ The tutorial is fairly in-depth, so you should probably get a cookie and a cup o --- -**Note**: The final code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. There is also a sandbox version for testing, [available here][sandbox]. +**Note**: The code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. As pieces of code are introduced, they are committed to this repository. The completed implementation is also online as a sandbox version for testing, [available here][sandbox]. --- @@ -73,7 +73,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. +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. from django.db import models from pygments.lexers import get_all_lexers From 12efd78fcf40ea8acf95259ffc5269bd9f360d2f Mon Sep 17 00:00:00 2001 From: Richard Wackerbarth Date: Wed, 9 Jan 2013 11:19:12 -0600 Subject: [PATCH 14/40] Bringing up the Web API --- docs/tutorial/1-serialization.md | 33 ++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index d12f7935f..28aaea4d7 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -295,9 +295,38 @@ It's worth noting that there are a couple of edge cases we're not dealing with p ## Testing our first attempt at a Web API -**TODO: Describe using runserver and making example requests from console** +Now we can start up a sample server that serves our snippets. -**TODO: Describe opening in a web browser and viewing json output** +Quit out of the shell + + quit() + +and start up Django's development server + + python manage.py runserver + + Validating models... + + 0 errors found + Django version 1.4.3, using settings 'tutorial.settings' + Development server is running at http://127.0.0.1:8000/ + Quit the server with CONTROL-C. + +In another terminal window, we can test the server. + +We can get a list of all of the snippets (we only have one at the moment) + + curl http://127.0.0.1:8000/snippets/ + + [{"id": 1, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}] + +or we can get a particular snippet by referencing its id + + curl http://127.0.0.1:8000/snippets/1/ + + {"id": 1, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"} + +Similarly, you can have the same json displayed by referencing these URLs from your favorite web browser. ## Where are we now From 7dd5c56f225c7fe97a23101eea1bb839110d8ed2 Mon Sep 17 00:00:00 2001 From: Richard Wackerbarth Date: Thu, 10 Jan 2013 16:16:30 -0600 Subject: [PATCH 15/40] Make the whitespace uniform --- docs/tutorial/1-serialization.md | 3 --- docs/tutorial/2-requests-and-responses.md | 3 --- 2 files changed, 6 deletions(-) diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 28aaea4d7..db6db2da6 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -202,8 +202,6 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer` model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style') - - ## Writing regular Django views using our Serializer Let's see how we can write some API views using our new Serializer class. @@ -229,7 +227,6 @@ Edit the `snippet/views.py` file, and add the following. kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) - The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet. @csrf_exempt diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index cdf6c13f3..340ea28ee 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -31,7 +31,6 @@ These wrappers provide a few bits of functionality such as making sure you recei The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.DATA` with malformed input. - ## Pulling it all together Okay, let's go ahead and start using these new components to write a few views. @@ -63,7 +62,6 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious. Here is the view for an individual snippet. @@ -138,7 +136,6 @@ Because the API chooses a return format based on what the client asks for, it wi See the [browsable api][browseable-api] topic for more information about the browsable API feature and how to customize it. - ## What's next? In [tutorial part 3][tut-3], we'll start using class based views, and see how generic views reduce the amount of code we need to write. From c09a579851b6d5e6c57bf32fae1c5dbd8466988e Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 11 Jan 2013 08:56:49 +0000 Subject: [PATCH 16/40] Added @wackerbarth. Thanks! --- docs/topics/credits.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/topics/credits.md b/docs/topics/credits.md index 83272766e..60800c9e6 100644 --- a/docs/topics/credits.md +++ b/docs/topics/credits.md @@ -88,6 +88,7 @@ The following people have helped make REST framework great. * Juan Riaza - [juanriaza] * Michael Mior - [michaelmior] * Marc Tamlyn - [mjtamlyn] +* Richard Wackerbarth - [wackerbarth] Many thanks to everyone who's contributed to the project. @@ -211,3 +212,4 @@ You can also contact [@_tomchristie][twitter] directly on twitter. [juanriaza]: https://github.com/juanriaza [michaelmior]: https://github.com/michaelmior [mjtamlyn]: https://github.com/mjtamlyn +[wackerbarth]: https://github.com/wackerbarth From 919c5e1e01106918af9f26c506c2198fbf731923 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stephan=20Gro=C3=9F?= Date: Fri, 11 Jan 2013 20:26:44 +0100 Subject: [PATCH 17/40] Fix typo in permission_classes --- docs/api-guide/authentication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index c089e4e1a..afd9a2619 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -52,7 +52,7 @@ Or, if you're using the `@api_view` decorator with function based views. @api_view(['GET']) @authentication_classes((SessionAuthentication, BasicAuthentication)) - @permissions_classes((IsAuthenticated,)) + @permission_classes((IsAuthenticated,)) def example_view(request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. From 73c4e5c4603e24ec1ea9976a3c6152a797f8f041 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 12 Jan 2013 09:32:53 +0000 Subject: [PATCH 18/40] auto_now and auto_now_add fields should be read only by default --- rest_framework/serializers.py | 3 +++ rest_framework/tests/fields.py | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 rest_framework/tests/fields.py diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index da0af467f..0bacacda7 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -452,6 +452,9 @@ class ModelSerializer(Serializer): if model_field.null or model_field.blank: kwargs['required'] = False + if not model_field.editable: + kwargs['read_only'] = True + if model_field.has_default(): kwargs['required'] = False kwargs['default'] = model_field.get_default() diff --git a/rest_framework/tests/fields.py b/rest_framework/tests/fields.py new file mode 100644 index 000000000..b1a8161a6 --- /dev/null +++ b/rest_framework/tests/fields.py @@ -0,0 +1,26 @@ +""" +General tests for relational fields. +""" + +from django.db import models +from django.test import TestCase +from rest_framework import serializers + + +class TimestampedModel(models.Model): + added = models.DateTimeField(auto_now_add=True) + updated = models.DateTimeField(auto_now=True) + + +class TimestampedModelSerializer(serializers.ModelSerializer): + class Meta: + model = TimestampedModel + + +class ReadOnlyFieldTests(TestCase): + def test_auto_now_fields_read_only(self): + """ + auto_now and auto_now_add fields should be readonly by default. + """ + serializer = TimestampedModelSerializer() + self.assertEquals(serializer.fields['added'].read_only, True) From d9acec3e6dd07d33f416646bc161108ea52842d6 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 12 Jan 2013 09:43:07 +0000 Subject: [PATCH 19/40] PK fields should only be read-only if they are an AutoField. Fixes #563 --- rest_framework/serializers.py | 5 +++-- rest_framework/tests/fields.py | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 0bacacda7..27458f968 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -415,7 +415,7 @@ class ModelSerializer(Serializer): """ Returns a default instance of the pk field. """ - return Field() + return self.get_field(model_field) def get_nested_field(self, model_field): """ @@ -452,7 +452,7 @@ class ModelSerializer(Serializer): if model_field.null or model_field.blank: kwargs['required'] = False - if not model_field.editable: + if isinstance(model_field, models.AutoField) or not model_field.editable: kwargs['read_only'] = True if model_field.has_default(): @@ -468,6 +468,7 @@ class ModelSerializer(Serializer): return ChoiceField(**kwargs) field_mapping = { + models.AutoField: IntegerField, models.FloatField: FloatField, models.IntegerField: IntegerField, models.PositiveIntegerField: IntegerField, diff --git a/rest_framework/tests/fields.py b/rest_framework/tests/fields.py index b1a8161a6..a6a059416 100644 --- a/rest_framework/tests/fields.py +++ b/rest_framework/tests/fields.py @@ -12,11 +12,20 @@ class TimestampedModel(models.Model): 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 ReadOnlyFieldTests(TestCase): def test_auto_now_fields_read_only(self): """ @@ -24,3 +33,11 @@ class ReadOnlyFieldTests(TestCase): """ serializer = TimestampedModelSerializer() self.assertEquals(serializer.fields['added'].read_only, True) + + def test_auto_pk_fields_read_only(self): + serializer = TimestampedModelSerializer() + self.assertEquals(serializer.fields['id'].read_only, True) + + def test_non_auto_pk_fields_not_read_only(self): + serializer = CharPrimaryKeyModelSerializer() + self.assertEquals(serializer.fields['id'].read_only, False) From 25a463be7302ae64fe1ea2a560d7bdbd022221d9 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 12 Jan 2013 10:07:11 +0000 Subject: [PATCH 20/40] Update release notes. --- docs/topics/release-notes.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md index d883571ad..b7907ec73 100644 --- a/docs/topics/release-notes.md +++ b/docs/topics/release-notes.md @@ -19,10 +19,13 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi ### Master * Deprecate django.utils.simplejson in favor of Python 2.6's built-in json module. +* Bugfix: PK fields now only default to `read_only=True` if they are an AutoField or if `editable=False`. * Bugfix: Validation errors instead of exceptions when serializers receive incorrect types. * Bugfix: Validation errors instead of exceptions when related fields receive incorrect types. * Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one +**Note**: If you are using auto UUID fields as your primary keys, you probably want to make sure that the model fields correctly set `editable=False`. + ### 2.1.15 **Date**: 3rd Jan 2013 From e0440e609b818b0426df33e31318cb8c0463b65a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stephan=20Gro=C3=9F?= Date: Sat, 12 Jan 2013 14:28:16 +0100 Subject: [PATCH 21/40] Update django-filter link to pypi --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8a9149cf1..1cf14f8d2 100644 --- a/README.md +++ b/README.md @@ -283,5 +283,5 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [urlobject]: https://github.com/zacharyvoase/urlobject [markdown]: http://pypi.python.org/pypi/Markdown/ [pyyaml]: http://pypi.python.org/pypi/PyYAML -[django-filter]: https://github.com/alex/django-filter +[django-filter]: http://pypi.python.org/pypi/django-filter From da85bb1ab3eedbd8df1e2fc9577ed3e2ab809c4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stephan=20Gro=C3=9F?= Date: Sat, 12 Jan 2013 14:31:40 +0100 Subject: [PATCH 22/40] Update django-filter link to pypi --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index 080eca6f2..497f19004 100644 --- a/docs/index.md +++ b/docs/index.md @@ -166,7 +166,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [urlobject]: https://github.com/zacharyvoase/urlobject [markdown]: http://pypi.python.org/pypi/Markdown/ [yaml]: http://pypi.python.org/pypi/PyYAML -[django-filter]: https://github.com/alex/django-filter +[django-filter]: http://pypi.python.org/pypi/django-filter [0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X [image]: img/quickstart.png [sandbox]: http://restframework.herokuapp.com/ From 0987bed2f74f69eccba181303689197e54836288 Mon Sep 17 00:00:00 2001 From: Richard Wackerbarth Date: Fri, 11 Jan 2013 14:04:13 -0600 Subject: [PATCH 23/40] Minor gramatical correction --- docs/tutorial/4-authentication-and-permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 5793d38eb..f6daebb7a 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -29,7 +29,7 @@ And now we can add a `.save()` method to our model class: def save(self, *args, **kwargs): """ - Use the `pygments` library to create an highlighted HTML + Use the `pygments` library to create a highlighted HTML representation of the code snippet. """ lexer = get_lexer_by_name(self.language) From 08943c3e0aad30b2f9f6b8146daa80117b7adfb3 Mon Sep 17 00:00:00 2001 From: Richard Wackerbarth Date: Sun, 13 Jan 2013 10:49:49 -0600 Subject: [PATCH 24/40] Format extensions have already been introduced. If format extensions are used, they must be used in the creation of the reverse URLs. --- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index c4c034956..27898f7b9 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -15,8 +15,8 @@ Right now we have endpoints for 'snippets' and 'users', but we don't have a sing @api_view(('GET',)) def api_root(request, format=None): return Response({ - 'users': reverse('user-list', request=request), - 'snippets': reverse('snippet-list', request=request) + 'users': reverse('user-list', request=request, format=format), + 'snippets': reverse('snippet-list', request=request, format=format) }) Notice that we're using REST framework's `reverse` function in order to return fully-qualified URLs. From 191135d7b06617069489fa5de4e6f519767a4ee1 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 14 Jan 2013 09:20:37 +0000 Subject: [PATCH 25/40] Version 2.1.16 --- README.md | 11 +++++++++++ docs/topics/release-notes.md | 9 +++++---- rest_framework/__init__.py | 2 +- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 1cf14f8d2..a70201661 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,17 @@ To run the tests. # Changelog +### 2.1.16 + +**Date**: 14th Jan 2013 + +* Deprecate django.utils.simplejson in favor of Python 2.6's built-in json module. +* Bugfix: `auto_now`, `auto_now_add` and other `editable=False` fields now default to read-only. +* Bugfix: PK fields now only default to read-only if they are an AutoField or if `editable=False`. +* Bugfix: Validation errors instead of exceptions when serializers receive incorrect types. +* Bugfix: Validation errors instead of exceptions when related fields receive incorrect types. +* Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one + ### 2.1.15 **Date**: 3rd Jan 2013 diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md index b7907ec73..bf23fa352 100644 --- a/docs/topics/release-notes.md +++ b/docs/topics/release-notes.md @@ -16,16 +16,17 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi ## 2.1.x series -### Master +### 2.1.16 + +**Date**: 14th Jan 2013 * Deprecate django.utils.simplejson in favor of Python 2.6's built-in json module. -* Bugfix: PK fields now only default to `read_only=True` if they are an AutoField or if `editable=False`. +* Bugfix: `auto_now`, `auto_now_add` and other `editable=False` fields now default to read-only. +* Bugfix: PK fields now only default to read-only if they are an AutoField or if `editable=False`. * Bugfix: Validation errors instead of exceptions when serializers receive incorrect types. * Bugfix: Validation errors instead of exceptions when related fields receive incorrect types. * Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one -**Note**: If you are using auto UUID fields as your primary keys, you probably want to make sure that the model fields correctly set `editable=False`. - ### 2.1.15 **Date**: 3rd Jan 2013 diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py index 1d25ee7f7..bc267fad7 100644 --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -1,3 +1,3 @@ -__version__ = '2.1.15' +__version__ = '2.1.16' VERSION = __version__ # synonym From a7e7c441a4e4eb058c0b879e62d976b848b618c6 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 14 Jan 2013 17:38:32 +0000 Subject: [PATCH 26/40] Add link to @mjumbewu's CSV package --- docs/api-guide/renderers.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 389dec1f6..86bbdaa16 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -280,6 +280,9 @@ The following third party packages are also available. ## MessagePack [MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack]. +## CSV + +Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework. [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process [conneg]: content-negotiation.md @@ -292,4 +295,5 @@ The following third party packages are also available. [django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views [messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack [juanriaza]: https://github.com/juanriaza -[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack \ No newline at end of file +[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack[mjumbewu]: https://github.com/mjumbewu +[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv \ No newline at end of file From 190473f5089c5862e610bd823d6b67257ab1376f Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 14 Jan 2013 17:38:45 +0000 Subject: [PATCH 27/40] Tweak messagepack links --- docs/api-guide/parsers.md | 2 +- docs/api-guide/renderers.md | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index 9356b4205..de9685578 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -167,7 +167,7 @@ The following third party packages are also available. ## MessagePack -[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack]. +[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework. [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion [messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 86bbdaa16..b4f7ec3d4 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -279,7 +279,8 @@ The following third party packages are also available. ## MessagePack -[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack]. +[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework. + ## CSV Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework. @@ -293,7 +294,8 @@ Comma-separated values are a plain-text tabular data format, that can be easily [application/vnd.github+json]: http://developer.github.com/v3/media/ [application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/ [django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views -[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack +[messagepack]: http://msgpack.org/ [juanriaza]: https://github.com/juanriaza -[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack[mjumbewu]: https://github.com/mjumbewu +[mjumbewu]: https://github.com/mjumbewu +[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack [djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv \ No newline at end of file From 79f635e0ddeee6647a9c6f8937953052b17f6ff8 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 15 Jan 2013 09:33:24 +0000 Subject: [PATCH 28/40] Modify tutorial to work with pygments 1.6rc. Fixes #581. --- docs/tutorial/1-serialization.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index db6db2da6..d3ada9e3a 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -78,9 +78,10 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles - - LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in get_all_lexers()]) - STYLE_CHOICES = sorted((item, item) for item in list(get_all_styles())) + + LEXERS = [item for item in get_all_lexers() if item[1]] + LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) + STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) class Snippet(models.Model): From da6b9576c5c5f019800555108fc86887ef7e453d Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 15 Jan 2013 10:51:10 +0000 Subject: [PATCH 29/40] Update docstrings --- rest_framework/tests/fields.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/rest_framework/tests/fields.py b/rest_framework/tests/fields.py index a6a059416..8068272d4 100644 --- a/rest_framework/tests/fields.py +++ b/rest_framework/tests/fields.py @@ -1,5 +1,5 @@ """ -General tests for relational fields. +General serializer field tests. """ from django.db import models @@ -29,15 +29,21 @@ class CharPrimaryKeyModelSerializer(serializers.ModelSerializer): class ReadOnlyFieldTests(TestCase): def test_auto_now_fields_read_only(self): """ - auto_now and auto_now_add fields should be readonly by default. + auto_now and auto_now_add fields should be read_only by default. """ serializer = TimestampedModelSerializer() self.assertEquals(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.assertEquals(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.assertEquals(serializer.fields['id'].read_only, False) From e67b23f1ace59f237f260075501a8fbf636b60f1 Mon Sep 17 00:00:00 2001 From: Johannes Spielmann Date: Tue, 15 Jan 2013 13:46:41 +0100 Subject: [PATCH 30/40] correcting template: closing tag was missing --- rest_framework/templates/rest_framework/base.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/templates/rest_framework/base.html b/rest_framework/templates/rest_framework/base.html index 42e49cb90..092bf2e47 100644 --- a/rest_framework/templates/rest_framework/base.html +++ b/rest_framework/templates/rest_framework/base.html @@ -112,7 +112,7 @@
{{ request.method }} {{ request.get_full_path }}
-
+
HTTP {{ response.status_code }} {{ response.status_text }}{% autoescape off %} {% for key, val in response.items %}{{ key }}: {{ val|urlize_quoted_links }} From e32aaa29b8e8665faf63ab4646cfba7aed6d9d8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stephan=20Gro=C3=9F?= Date: Tue, 15 Jan 2013 14:00:32 +0100 Subject: [PATCH 31/40] Add @shezi thanks! --- docs/topics/credits.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/topics/credits.md b/docs/topics/credits.md index 60800c9e6..4af4ec8fc 100644 --- a/docs/topics/credits.md +++ b/docs/topics/credits.md @@ -89,6 +89,7 @@ The following people have helped make REST framework great. * Michael Mior - [michaelmior] * Marc Tamlyn - [mjtamlyn] * Richard Wackerbarth - [wackerbarth] +* Johannes Spielmann - [shezi] Many thanks to everyone who's contributed to the project. @@ -213,3 +214,4 @@ You can also contact [@_tomchristie][twitter] directly on twitter. [michaelmior]: https://github.com/michaelmior [mjtamlyn]: https://github.com/mjtamlyn [wackerbarth]: https://github.com/wackerbarth +[shezi]: https://github.com/shezi From 4fc3b1ba56239a1fb999f9aef99cdbcfbc9aa254 Mon Sep 17 00:00:00 2001 From: James Cleveland Date: Tue, 15 Jan 2013 13:02:53 +0000 Subject: [PATCH 32/40] Add timedelta encoder to the JSONEncoder class. Whilst this commit adds *encoding* of timedeltas to a string of a floating point value of the seconds, you must add your own serializer field for whatever timedelta model field you are using. This is because Django doesn't support any kind of timedelta field out-of-the-box, so you have to either implement your own or use django-timedelta. If this is the case and you want to serialise timedelta input, you will have to implement your own special field to use for the timedelta, which is not included in core as it is based on a 3rd party library. Here is an example: import datetime import timedelta from django import forms from django.core import validators from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from rest_framework.fields import WritableField class TimedeltaField(WritableField): type_name = 'TimedeltaField' form_field_class = forms.FloatField default_error_messages = { 'invalid': _("'%s' value must be in seconds."), } def from_native(self, value): if value in validators.EMPTY_VALUES: return None try: return datetime.timedelta(seconds=float(value)) except (TypeError, ValueError): msg = self.error_messages['invalid'] % value raise ValidationError(msg) Which is based on the FloatField. This field can then be used in your serializer like this: from yourapp.fields import TimedeltaField class YourSerializer(serializers.ModelSerializer): duration = TimedeltaField() --- rest_framework/utils/encoders.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py index c70b24dda..7afe100a8 100644 --- a/rest_framework/utils/encoders.py +++ b/rest_framework/utils/encoders.py @@ -12,7 +12,7 @@ from rest_framework.serializers import DictWithMetadata, SortedDictWithMetadata class JSONEncoder(json.JSONEncoder): """ - JSONEncoder subclass that knows how to encode date/time, + JSONEncoder subclass that knows how to encode date/time/timedelta, decimal types, and generators. """ def default(self, o): @@ -34,6 +34,8 @@ class JSONEncoder(json.JSONEncoder): if o.microsecond: r = r[:12] return r + elif isinstance(o, datetime.timedelta): + return str(o.total_seconds()) elif isinstance(o, decimal.Decimal): return str(o) elif hasattr(o, '__iter__'): From b4c43d5fe44023a82309d57d0a3b5ae85949a5e9 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 15 Jan 2013 13:29:21 +0000 Subject: [PATCH 33/40] Update release notes --- docs/topics/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md index bf23fa352..f43dc1d3d 100644 --- a/docs/topics/release-notes.md +++ b/docs/topics/release-notes.md @@ -16,6 +16,10 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi ## 2.1.x series +### Master + +* Support json encoding of timedelta objects. + ### 2.1.16 **Date**: 14th Jan 2013 From e1076cfb49b6293aa837cf7bdb4c11988892c598 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 15 Jan 2013 13:31:05 +0000 Subject: [PATCH 34/40] Added @radiosilence, for the timedelta encoding support. Thanks! See: #584 --- docs/topics/credits.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/topics/credits.md b/docs/topics/credits.md index 4af4ec8fc..b0b00c122 100644 --- a/docs/topics/credits.md +++ b/docs/topics/credits.md @@ -90,6 +90,7 @@ The following people have helped make REST framework great. * Marc Tamlyn - [mjtamlyn] * Richard Wackerbarth - [wackerbarth] * Johannes Spielmann - [shezi] +* James Cleveland - [radiosilence] Many thanks to everyone who's contributed to the project. @@ -215,3 +216,4 @@ You can also contact [@_tomchristie][twitter] directly on twitter. [mjtamlyn]: https://github.com/mjtamlyn [wackerbarth]: https://github.com/wackerbarth [shezi]: https://github.com/shezi +[radiosilence]: https://github.com/radiosilence From 87029122c287b4a03e309a432dc9f9668efd7c0e Mon Sep 17 00:00:00 2001 From: Steven Gregory Date: Tue, 15 Jan 2013 13:49:48 -0700 Subject: [PATCH 35/40] Added a new file 'relations_slug.py' that tests Nullable Foreign Keys and the SlugRelatedField --- rest_framework/tests/relations_slug.py | 281 +++++++++++++++++++++++++ 1 file changed, 281 insertions(+) create mode 100644 rest_framework/tests/relations_slug.py diff --git a/rest_framework/tests/relations_slug.py b/rest_framework/tests/relations_slug.py new file mode 100644 index 000000000..d56f4d4ac --- /dev/null +++ b/rest_framework/tests/relations_slug.py @@ -0,0 +1,281 @@ +from django.test import TestCase +from rest_framework import serializers +from rest_framework.compat import patterns, url +from rest_framework.tests.models import NullableForeignKeySource, ForeignKeyTarget + +def dummy_view(request, pk): + pass + + +# Nullable ForeignKey +class SluggedNullableForeignKeySourceSerializer(serializers.ModelSerializer): + target = serializers.SlugRelatedField(slug_field='name') + class Meta: + model = NullableForeignKeySource + +class NullOKSluggedNullableForeignKeySourceSerializer(serializers.ModelSerializer): + target = serializers.SlugRelatedField(slug_field='name', null=True) + class Meta: + model = NullableForeignKeySource + +class DefaultSluggedNullableForeignKeySourceSerializer(serializers.ModelSerializer): + target = serializers.SlugRelatedField(slug_field='name', default='N/A') + class Meta: + model = NullableForeignKeySource + +class NotRequiredSluggedNullableForeignKeySourceSerializer(serializers.ModelSerializer): + target = serializers.SlugRelatedField(slug_field='name', required=False) + class Meta: + model = NullableForeignKeySource + + +class SluggedNullableForeignKeyTests(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_slug_foreign_key_retrieve_with_null(self): + queryset = NullableForeignKeySource.objects.all() + + default_expected = [ + {'name': u'source-1', 'target': 'target-1'}, + {'name': u'source-2', 'target': 'target-1'}, + {'name': u'source-3', 'target': 'N/A'}, + ] + expected = [ + {'name': u'source-1', 'target': 'target-1'}, + {'name': u'source-2', 'target': 'target-1'}, + {'name': u'source-3', 'target': None}, + ] + + serializer = DefaultSluggedNullableForeignKeySourceSerializer(queryset) + self.assertEquals(serializer.data, default_expected) + + serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(queryset) + self.assertEquals(serializer.data, expected) + + serializer = NullOKSluggedNullableForeignKeySourceSerializer(queryset) + self.assertEquals(serializer.data, expected) + + serializer = SluggedNullableForeignKeySourceSerializer(queryset) + #Throws + self.assertEquals(serializer.data, expected) + + def test_slug_foreign_key_create_with_valid_null(self): + data = {'name': u'source-4', 'target': None} + default_data = {'name': u'source-4', 'target': 'N/A'} + + serializer = SluggedNullableForeignKeySourceSerializer(data=data) + self.assertFalse(serializer.is_valid()) + self.assertEquals(serializer.errors, {'target': [u'Value may not be null']}) + + + #If attribute not required, data should match + serializer = NullOKSluggedNullableForeignKeySourceSerializer(data=data) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + #BUG: Throws AttributeError: "NoneType object has no attribute 'name'" + self.assertEquals(serializer.data, data) + self.assertEqual(obj.name, u'source-4') + + #If default = 'N/A' then target should pass validation, and be the default ('N/A') + serializer = DefaultSluggedNullableForeignKeySourceSerializer(data=data) + #BUG: test case fails + self.assertTrue(serializer.is_valid()) + #BUG: serializer.errors = {'target': [u'Value may not be null']} + #BUG: Serializer does not use default value to save object + obj = serializer.save() + #BUG: Throws AttributeError - NoneType object has no attribute 'name' + self.assertEquals(serializer.data, data) + self.assertEqual(obj.name, u'source-4') + + #If null = True then target should be None + serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(data=data) + #BUG: test case fails + self.assertTrue(serializer.is_valid()) + #BUG: serializer.errors = {'target': [u'Value may not be null']} + #BUG: serializer does not save object (But it can because its not required) + obj = serializer.save() + #BUG: Throws AttributeError - NoneType object has no attribute 'name' + self.assertEquals(serializer.data, data) + self.assertEqual(obj.name, u'source-4') + + # Ensure source 4 is created, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + default_expected = [ + {'name': u'source-1', 'target': 'target-1'}, + {'name': u'source-2', 'target': 'target-1'}, + {'name': u'source-3', 'target': 'N/A'}, + {'name': u'source-4', 'target': 'N/A'} + ] + expected = [ + {'name': u'source-1', 'target': 'target-1'}, + {'name': u'source-2', 'target': 'target-1'}, + {'name': u'source-3', 'target': None}, + {'name': u'source-4', 'target': None} + ] + serializer = NullOKSluggedNullableForeignKeySourceSerializer(data=data) + self.assertEquals(serializer.data, expected) + serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(data=data) + self.assertEquals(serializer.data, expected) + serializer = DefaultSluggedNullableForeignKeySourceSerializer(data=data) + self.assertEquals(serializer.data, default_expected) + + def test_slug_foreign_key_create_with_valid_emptystring(self): + """ + The emptystring should be interpreted as null in the context + of relationships. + """ + data = {'name': u'source-4', 'target': ''} + expected_data = {'name': u'source-4', 'target': None} + + serializer = SluggedNullableForeignKeySourceSerializer(data=data) + self.assertFalse(serializer.is_valid()) + self.assertEquals(serializer.errors, {'target': [u'Value may not be null']}) + + serializer = NullOKSluggedNullableForeignKeySourceSerializer(data=data) + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' + self.assertEquals(serializer.data, expected_data) + self.assertEqual(obj.name, u'source-4') + + serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(data=data) + #BUG: is_valid() is False + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' + self.assertEquals(serializer.data, expected_data) + self.assertEqual(obj.name, u'source-4') + + serializer = DefaultSluggedNullableForeignKeySourceSerializer(data=data) + #BUG: is_valid() is False + self.assertTrue(serializer.is_valid()) + obj = serializer.save() + #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' + self.assertEquals(serializer.data, expected_data) + self.assertEqual(obj.name, u'source-4') + + # Ensure source 4 is created, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + default_expected = [ + {'name': u'source-1', 'target': 'target-1'}, + {'name': u'source-2', 'target': 'target-1'}, + {'name': u'source-3', 'target': 'N/A'}, + {'name': u'source-4', 'target': 'N/A'} + ] + expected = [ + {'name': u'source-1', 'target': 'target-1'}, + {'name': u'source-2', 'target': 'target-1'}, + {'name': u'source-3', 'target': None}, + {'name': u'source-4', 'target': None} + ] + #BUG: All serializers fail here + serializer = DefaultSluggedNullableForeignKeySourceSerializer(queryset) + self.assertEquals(serializer.data, default_expected) + serializer = NullOKSluggedNullableForeignKeySourceSerializer(queryset) + self.assertEquals(serializer.data, expected) + serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(queryset) + self.assertEquals(serializer.data, expected) + + def test_slug_foreign_key_update_with_valid_null(self): + data = {'name': u'source-1', 'target': None} + default_data = {'name': u'source-1', 'target': 'N/A'} + instance = NullableForeignKeySource.objects.get(pk=1) + + serializer = SluggedNullableForeignKeySourceSerializer(instance, data=data) + self.assertFalse(serializer.is_valid()) + self.assertEquals(serializer.errors, {'target': [u'Value may not be null']}) + + serializer = DefaultSluggedNullableForeignKeySourceSerializer(instance, data=data) + #BUG: is_valid() is False + self.assertTrue(serializer.is_valid()) + self.assertEquals(serializer.data, default_data) + serializer.save() + + serializer = NullOKSluggedNullableForeignKeySourceSerializer(instance, data=data) + self.assertTrue(serializer.is_valid()) + #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' + self.assertEquals(serializer.data, data) + serializer.save() + + + serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(instance, data=data) + #BUG: is_valid() is False + self.assertTrue(serializer.is_valid()) + #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' + self.assertEquals(serializer.data, data) + serializer.save() + + # Ensure source 1 is updated, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + expected = [ + {'name': u'source-1', 'target': None}, + {'name': u'source-2', 'target': 'target-1'}, + {'name': u'source-3', 'target': None}, + ] + serializer = NullOKSluggedNullableForeignKeySourceSerializer(queryset) + self.assertEquals(serializer.data, expected) + + serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(queryset) + self.assertEquals(serializer.data, expected) + + expected = [ + {'name': u'source-1', 'target': 'N/A'}, + {'name': u'source-2', 'target': 'target-1'}, + {'name': u'source-3', 'target': 'N/A'}, + ] + serializer = NullOKSluggedNullableForeignKeySourceSerializer(queryset) + self.assertEquals(serializer.data, expected) + + def test_slug_foreign_key_update_with_valid_emptystring(self): + """ + The emptystring should be interpreted as null in the context + of relationships. + """ + data = {'name': u'source-1', 'target': ''} + default_data = {'name': u'source-1', 'target': 'N/A'} + expected_data = {'name': u'source-1', 'target': None} + instance = NullableForeignKeySource.objects.get(pk=1) + + serializer = SluggedNullableForeignKeySourceSerializer(instance, data=data) + self.assertFalse(serializer.is_valid()) + self.assertEquals(serializer.errors, {'target': [u'Value may not be null']}) + + serializer = DefaultSluggedNullableForeignKeySourceSerializer(instance, data=data) + #BUG: is_valid() is False + self.assertTrue(serializer.is_valid()) + self.assertEquals(serializer.data, default_data) + serializer.save() + + serializer = NullOKSluggedNullableForeignKeySourceSerializer(instance, data=data) + self.assertTrue(serializer.is_valid()) + #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' + self.assertEquals(serializer.data, data) + serializer.save() + + serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(instance, data=data) + #BUG: is_valid() is False + self.assertTrue(serializer.is_valid()) + #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' + self.assertEquals(serializer.data, data) + serializer.save() + + # Ensure source 1 is updated, and everything else is as expected + queryset = NullableForeignKeySource.objects.all() + expected = [ + {'name': u'source-1', 'target': None}, + {'name': u'source-2', 'target': 'target-1'}, + {'name': u'source-3', 'target': None}, + ] + serializer = NullOKSluggedNullableForeignKeySourceSerializer(queryset) + self.assertEquals(serializer.data, expected) + serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(queryset) + self.assertEquals(serializer.data, expected) + From eb3d4d0e93b07d245232685d4fe3ad78144ea933 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 16 Jan 2013 14:32:51 +0000 Subject: [PATCH 36/40] Drop bits of relations_slug tests which don't mirror existing tests. --- rest_framework/relations.py | 3 + rest_framework/tests/relations_hyperlink.py | 2 + rest_framework/tests/relations_pk.py | 2 +- rest_framework/tests/relations_slug.py | 246 ++++---------------- 4 files changed, 47 insertions(+), 206 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 5e4552b7a..7ded38918 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -105,6 +105,9 @@ class RelatedField(WritableField): value = getattr(obj, self.source or field_name) except ObjectDoesNotExist: return None + + if value is None: + return None return self.to_native(value) def field_from_native(self, data, files, field_name, into): diff --git a/rest_framework/tests/relations_hyperlink.py b/rest_framework/tests/relations_hyperlink.py index 579136704..7d65eae79 100644 --- a/rest_framework/tests/relations_hyperlink.py +++ b/rest_framework/tests/relations_hyperlink.py @@ -3,6 +3,7 @@ from rest_framework import serializers from rest_framework.compat import patterns, url from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource + def dummy_view(request, pk): pass @@ -16,6 +17,7 @@ urlpatterns = patterns('', url(r'^nullableonetoonesource/(?P[0-9]+)/$', dummy_view, name='nullableonetoonesource-detail'), ) + class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer): sources = serializers.ManyHyperlinkedRelatedField(view_name='manytomanysource-detail') diff --git a/rest_framework/tests/relations_pk.py b/rest_framework/tests/relations_pk.py index 548358603..dd1e86b57 100644 --- a/rest_framework/tests/relations_pk.py +++ b/rest_framework/tests/relations_pk.py @@ -206,7 +206,7 @@ class PKForeignKeyTests(TestCase): expected = [ {'id': 1, 'name': u'target-1', 'sources': [1, 2, 3]}, {'id': 2, 'name': u'target-2', 'sources': []}, - ] + ] self.assertEquals(new_serializer.data, expected) serializer.save() diff --git a/rest_framework/tests/relations_slug.py b/rest_framework/tests/relations_slug.py index d56f4d4ac..503b61e81 100644 --- a/rest_framework/tests/relations_slug.py +++ b/rest_framework/tests/relations_slug.py @@ -1,36 +1,18 @@ from django.test import TestCase from rest_framework import serializers -from rest_framework.compat import patterns, url from rest_framework.tests.models import NullableForeignKeySource, ForeignKeyTarget -def dummy_view(request, pk): - pass - -# Nullable ForeignKey -class SluggedNullableForeignKeySourceSerializer(serializers.ModelSerializer): - target = serializers.SlugRelatedField(slug_field='name') - class Meta: - model = NullableForeignKeySource - -class NullOKSluggedNullableForeignKeySourceSerializer(serializers.ModelSerializer): +class NullableSlugSourceSerializer(serializers.ModelSerializer): target = serializers.SlugRelatedField(slug_field='name', null=True) - class Meta: - model = NullableForeignKeySource -class DefaultSluggedNullableForeignKeySourceSerializer(serializers.ModelSerializer): - target = serializers.SlugRelatedField(slug_field='name', default='N/A') - class Meta: - model = NullableForeignKeySource - -class NotRequiredSluggedNullableForeignKeySourceSerializer(serializers.ModelSerializer): - target = serializers.SlugRelatedField(slug_field='name', required=False) class Meta: model = NullableForeignKeySource -class SluggedNullableForeignKeyTests(TestCase): +# TODO: M2M Tests, FKTests (Non-nulable), One2One +class SlugNullableForeignKeyTests(TestCase): def setUp(self): target = ForeignKeyTarget(name='target-1') target.save() @@ -40,242 +22,96 @@ class SluggedNullableForeignKeyTests(TestCase): source = NullableForeignKeySource(name='source-%d' % idx, target=target) source.save() - def test_slug_foreign_key_retrieve_with_null(self): + def test_foreign_key_retrieve_with_null(self): queryset = NullableForeignKeySource.objects.all() - - default_expected = [ - {'name': u'source-1', 'target': 'target-1'}, - {'name': u'source-2', 'target': 'target-1'}, - {'name': u'source-3', 'target': 'N/A'}, - ] + serializer = NullableSlugSourceSerializer(queryset) expected = [ - {'name': u'source-1', 'target': 'target-1'}, - {'name': u'source-2', 'target': 'target-1'}, - {'name': u'source-3', 'target': None}, + {'id': 1, 'name': u'source-1', 'target': 'target-1'}, + {'id': 2, 'name': u'source-2', 'target': 'target-1'}, + {'id': 3, 'name': u'source-3', 'target': None}, ] - - serializer = DefaultSluggedNullableForeignKeySourceSerializer(queryset) - self.assertEquals(serializer.data, default_expected) - - serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(queryset) self.assertEquals(serializer.data, expected) - serializer = NullOKSluggedNullableForeignKeySourceSerializer(queryset) - self.assertEquals(serializer.data, expected) - - serializer = SluggedNullableForeignKeySourceSerializer(queryset) - #Throws - self.assertEquals(serializer.data, expected) - - def test_slug_foreign_key_create_with_valid_null(self): - data = {'name': u'source-4', 'target': None} - default_data = {'name': u'source-4', 'target': 'N/A'} - - serializer = SluggedNullableForeignKeySourceSerializer(data=data) - self.assertFalse(serializer.is_valid()) - self.assertEquals(serializer.errors, {'target': [u'Value may not be null']}) - - - #If attribute not required, data should match - serializer = NullOKSluggedNullableForeignKeySourceSerializer(data=data) + def test_foreign_key_create_with_valid_null(self): + data = {'id': 4, 'name': u'source-4', 'target': None} + serializer = NullableSlugSourceSerializer(data=data) self.assertTrue(serializer.is_valid()) obj = serializer.save() - #BUG: Throws AttributeError: "NoneType object has no attribute 'name'" - self.assertEquals(serializer.data, data) - self.assertEqual(obj.name, u'source-4') - - #If default = 'N/A' then target should pass validation, and be the default ('N/A') - serializer = DefaultSluggedNullableForeignKeySourceSerializer(data=data) - #BUG: test case fails - self.assertTrue(serializer.is_valid()) - #BUG: serializer.errors = {'target': [u'Value may not be null']} - #BUG: Serializer does not use default value to save object - obj = serializer.save() - #BUG: Throws AttributeError - NoneType object has no attribute 'name' - self.assertEquals(serializer.data, data) - self.assertEqual(obj.name, u'source-4') - - #If null = True then target should be None - serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(data=data) - #BUG: test case fails - self.assertTrue(serializer.is_valid()) - #BUG: serializer.errors = {'target': [u'Value may not be null']} - #BUG: serializer does not save object (But it can because its not required) - obj = serializer.save() - #BUG: Throws AttributeError - NoneType object has no attribute 'name' self.assertEquals(serializer.data, data) self.assertEqual(obj.name, u'source-4') # Ensure source 4 is created, and everything else is as expected queryset = NullableForeignKeySource.objects.all() - default_expected = [ - {'name': u'source-1', 'target': 'target-1'}, - {'name': u'source-2', 'target': 'target-1'}, - {'name': u'source-3', 'target': 'N/A'}, - {'name': u'source-4', 'target': 'N/A'} - ] + serializer = NullableSlugSourceSerializer(queryset) expected = [ - {'name': u'source-1', 'target': 'target-1'}, - {'name': u'source-2', 'target': 'target-1'}, - {'name': u'source-3', 'target': None}, - {'name': u'source-4', 'target': None} + {'id': 1, 'name': u'source-1', 'target': 'target-1'}, + {'id': 2, 'name': u'source-2', 'target': 'target-1'}, + {'id': 3, 'name': u'source-3', 'target': None}, + {'id': 4, 'name': u'source-4', 'target': None} ] - serializer = NullOKSluggedNullableForeignKeySourceSerializer(data=data) self.assertEquals(serializer.data, expected) - serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(data=data) - self.assertEquals(serializer.data, expected) - serializer = DefaultSluggedNullableForeignKeySourceSerializer(data=data) - self.assertEquals(serializer.data, default_expected) - def test_slug_foreign_key_create_with_valid_emptystring(self): + def test_foreign_key_create_with_valid_emptystring(self): """ The emptystring should be interpreted as null in the context of relationships. """ - data = {'name': u'source-4', 'target': ''} - expected_data = {'name': u'source-4', 'target': None} - - serializer = SluggedNullableForeignKeySourceSerializer(data=data) - self.assertFalse(serializer.is_valid()) - self.assertEquals(serializer.errors, {'target': [u'Value may not be null']}) - - serializer = NullOKSluggedNullableForeignKeySourceSerializer(data=data) + data = {'id': 4, 'name': u'source-4', 'target': ''} + expected_data = {'id': 4, 'name': u'source-4', 'target': None} + serializer = NullableSlugSourceSerializer(data=data) self.assertTrue(serializer.is_valid()) obj = serializer.save() - #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' - self.assertEquals(serializer.data, expected_data) - self.assertEqual(obj.name, u'source-4') - - serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(data=data) - #BUG: is_valid() is False - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' - self.assertEquals(serializer.data, expected_data) - self.assertEqual(obj.name, u'source-4') - - serializer = DefaultSluggedNullableForeignKeySourceSerializer(data=data) - #BUG: is_valid() is False - self.assertTrue(serializer.is_valid()) - obj = serializer.save() - #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' self.assertEquals(serializer.data, expected_data) self.assertEqual(obj.name, u'source-4') # Ensure source 4 is created, and everything else is as expected queryset = NullableForeignKeySource.objects.all() - default_expected = [ - {'name': u'source-1', 'target': 'target-1'}, - {'name': u'source-2', 'target': 'target-1'}, - {'name': u'source-3', 'target': 'N/A'}, - {'name': u'source-4', 'target': 'N/A'} - ] + serializer = NullableSlugSourceSerializer(queryset) expected = [ - {'name': u'source-1', 'target': 'target-1'}, - {'name': u'source-2', 'target': 'target-1'}, - {'name': u'source-3', 'target': None}, - {'name': u'source-4', 'target': None} + {'id': 1, 'name': u'source-1', 'target': 'target-1'}, + {'id': 2, 'name': u'source-2', 'target': 'target-1'}, + {'id': 3, 'name': u'source-3', 'target': None}, + {'id': 4, 'name': u'source-4', 'target': None} ] - #BUG: All serializers fail here - serializer = DefaultSluggedNullableForeignKeySourceSerializer(queryset) - self.assertEquals(serializer.data, default_expected) - serializer = NullOKSluggedNullableForeignKeySourceSerializer(queryset) - self.assertEquals(serializer.data, expected) - serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(queryset) self.assertEquals(serializer.data, expected) - def test_slug_foreign_key_update_with_valid_null(self): - data = {'name': u'source-1', 'target': None} - default_data = {'name': u'source-1', 'target': 'N/A'} + def test_foreign_key_update_with_valid_null(self): + data = {'id': 1, 'name': u'source-1', 'target': None} instance = NullableForeignKeySource.objects.get(pk=1) - - serializer = SluggedNullableForeignKeySourceSerializer(instance, data=data) - self.assertFalse(serializer.is_valid()) - self.assertEquals(serializer.errors, {'target': [u'Value may not be null']}) - - serializer = DefaultSluggedNullableForeignKeySourceSerializer(instance, data=data) - #BUG: is_valid() is False + serializer = NullableSlugSourceSerializer(instance, data=data) self.assertTrue(serializer.is_valid()) - self.assertEquals(serializer.data, default_data) - serializer.save() - - serializer = NullOKSluggedNullableForeignKeySourceSerializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' - self.assertEquals(serializer.data, data) - serializer.save() - - - serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(instance, data=data) - #BUG: is_valid() is False - self.assertTrue(serializer.is_valid()) - #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' self.assertEquals(serializer.data, data) serializer.save() # Ensure source 1 is updated, and everything else is as expected queryset = NullableForeignKeySource.objects.all() + serializer = NullableSlugSourceSerializer(queryset) expected = [ - {'name': u'source-1', 'target': None}, - {'name': u'source-2', 'target': 'target-1'}, - {'name': u'source-3', 'target': None}, + {'id': 1, 'name': u'source-1', 'target': None}, + {'id': 2, 'name': u'source-2', 'target': 'target-1'}, + {'id': 3, 'name': u'source-3', 'target': None} ] - serializer = NullOKSluggedNullableForeignKeySourceSerializer(queryset) self.assertEquals(serializer.data, expected) - serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(queryset) - self.assertEquals(serializer.data, expected) - - expected = [ - {'name': u'source-1', 'target': 'N/A'}, - {'name': u'source-2', 'target': 'target-1'}, - {'name': u'source-3', 'target': 'N/A'}, - ] - serializer = NullOKSluggedNullableForeignKeySourceSerializer(queryset) - self.assertEquals(serializer.data, expected) - - def test_slug_foreign_key_update_with_valid_emptystring(self): + def test_foreign_key_update_with_valid_emptystring(self): """ The emptystring should be interpreted as null in the context of relationships. """ - data = {'name': u'source-1', 'target': ''} - default_data = {'name': u'source-1', 'target': 'N/A'} - expected_data = {'name': u'source-1', 'target': None} + data = {'id': 1, 'name': u'source-1', 'target': ''} + expected_data = {'id': 1, 'name': u'source-1', 'target': None} instance = NullableForeignKeySource.objects.get(pk=1) - - serializer = SluggedNullableForeignKeySourceSerializer(instance, data=data) - self.assertFalse(serializer.is_valid()) - self.assertEquals(serializer.errors, {'target': [u'Value may not be null']}) - - serializer = DefaultSluggedNullableForeignKeySourceSerializer(instance, data=data) - #BUG: is_valid() is False + serializer = NullableSlugSourceSerializer(instance, data=data) self.assertTrue(serializer.is_valid()) - self.assertEquals(serializer.data, default_data) - serializer.save() - - serializer = NullOKSluggedNullableForeignKeySourceSerializer(instance, data=data) - self.assertTrue(serializer.is_valid()) - #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' - self.assertEquals(serializer.data, data) - serializer.save() - - serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(instance, data=data) - #BUG: is_valid() is False - self.assertTrue(serializer.is_valid()) - #BUG: Throws AttributeError: 'NoneType' object has no attribute 'name' - self.assertEquals(serializer.data, data) + self.assertEquals(serializer.data, expected_data) serializer.save() # Ensure source 1 is updated, and everything else is as expected queryset = NullableForeignKeySource.objects.all() + serializer = NullableSlugSourceSerializer(queryset) expected = [ - {'name': u'source-1', 'target': None}, - {'name': u'source-2', 'target': 'target-1'}, - {'name': u'source-3', 'target': None}, + {'id': 1, 'name': u'source-1', 'target': None}, + {'id': 2, 'name': u'source-2', 'target': 'target-1'}, + {'id': 3, 'name': u'source-3', 'target': None} ] - serializer = NullOKSluggedNullableForeignKeySourceSerializer(queryset) self.assertEquals(serializer.data, expected) - serializer = NotRequiredSluggedNullableForeignKeySourceSerializer(queryset) - self.assertEquals(serializer.data, expected) - From 0756ca1f42cd7768f9450ec004a65664678ddf82 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 16 Jan 2013 14:35:30 +0000 Subject: [PATCH 37/40] Added @steve-gregory for nullable slug relation tests. See: #585 --- docs/topics/credits.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/topics/credits.md b/docs/topics/credits.md index b0b00c122..68d07f200 100644 --- a/docs/topics/credits.md +++ b/docs/topics/credits.md @@ -91,6 +91,7 @@ The following people have helped make REST framework great. * Richard Wackerbarth - [wackerbarth] * Johannes Spielmann - [shezi] * James Cleveland - [radiosilence] +* Steve Gregory - [steve-gregory] Many thanks to everyone who's contributed to the project. @@ -217,3 +218,4 @@ You can also contact [@_tomchristie][twitter] directly on twitter. [wackerbarth]: https://github.com/wackerbarth [shezi]: https://github.com/shezi [radiosilence]: https://github.com/radiosilence +[steve-gregory]: https://github.com/steve-gregory From fecfe57aeff8a10841b0ff1f51a7e4747ce897fb Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 16 Jan 2013 14:36:37 +0000 Subject: [PATCH 38/40] Updated release notes. --- docs/topics/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md index f43dc1d3d..74c3b74a6 100644 --- a/docs/topics/release-notes.md +++ b/docs/topics/release-notes.md @@ -19,6 +19,7 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi ### Master * Support json encoding of timedelta objects. +* Bugfix: Support nullable FKs with `SlugRelatedField`. ### 2.1.16 From 0f0a07b732a4bd90957c08b01d51e70c7e739d5d Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 16 Jan 2013 14:41:57 +0000 Subject: [PATCH 39/40] Note changes to Decimal rendering to json behavior. Fixes #582. --- docs/topics/release-notes.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md index 74c3b74a6..e00a5e937 100644 --- a/docs/topics/release-notes.md +++ b/docs/topics/release-notes.md @@ -25,13 +25,15 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi **Date**: 14th Jan 2013 -* Deprecate django.utils.simplejson in favor of Python 2.6's built-in json module. +* Deprecate `django.utils.simplejson` in favor of Python 2.6's built-in json module. * Bugfix: `auto_now`, `auto_now_add` and other `editable=False` fields now default to read-only. * Bugfix: PK fields now only default to read-only if they are an AutoField or if `editable=False`. * Bugfix: Validation errors instead of exceptions when serializers receive incorrect types. * Bugfix: Validation errors instead of exceptions when related fields receive incorrect types. * Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one +**Note**: Prior to 2.1.16, The Decimals would render in JSON using floating point if `simplejson` was installed, but otherwise render using string notation. Now that use of `simplejson` has been deprecated, Decimals will consistently render using string notation. See [#582] for more details. + ### 2.1.15 **Date**: 3rd Jan 2013 @@ -324,3 +326,4 @@ This change will not affect user code, so long as it's following the recommended [staticfiles13]: https://docs.djangoproject.com/en/1.3/howto/static-files/#with-a-template-tag [2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion [announcement]: rest-framework-2-announcement.md +[#582]: https://github.com/tomchristie/django-rest-framework/issues/582 From c07cdbdaca16e226c2e042443994a7579964faf3 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 17 Jan 2013 13:08:06 +0000 Subject: [PATCH 40/40] Kick travis into action --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index a70201661..d7cc1c6d6 100644 --- a/README.md +++ b/README.md @@ -295,4 +295,3 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [markdown]: http://pypi.python.org/pypi/Markdown/ [pyyaml]: http://pypi.python.org/pypi/PyYAML [django-filter]: http://pypi.python.org/pypi/django-filter -