Django rest framework: restriction fields that can be updated

I want users to be able to update only one specific field. eg:

models.py

class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) class Meta: ordering = ('created',) 

serializer.py

 class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style') 

views.py

 class SnippetList(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer 

after creating Snippet user should only update the title .

I know that I can achieve something like this:

serializers.py

 def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.title = validated_data.get('title', instance.title) instance.save() return instance 

in the serializer class. but I want to know if there is a way that the viewed api only shows the title field in the edit form? and also skip checking for fields that are not required?

+8
django django-rest-framework
source share
2 answers

The Django REST Framework provides read_only and write_only to control what is used for editing and what is not.

serializers.py

 class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style') extra_kwargs = { 'id': {'read_only': True}, 'code': {'read_only': True}, 'lineos': {'read_only': True}, 'language': {'read_only': True}, 'style': {'read_only': True} } 

The above will return all fields for read requests, but only the title will be writable. You can find more information in the official documentation: http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields

+4
source share

This code will update the parameters sent in the request, will be updates.

views.py

 class SnippetSerializer(viewset.ModelViewSet): queryset = Snippet.objects.all() serializer_class = SnippetSerializer http_method_names = ['put'] def update(self, request, *args, **kwargs): snippet = self.get_object() serializer = self.get_serializer(snippet, data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) 
0
source share

All Articles