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
01.
class
EventForm(forms.ModelForm):
02.
class
Meta:
03.
model
=
Event
04.
05.
title
=
forms.CharField(required
=
True
)
06.
lawyer
=
forms.CharField(required
=
True
)
07.
when
=
forms.CharField(max_length
=
10
, min_length
=
10
, widget
=
DateInput(format
=
"%d-%m-%Y"
))
08.
09.
def
clean_when(
self
):
10.
value
=
self
.cleaned_data.get(field_name)
11.
12.
if
value:
13.
try
:
14.
value
=
datetime.datetime.strptime(value,
'%d-%m-%Y'
)
15.
except
ValueError:
16.
value
=
None
17.
# Displays an error under the title field, even though it's validating as the "when" field.
18.
self
._errors[
'title'
]
=
[
'Invalid date given.'
]
19.
20.
return
value
21.
22.
23.
def
clean_lawyer(
self
):
24.
# Display error for the lawyer field
25.
raise
forms.ValidationError(
"OBJECTION!"
)
26.
27.
28.
def
clean(
self
):
29.
data
=
super(EventForm,
self
).clean()
30.
31.
# In the clean() even, errors raised will display as an error for the form (non field error)
32.
raise
forms.ValidationError(
'Just for the hell of it.'
)
33.
34.
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.