Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise field error in models clean method

How to raise a field bound ValidationException in django's models clean method?

from django.core.exceptions import ValidationError

def clean(self):
    if self.title:
        raise ValidationError({'title': 'not ok'})

The above does not add the error to the title field (when using a form), but to the non field errors (__all__).

I know how to do it inside a form (self._errors['title'] = self.error_class([msg])), but self._errors does not exist inside the models clean method.

like image 323
Zardoz Avatar asked May 19 '13 10:05

Zardoz


1 Answers

According to the Django docs, this is possible using model.clean()

This provides everything you asked for!

The box above the note appears to be what you are looking for:

raise ValidationError({
    'title': ValidationError(_('Missing title.'), code='required'),
    'pub_date': ValidationError(_('Invalid date.'), code='invalid'),
})

The code parameter is a kwarg and therefor optional. (It's in the example so i've pasted it over)

in your case my guess is you needs something like this:

raise ValidationError({
    'title': ValidationError('not ok'),
})
like image 168
Nebulosar Avatar answered Sep 28 '22 05:09

Nebulosar