V-D
V-D

Reputation: 23

Django REST framework: validate using request method

Is it possible to validate request method (POST, PUT, GET...) together with queryset in example below?

    def validate_title(self, value):
      qs = Place.objects.filter(title__iexact=value)
      if qs.exists():
        raise serializers.ValidationError("Duplicated title")

      return value

Upvotes: 1

Views: 1110

Answers (1)

JPG
JPG

Reputation: 88429

You could access the request method by using the serializer context as below,

def validate_title(self, value):
    request_method = self.context['request'].method # change is here
    qs = Place.objects.filter(title__iexact=value)
    if qs.exists():
        raise serializers.ValidationError("Duplicated title")

    return value

Upvotes: 5

Related Questions