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.

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

    def __unicode__(self):
        return self.serie


# forms.py
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.

Reference: https://docs.djangoproject.com/en/1.8/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s