diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 9576a7f0b..56fab90d3 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -96,7 +96,11 @@ Now that snippets are associated with the user that created them, let's update o owner = serializers.Field(source='owner.username') -**Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class. +**Note**: Make sure you also add `'owner',` to the list of excluded fields in the inner `Meta` class, like so: + + exclude = ('owner', ) + +This makes the owner field not required, which is correct, because we set it in our `pre_save()` method. This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language. @@ -188,4 +192,4 @@ We've now got a fairly fine-grained set of permissions on our Web API, and end p In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our hightlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system. -[tut-5]: 5-relationships-and-hyperlinked-apis.md \ No newline at end of file +[tut-5]: 5-relationships-and-hyperlinked-apis.md diff --git a/rest_framework/tests/generics.py b/rest_framework/tests/generics.py index a8279ef2b..51b9c83a4 100644 --- a/rest_framework/tests/generics.py +++ b/rest_framework/tests/generics.py @@ -301,3 +301,34 @@ class TestCreateModelWithAutoNowAddField(TestCase): self.assertEquals(response.status_code, status.HTTP_201_CREATED) created = self.objects.get(id=1) self.assertEquals(created.content, 'foobar') + + +class CommentSerializer(serializers.ModelSerializer): + class Meta: + model = Comment + exclude = ('created', 'email') + + +class ViewUsingPreSave(generics.CreateAPIView): + serializer_class = CommentSerializer + model = Comment + + def pre_save(self, obj): + obj.email = 'overriden@address.com' + + +class TestPreSave(TestCase): + def setUp(self): + self.view = ViewUsingPreSave.as_view() + + def test_pre_save_gets_called(self): + """ + The email address is set at pre_save time. + """ + content = {'content': 'some content'} + request = factory.post('/', json.dumps(content), + content_type='application/json') + response = self.view(request).render() + self.assertEquals(response.status_code, status.HTTP_201_CREATED) + self.assertEquals(Comment.objects.get(pk=1).email, 'overriden@address.com') +