This commit is contained in:
Xavier Ordoquy 2014-12-17 23:05:28 +00:00
commit fe71f1b7a3

View File

@ -44,8 +44,8 @@ Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl
snippet = self.get_object() snippet = self.get_object()
return Response(snippet.highlighted) return Response(snippet.highlighted)
def pre_save(self, obj): def perform_create(self, serializer):
obj.owner = self.request.user 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. 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. 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 ## Binding ViewSets to URLs explicitly
The handler methods only get bound to the actions when we define the URLConf. The handler methods only get bound to the actions when we define the URLConf.