How to write a Custom field Validation for ModelSerializers in Django Rest Framework(DRF) similar to Form Validation in Django?

12,853

You can add a validate_name() method to your serializer which will perform this validation. It should return the validated value or raise a ValidationError.

To perform the check whether user has entered a full name or not, we will use str.split() which will return all the words in the string. If the no. of words in the string is not greater than 1, then we will raise a ValidationError. Otherwise, we return the value.

class TaskSerializer(serializers.ModelSerializer):

    def validate_name(self, value):
        """
        Check that value is a valid name.
        """
        if not len(value.split()) > 1: # check name has more than 1 word
            raise serializers.ValidationError("Please enter full name") # raise ValidationError
        return value
Share:
12,853

Related videos on Youtube

Rahul
Author by

Rahul

Focus.Do it.

Updated on July 13, 2022

Comments

  • Rahul
    Rahul almost 2 years

    I am currently creating an api based on DRF.I have a model which is like:

    class Task(models.Model):
        name = models.CharField(max_length = 255)
        completed = models.BooleanField(default = False)
        description = models.TextField()
        text = models.TextField(blank = False, default = "this is my text" )
    
        def __unicode__(self):
            return self.name
    

    and the corresponding Serializer for this model is as :

    class TaskSerializer(serializers.ModelSerializer):
        class Meta:
            model = Task
            fields = ('name','description','completed','text')
    

    Now my question is that I want to validate the 'name' field of my model while taking up data. For instance I may end checking the first name or second name of the user by a Python code similar to a Django Form:

    def clean_name(self):
        name = form.cleaned_data.get('name')
        first,second = name.split(' ')
        if second is None:
            raise forms.ValidationError("Please enter full name")
    

    I know of something called 'validate_(fieldname)' in Serializers.serializer class. But I want this to be used in Serializers.ModelSerializer instead.(Just similar to the custom forms validation in Django)

  • Rahul
    Rahul over 8 years
    Is there anything similar to cleaned_data in serializers?
  • Rahul Gupta
    Rahul Gupta over 8 years
    Yes, there exists serializer.validated_data which is accessible after .is_valid() has been called on the serializer.
  • Saurabh Kumar
    Saurabh Kumar over 8 years
    You can also use validators parameter in a field in model class, DRF will make use that as well. Helpful in enforcing a global validation. This answer is correct as well.