Django: Display a field specific error in your Form/ModelForm

Django forms are incredibly flexible, but they're also a little cumbersome when it comes to errors.

The following example shows you that you can display an error for:

  • a specific field
  • a specific field from another field
  • the form as a whole
class EventForm(forms.ModelForm):
class Meta:
model = Event

title = forms.CharField(required = True)
lawyer = forms.CharField(required = True)
when = forms.CharField(max_length = 10, min_length = 10, widget = DateInput(format="%d-%m-%Y"))

def clean_when(self):
value = self.cleaned_data.get(field_name)

if value:
try:
value = datetime.datetime.strptime(value, '%d-%m-%Y')
except ValueError:
value = None
# Displays an error under the title field, even though it's validating as the "when" field.
self._errors['title'] = ['Invalid date given.']

return value


def clean_lawyer(self):
# Display error for the lawyer field
raise forms.ValidationError("OBJECTION!")


def clean(self):
data = super(EventForm, self).clean()

# In the clean() even, errors raised will display as an error for the form (non field error)
raise forms.ValidationError('Just for the hell of it.')

return data

Raising an error is the preferred way of doing things, but if you need to do multi-line errors then it's possible to use the self._errors method.

image
How many errors can you see here?

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog