Set Specific Error in Django Form Clean

Sometimes we have to create our own validation by overriding some method in Form class in Django. there are a lot of way to do this, you can refer to this documentation.

But if we override clean method. We have to set to which field error message supposed to be displayed.

Here is example model and my form if I need to set specific error to manufacture field.

class Car(models.Model):
    serie = models.CharField(max_length=120)
    manufacture = models.CharField(max_length=120)

    def __unicode__(self):
        return self.serie

class CarForm(forms.ModelForm):
    def clean(self):
        cleaned_data = super(CarForm, self).clean()
        if cleaned_data.get('manufacture') == 'HONDA':
            self.add_error('manufacture', 'Choose another manufacture.')
        return cleaned_data

    class Meta:
        model = Car

With add_error we can set to whatever field we want. If we raise error with forms.ValidationError, error message will displayed globally.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.