From 4d1ab3204a9e1fd9f966f398b4eb1f32fd57b6fc Mon Sep 17 00:00:00 2001 From: Xavier Ordoquy Date: Thu, 18 Dec 2014 00:03:58 +0100 Subject: [PATCH] Fix the `pre_save` removal. --- docs/tutorial/6-viewsets-and-routers.md | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index 816e9da69..b57325c1c 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -44,8 +44,8 @@ Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl snippet = self.get_object() return Response(snippet.highlighted) - def pre_save(self, obj): - obj.owner = self.request.user + def perform_create(self, serializer): + serializer.save(owner=self.request.user) This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations. @@ -53,6 +53,20 @@ Notice that we've also used the `@detail_route` decorator to create a custom act Custom actions which use the `@detail_route` decorator will respond to `GET` requests. We can use the `methods` argument if we wanted an action that responded to `POST` requests. +Also note that we are setting the `owner` as the `request.user`. However, to make this work, we need to customize the associated serializer: + + class SnippetSerializer(serializers.HyperlinkedModelSerializer): + owner = serializers.ReadOnlyField(source='owner.username') + highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') + + class Meta: + model = Snippet + fields = ('url', 'highlight', 'owner', + 'title', 'code', 'linenos', 'language', 'style') + + def create(self, validated_data): + return Snippet.objects.create(**validated_data) + ## Binding ViewSets to URLs explicitly The handler methods only get bound to the actions when we define the URLConf.