runitfirst
runitfirst

Reputation: 323

Validation does not get called on PATCH

i have a serializer like

class MySerializer(serializers.HyperlinkedModelSerializer):
    age = serializers.HiddenField(default=None)

    class Meta:
        model = Profile

    def validate_age(self, value):
        # this code not executing in update(put/patch) 

and view

class MyView(viewsets.GenericViewSet, mixins.UpdateModelMixin, mixins.CreateModelMixin):

    queryset = Profile.objects.all()
    serializer_class = MySerializer
    permission_classes = (IsAuthenticated,) 

When i POST the data validate_age get called, but not in the case of PATCH. Is it the intended behaviour or i am missing something ?

Upvotes: 2

Views: 934

Answers (2)

runitfirst
runitfirst

Reputation: 323

Just posting some detail in case anyone is having similar issue. Digging little bit deeper i found that my HiddenField was getting skipped here because of empty value i think. getattr(self.root, 'partial') was returning True which is because of PATCH.

APIView call partial_update of UpdateModelMixin on PATCH which sets partial to True. Although in case of PUT update(not partial_update) method get called. So i just changed HTTP Method from PATCH to PUT and everything working fine.

However Now the question is why HiddenField is getting ignored on partial update. :)

Upvotes: 3

Apoorv Kansal
Apoorv Kansal

Reputation: 3290

According to django-rest docs:

A [HiddenFiled] field class that does not take a value based on user input, but instead takes its value from a default value or callable.

http://www.django-rest-framework.org/api-guide/fields/#hiddenfield

As such, any user input for age will not actually run your specific validation code.

Another snippet:

This field type does not accept user input, but instead always returns it's default value to the validated_data in the serializer.

http://www.django-rest-framework.org/api-guide/validators/

I would suggest using some sort of IntegerField or even CharField depending on your business logic.

Upvotes: -2

Related Questions