1

I am trying to abstract my endpoints by using the Viewsets and for some reasons the update() method to one of the endpoints isn't saving an updated field.

How do I update the fields?

NB: I am testing using Postman using PUT method

serializers.py:

class UpdateArticleSerializer(serializers.Serializer):

    title = serializers.CharField(max_length=250, required=True)
    body = serializers.CharField()
    image_url = serializers.URLField()
    keypoint = serializers.ListField()
    country = CountrySerializer(read_only=True)
    category = CategorySerializer(read_only=True)

    def create(self, validated_data):
        return Article(**validated_data)

    def update(self, instance, validated_data):
        instance.title = validated_data.get('title', instance.title)
        instance.body = validated_data.get('body', instance.body)
        instance.image_url = validated_data.get('image_url', 
            instance.image_url)
        instance.keypoint = validated_data.get('keypoint', 
            instance.keypoint)
        instance.country = validated_data.get('country', 
            instance.country)
        instance.category = validated_data.get('category', 
            instance.category)
        instance.save()

        return instance

views.py [update method]:

    def update(self, request, pk=None):
        article = Article.objects.get(id=pk)
        serializer = UpdateArticleSerializer(data=request.data)

        if article.author == request.user:
            if article.is_published != True:

                if serializer.is_valid():
                    serializer.save(author=request.user)
               queryset = article
               serializer = ArticleSerializer(queryset)   
                return 
                     Response(jsend.success({'post':serializer.data}), 
                     status=status.HTTP_200_OK)
            else: 
                return Response((jsend.error('Published post cannot be 
                  edited')), status=status.HTTP_409_CONFLICT)
        else:
            return Response((jsend.error("You are not authorized to 
            perform this action")), status=status.HTTP_403_FORBIDDEN)
zencoder
  • 169
  • 2
  • 13

1 Answers1

5
serializer = UpdateArticleSerializer(data=request.data)

You don't provide an existing instance thus serializer.save() will be routed to serializer.create()

it should instead be something like:

serializer = UpdateArticleSerializer(instance=self.get_object(), data=request.data)
Linovia
  • 19,812
  • 4
  • 47
  • 48
  • Thanks @Linovia, problem solved. Check here: https://stackoverflow.com/questions/31173324/django-rest-framework-update-field – zencoder Sep 19 '18 at 20:14
  • Thanks, your comment helped to solve my problem, although I had to pass the 'request' as a context: UpdateSerializer(.... context={'request': request}) – Gabor Mar 21 '21 at 10:10