Form and field validation¶
Form validation happens when the data is cleaned. If you want to customize
this process, there are various places to make changes, each one serving a
different purpose. Three types of cleaning methods are run during form
processing. These are normally executed when you call the is_valid()
method on a form. There are other things that can also trigger cleaning and
validation (accessing the errors
attribute or calling full_clean()
directly), but normally they won’t be needed.
In general, any cleaning method can raise ValidationError
if there is a
problem with the data it is processing, passing the relevant information to
the ValidationError
constructor. See below
for the best practice in raising ValidationError
. If no ValidationError
is raised, the method should return the cleaned (normalized) data as a Python
object.
Most validation can be done using validators — helpers that can be reused.
Validators are functions (or callables) that take a single argument and raise
ValidationError
on invalid input. Validators are run after the field’s
to_python
and validate
methods have been called.
Validation of a form is split into several steps, which can be customized or
overridden:
-
The
to_python()
method on aField
is the first step in every
validation. It coerces the value to a correct datatype and raises
ValidationError
if that is not possible. This method accepts the raw
value from the widget and returns the converted value. For example, a
FloatField
will turn the data into a Pythonfloat
or raise a
ValidationError
. -
The
validate()
method on aField
handles field-specific validation
that is not suitable for a validator. It takes a value that has been
coerced to a correct datatype and raisesValidationError
on any error.
This method does not return anything and shouldn’t alter the value. You
should override it to handle validation logic that you can’t or don’t
want to put in a validator. -
The
run_validators()
method on aField
runs all of the field’s
validators and aggregates all the errors into a single
ValidationError
. You shouldn’t need to override this method. -
The
clean()
method on aField
subclass is responsible for running
to_python()
,validate()
, andrun_validators()
in the correct
order and propagating their errors. If, at any time, any of the methods
raiseValidationError
, the validation stops and that error is raised.
This method returns the clean data, which is then inserted into the
cleaned_data
dictionary of the form. -
The
clean_<fieldname>()
method is called on a form subclass – where
<fieldname>
is replaced with the name of the form field attribute.
This method does any cleaning that is specific to that particular
attribute, unrelated to the type of field that it is. This method is not
passed any parameters. You will need to look up the value of the field
inself.cleaned_data
and remember that it will be a Python object
at this point, not the original string submitted in the form (it will be
incleaned_data
because the general fieldclean()
method, above,
has already cleaned the data once).For example, if you wanted to validate that the contents of a
CharField
calledserialnumber
was unique,
clean_serialnumber()
would be the right place to do this. You don’t
need a specific field (it’s aCharField
), but you want a
formfield-specific piece of validation and, possibly, cleaning/normalizing
the data.The return value of this method replaces the existing value in
cleaned_data
, so it must be the field’s value fromcleaned_data
(even
if this method didn’t change it) or a new cleaned value. -
The form subclass’s
clean()
method can perform validation that requires
access to multiple form fields. This is where you might put in checks such as
“if fieldA
is supplied, fieldB
must contain a valid email address”.
This method can return a completely different dictionary if it wishes, which
will be used as thecleaned_data
.Since the field validation methods have been run by the time
clean()
is
called, you also have access to the form’serrors
attribute which
contains all the errors raised by cleaning of individual fields.Note that any errors raised by your
Form.clean()
override will not
be associated with any field in particular. They go into a special
“field” (called__all__
), which you can access via the
non_field_errors()
method if you need to. If you
want to attach errors to a specific field in the form, you need to call
add_error()
.Also note that there are special considerations when overriding
theclean()
method of aModelForm
subclass. (see the
ModelForm documentation for more information)
These methods are run in the order given above, one field at a time. That is,
for each field in the form (in the order they are declared in the form
definition), the Field.clean()
method (or its override) is run, then
clean_<fieldname>()
. Finally, once those two methods are run for every
field, the Form.clean()
method, or its override, is executed whether
or not the previous methods have raised errors.
Examples of each of these methods are provided below.
As mentioned, any of these methods can raise a ValidationError
. For any
field, if the Field.clean()
method raises a ValidationError
, any
field-specific cleaning method is not called. However, the cleaning methods
for all remaining fields are still executed.
Raising ValidationError
¶
In order to make error messages flexible and easy to override, consider the
following guidelines:
-
Provide a descriptive error
code
to the constructor:# Good ValidationError(_('Invalid value'), code='invalid') # Bad ValidationError(_('Invalid value'))
-
Don’t coerce variables into the message; use placeholders and the
params
argument of the constructor:# Good ValidationError( _('Invalid value: %(value)s'), params={'value': '42'}, ) # Bad ValidationError(_('Invalid value: %s') % value)
-
Use mapping keys instead of positional formatting. This enables putting
the variables in any order or omitting them altogether when rewriting the
message:# Good ValidationError( _('Invalid value: %(value)s'), params={'value': '42'}, ) # Bad ValidationError( _('Invalid value: %s'), params=('42',), )
-
Wrap the message with
gettext
to enable translation:# Good ValidationError(_('Invalid value')) # Bad ValidationError('Invalid value')
Putting it all together:
raise ValidationError( _('Invalid value: %(value)s'), code='invalid', params={'value': '42'}, )
Following these guidelines is particularly necessary if you write reusable
forms, form fields, and model fields.
While not recommended, if you are at the end of the validation chain
(i.e. your form clean()
method) and you know you will never need
to override your error message you can still opt for the less verbose:
ValidationError(_('Invalid value: %s') % value)
The Form.errors.as_data()
and
Form.errors.as_json()
methods
greatly benefit from fully featured ValidationError
s (with a code
name
and a params
dictionary).
Raising multiple errors¶
If you detect multiple errors during a cleaning method and wish to signal all
of them to the form submitter, it is possible to pass a list of errors to the
ValidationError
constructor.
As above, it is recommended to pass a list of ValidationError
instances
with code
s and params
but a list of strings will also work:
# Good raise ValidationError([ ValidationError(_('Error 1'), code='error1'), ValidationError(_('Error 2'), code='error2'), ]) # Bad raise ValidationError([ _('Error 1'), _('Error 2'), ])
Using validation in practice¶
The previous sections explained how validation works in general for forms.
Since it can sometimes be easier to put things into place by seeing each
feature in use, here are a series of small examples that use each of the
previous features.
Using validators¶
Django’s form (and model) fields support use of utility functions and classes
known as validators. A validator is a callable object or function that takes a
value and returns nothing if the value is valid or raises a
ValidationError
if not. These can be passed to a
field’s constructor, via the field’s validators
argument, or defined on the
Field
class itself with the default_validators
attribute.
Validators can be used to validate values inside the field, let’s have a look
at Django’s SlugField
:
from django.core import validators from django.forms import CharField class SlugField(CharField): default_validators = [validators.validate_slug]
As you can see, SlugField
is a CharField
with a customized validator
that validates that submitted text obeys to some character rules. This can also
be done on field definition so:
is equivalent to:
slug = forms.CharField(validators=[validators.validate_slug])
Common cases such as validating against an email or a regular expression can be
handled using existing validator classes available in Django. For example,
validators.validate_slug
is an instance of
a RegexValidator
constructed with the first
argument being the pattern: ^[-a-zA-Z0-9_]+$
. See the section on
writing validators to see a list of what is already
available and for an example of how to write a validator.
Form field default cleaning¶
Let’s first create a custom form field that validates its input is a string
containing comma-separated email addresses. The full class looks like this:
from django import forms from django.core.validators import validate_email class MultiEmailField(forms.Field): def to_python(self, value): """Normalize data to a list of strings.""" # Return an empty list if no input was given. if not value: return [] return value.split(',') def validate(self, value): """Check if value consists only of valid emails.""" # Use the parent's handling of required fields, etc. super().validate(value) for email in value: validate_email(email)
Every form that uses this field will have these methods run before anything
else can be done with the field’s data. This is cleaning that is specific to
this type of field, regardless of how it is subsequently used.
Let’s create a ContactForm
to demonstrate how you’d use this field:
class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() recipients = MultiEmailField() cc_myself = forms.BooleanField(required=False)
Use MultiEmailField
like any other form field. When the is_valid()
method is called on the form, the MultiEmailField.clean()
method will be
run as part of the cleaning process and it will, in turn, call the custom
to_python()
and validate()
methods.
Cleaning a specific field attribute¶
Continuing on from the previous example, suppose that in our ContactForm
,
we want to make sure that the recipients
field always contains the address
"fred@example.com"
. This is validation that is specific to our form, so we
don’t want to put it into the general MultiEmailField
class. Instead, we
write a cleaning method that operates on the recipients
field, like so:
from django import forms from django.core.exceptions import ValidationError class ContactForm(forms.Form): # Everything as before. ... def clean_recipients(self): data = self.cleaned_data['recipients'] if "fred@example.com" not in data: raise ValidationError("You have forgotten about Fred!") # Always return a value to use as the new cleaned data, even if # this method didn't change it. return data
Cleaning and validating fields that depend on each other¶
Suppose we add another requirement to our contact form: if the cc_myself
field is True
, the subject
must contain the word "help"
. We are
performing validation on more than one field at a time, so the form’s
clean()
method is a good spot to do this. Notice that we are
talking about the clean()
method on the form here, whereas earlier we were
writing a clean()
method on a field. It’s important to keep the field and
form difference clear when working out where to validate things. Fields are
single data points, forms are a collection of fields.
By the time the form’s clean()
method is called, all the individual field
clean methods will have been run (the previous two sections), so
self.cleaned_data
will be populated with any data that has survived so
far. So you also need to remember to allow for the fact that the fields you
are wanting to validate might not have survived the initial individual field
checks.
There are two ways to report any errors from this step. Probably the most
common method is to display the error at the top of the form. To create such
an error, you can raise a ValidationError
from the clean()
method. For
example:
from django import forms from django.core.exceptions import ValidationError class ContactForm(forms.Form): # Everything as before. ... def clean(self): cleaned_data = super().clean() cc_myself = cleaned_data.get("cc_myself") subject = cleaned_data.get("subject") if cc_myself and subject: # Only do something if both fields are valid so far. if "help" not in subject: raise ValidationError( "Did not send for 'help' in the subject despite " "CC'ing yourself." )
In this code, if the validation error is raised, the form will display an
error message at the top of the form (normally) describing the problem. Such
errors are non-field errors, which are displayed in the template with
{{ form.non_field_errors }}
.
The call to super().clean()
in the example code ensures that any validation
logic in parent classes is maintained. If your form inherits another that
doesn’t return a cleaned_data
dictionary in its clean()
method (doing
so is optional), then don’t assign cleaned_data
to the result of the
super()
call and use self.cleaned_data
instead:
def clean(self): super().clean() cc_myself = self.cleaned_data.get("cc_myself") ...
The second approach for reporting validation errors might involve assigning the
error message to one of the fields. In this case, let’s assign an error message
to both the “subject” and “cc_myself” rows in the form display. Be careful when
doing this in practice, since it can lead to confusing form output. We’re
showing what is possible here and leaving it up to you and your designers to
work out what works effectively in your particular situation. Our new code
(replacing the previous sample) looks like this:
from django import forms class ContactForm(forms.Form): # Everything as before. ... def clean(self): cleaned_data = super().clean() cc_myself = cleaned_data.get("cc_myself") subject = cleaned_data.get("subject") if cc_myself and subject and "help" not in subject: msg = "Must put 'help' in subject when cc'ing yourself." self.add_error('cc_myself', msg) self.add_error('subject', msg)
The second argument of add_error()
can be a string, or preferably an
instance of ValidationError
. See Raising ValidationError for more
details. Note that add_error()
automatically removes the field from
cleaned_data
.
The Forms API¶
Bound and unbound forms¶
A Form
instance is either bound to a set of data, or unbound.
- If it’s bound to a set of data, it’s capable of validating that data
and rendering the form as HTML with the data displayed in the HTML. - If it’s unbound, it cannot do validation (because there’s no data to
validate!), but it can still render the blank form as HTML.
-
class
Form
¶
To create an unbound Form
instance, instantiate the class:
To bind data to a form, pass the data as a dictionary as the first parameter to
your Form
class constructor:
>>> data = {'subject': 'hello', ... 'message': 'Hi there', ... 'sender': 'foo@example.com', ... 'cc_myself': True} >>> f = ContactForm(data)
In this dictionary, the keys are the field names, which correspond to the
attributes in your Form
class. The values are the data you’re trying to
validate. These will usually be strings, but there’s no requirement that they be
strings; the type of data you pass depends on the Field
, as we’ll see
in a moment.
-
Form.
is_bound
¶
If you need to distinguish between bound and unbound form instances at runtime,
check the value of the form’s is_bound
attribute:
>>> f = ContactForm() >>> f.is_bound False >>> f = ContactForm({'subject': 'hello'}) >>> f.is_bound True
Note that passing an empty dictionary creates a bound form with empty data:
>>> f = ContactForm({}) >>> f.is_bound True
If you have a bound Form
instance and want to change the data somehow,
or if you want to bind an unbound Form
instance to some data, create
another Form
instance. There is no way to change data in a
Form
instance. Once a Form
instance has been created, you
should consider its data immutable, whether it has data or not.
Using forms to validate data¶
-
Form.
clean
()¶
Implement a clean()
method on your Form
when you must add custom
validation for fields that are interdependent. See
Cleaning and validating fields that depend on each other for example usage.
-
Form.
is_valid
()¶
The primary task of a Form
object is to validate data. With a bound
Form
instance, call the is_valid()
method to run validation
and return a boolean designating whether the data was valid:
>>> data = {'subject': 'hello', ... 'message': 'Hi there', ... 'sender': 'foo@example.com', ... 'cc_myself': True} >>> f = ContactForm(data) >>> f.is_valid() True
Let’s try with some invalid data. In this case, subject
is blank (an error,
because all fields are required by default) and sender
is not a valid
email address:
>>> data = {'subject': '', ... 'message': 'Hi there', ... 'sender': 'invalid email address', ... 'cc_myself': True} >>> f = ContactForm(data) >>> f.is_valid() False
-
Form.
errors
¶
Access the errors
attribute to get a dictionary of error
messages:
>>> f.errors {'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}
In this dictionary, the keys are the field names, and the values are lists of
strings representing the error messages. The error messages are stored
in lists because a field can have multiple error messages.
You can access errors
without having to call
is_valid()
first. The form’s data will be validated the first time
either you call is_valid()
or access errors
.
The validation routines will only get called once, regardless of how many times
you access errors
or call is_valid()
. This means that
if validation has side effects, those side effects will only be triggered once.
-
Form.errors.
as_data
()¶
Returns a dict
that maps fields to their original ValidationError
instances.
>>> f.errors.as_data() {'sender': [ValidationError(['Enter a valid email address.'])], 'subject': [ValidationError(['This field is required.'])]}
Use this method anytime you need to identify an error by its code
. This
enables things like rewriting the error’s message or writing custom logic in a
view when a given error is present. It can also be used to serialize the errors
in a custom format (e.g. XML); for instance, as_json()
relies on as_data()
.
The need for the as_data()
method is due to backwards compatibility.
Previously ValidationError
instances were lost as soon as their
rendered error messages were added to the Form.errors
dictionary.
Ideally Form.errors
would have stored ValidationError
instances
and methods with an as_
prefix could render them, but it had to be done
the other way around in order not to break code that expects rendered error
messages in Form.errors
.
-
Form.errors.
as_json
(escape_html=False)¶
Returns the errors serialized as JSON.
>>> f.errors.as_json() {"sender": [{"message": "Enter a valid email address.", "code": "invalid"}], "subject": [{"message": "This field is required.", "code": "required"}]}
By default, as_json()
does not escape its output. If you are using it for
something like AJAX requests to a form view where the client interprets the
response and inserts errors into the page, you’ll want to be sure to escape the
results on the client-side to avoid the possibility of a cross-site scripting
attack. You can do this in JavaScript with element.textContent = errorText
or with jQuery’s $(el).text(errorText)
(rather than its .html()
function).
If for some reason you don’t want to use client-side escaping, you can also
set escape_html=True
and error messages will be escaped so you can use them
directly in HTML.
-
Form.errors.
get_json_data
(escape_html=False)¶
Returns the errors as a dictionary suitable for serializing to JSON.
Form.errors.as_json()
returns serialized JSON, while this returns the
error data before it’s serialized.
The escape_html
parameter behaves as described in
Form.errors.as_json()
.
-
Form.
add_error
(field, error)¶
This method allows adding errors to specific fields from within the
Form.clean()
method, or from outside the form altogether; for instance
from a view.
The field
argument is the name of the field to which the errors
should be added. If its value is None
the error will be treated as
a non-field error as returned by Form.non_field_errors()
.
The error
argument can be a string, or preferably an instance of
ValidationError
. See Raising ValidationError for best practices
when defining form errors.
Note that Form.add_error()
automatically removes the relevant field from
cleaned_data
.
-
Form.
has_error
(field, code=None)¶
This method returns a boolean designating whether a field has an error with
a specific error code
. If code
is None
, it will return True
if the field contains any errors at all.
To check for non-field errors use
NON_FIELD_ERRORS
as the field
parameter.
-
Form.
non_field_errors
()¶
This method returns the list of errors from Form.errors
that aren’t associated with a particular field.
This includes ValidationError
s that are raised in Form.clean()
and errors added using Form.add_error(None,
.
"...")
Behavior of unbound forms¶
It’s meaningless to validate a form with no data, but, for the record, here’s
what happens with unbound forms:
>>> f = ContactForm() >>> f.is_valid() False >>> f.errors {}
Initial form values¶
-
Form.
initial
¶
Use initial
to declare the initial value of form fields at
runtime. For example, you might want to fill in a username
field with the
username of the current session.
To accomplish this, use the initial
argument to a Form
.
This argument, if given, should be a dictionary mapping field names to initial
values. Only include the fields for which you’re specifying an initial value;
it’s not necessary to include every field in your form. For example:
>>> f = ContactForm(initial={'subject': 'Hi there!'})
These values are only displayed for unbound forms, and they’re not used as
fallback values if a particular value isn’t provided.
If a Field
defines initial
and you
include initial
when instantiating the Form
, then the latter
initial
will have precedence. In this example, initial
is provided both
at the field level and at the form instance level, and the latter gets
precedence:
>>> from django import forms >>> class CommentForm(forms.Form): ... name = forms.CharField(initial='class') ... url = forms.URLField() ... comment = forms.CharField() >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False) >>> print(f) <tr><th>Name:</th><td><input type="text" name="name" value="instance" required></td></tr> <tr><th>Url:</th><td><input type="url" name="url" required></td></tr> <tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>
-
Form.
get_initial_for_field
(field, field_name)¶
Returns the initial data for a form field. It retrieves the data from
Form.initial
if present, otherwise trying Field.initial
.
Callable values are evaluated.
It is recommended to use BoundField.initial
over
get_initial_for_field()
because BoundField.initial
has a
simpler interface. Also, unlike get_initial_for_field()
,
BoundField.initial
caches its values. This is useful especially when
dealing with callables whose return values can change (e.g. datetime.now
or
uuid.uuid4
):
>>> import uuid >>> class UUIDCommentForm(CommentForm): ... identifier = forms.UUIDField(initial=uuid.uuid4) >>> f = UUIDCommentForm() >>> f.get_initial_for_field(f.fields['identifier'], 'identifier') UUID('972ca9e4-7bfe-4f5b-af7d-07b3aa306334') >>> f.get_initial_for_field(f.fields['identifier'], 'identifier') UUID('1b411fab-844e-4dec-bd4f-e9b0495f04d0') >>> # Using BoundField.initial, for comparison >>> f['identifier'].initial UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30') >>> f['identifier'].initial UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')
Checking which form data has changed¶
-
Form.
has_changed
()¶
Use the has_changed()
method on your Form
when you need to check if the
form data has been changed from the initial data.
>>> data = {'subject': 'hello', ... 'message': 'Hi there', ... 'sender': 'foo@example.com', ... 'cc_myself': True} >>> f = ContactForm(data, initial=data) >>> f.has_changed() False
When the form is submitted, we reconstruct it and provide the original data
so that the comparison can be done:
>>> f = ContactForm(request.POST, initial=data) >>> f.has_changed()
has_changed()
will be True
if the data from request.POST
differs
from what was provided in initial
or False
otherwise. The
result is computed by calling Field.has_changed()
for each field in the
form.
-
Form.
changed_data
¶
The changed_data
attribute returns a list of the names of the fields whose
values in the form’s bound data (usually request.POST
) differ from what was
provided in initial
. It returns an empty list if no data differs.
>>> f = ContactForm(request.POST, initial=data) >>> if f.has_changed(): ... print("The following fields changed: %s" % ", ".join(f.changed_data)) >>> f.changed_data ['subject', 'message']
Accessing the fields from the form¶
-
Form.
fields
¶
You can access the fields of Form
instance from its fields
attribute:
>>> for row in f.fields.values(): print(row) ... <django.forms.fields.CharField object at 0x7ffaac632510> <django.forms.fields.URLField object at 0x7ffaac632f90> <django.forms.fields.CharField object at 0x7ffaac3aa050> >>> f.fields['name'] <django.forms.fields.CharField object at 0x7ffaac6324d0>
You can alter the field and BoundField
of Form
instance to
change the way it is presented in the form:
>>> f.as_div().split("</div>")[0] '<div><label for="id_subject">Subject:</label><input type="text" name="subject" maxlength="100" required id="id_subject">' >>> f["subject"].label = "Topic" >>> f.as_div().split("</div>")[0] '<div><label for="id_subject">Topic:</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
Beware not to alter the base_fields
attribute because this modification
will influence all subsequent ContactForm
instances within the same Python
process:
>>> f.base_fields["subject"].label_suffix = "?" >>> another_f = CommentForm(auto_id=False) >>> f.as_div().split("</div>")[0] '<div><label for="id_subject">Subject?</label><input type="text" name="subject" maxlength="100" required id="id_subject">'
Accessing “clean” data¶
-
Form.
cleaned_data
¶
Each field in a Form
class is responsible not only for validating
data, but also for “cleaning” it – normalizing it to a consistent format. This
is a nice feature, because it allows data for a particular field to be input in
a variety of ways, always resulting in consistent output.
For example, DateField
normalizes input into a
Python datetime.date
object. Regardless of whether you pass it a string in
the format '1994-07-15'
, a datetime.date
object, or a number of other
formats, DateField
will always normalize it to a datetime.date
object
as long as it’s valid.
Once you’ve created a Form
instance with a set of data and validated
it, you can access the clean data via its cleaned_data
attribute:
>>> data = {'subject': 'hello', ... 'message': 'Hi there', ... 'sender': 'foo@example.com', ... 'cc_myself': True} >>> f = ContactForm(data) >>> f.is_valid() True >>> f.cleaned_data {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
Note that any text-based field – such as CharField
or EmailField
–
always cleans the input into a string. We’ll cover the encoding implications
later in this document.
If your data does not validate, the cleaned_data
dictionary contains
only the valid fields:
>>> data = {'subject': '', ... 'message': 'Hi there', ... 'sender': 'invalid email address', ... 'cc_myself': True} >>> f = ContactForm(data) >>> f.is_valid() False >>> f.cleaned_data {'cc_myself': True, 'message': 'Hi there'}
cleaned_data
will always only contain a key for fields defined in the
Form
, even if you pass extra data when you define the Form
. In this
example, we pass a bunch of extra fields to the ContactForm
constructor,
but cleaned_data
contains only the form’s fields:
>>> data = {'subject': 'hello', ... 'message': 'Hi there', ... 'sender': 'foo@example.com', ... 'cc_myself': True, ... 'extra_field_1': 'foo', ... 'extra_field_2': 'bar', ... 'extra_field_3': 'baz'} >>> f = ContactForm(data) >>> f.is_valid() True >>> f.cleaned_data # Doesn't contain extra_field_1, etc. {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}
When the Form
is valid, cleaned_data
will include a key and value for
all its fields, even if the data didn’t include a value for some optional
fields. In this example, the data dictionary doesn’t include a value for the
nick_name
field, but cleaned_data
includes it, with an empty value:
>>> from django import forms >>> class OptionalPersonForm(forms.Form): ... first_name = forms.CharField() ... last_name = forms.CharField() ... nick_name = forms.CharField(required=False) >>> data = {'first_name': 'John', 'last_name': 'Lennon'} >>> f = OptionalPersonForm(data) >>> f.is_valid() True >>> f.cleaned_data {'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'}
In this above example, the cleaned_data
value for nick_name
is set to an
empty string, because nick_name
is CharField
, and CharField
s treat
empty values as an empty string. Each field type knows what its “blank” value
is – e.g., for DateField
, it’s None
instead of the empty string. For
full details on each field’s behavior in this case, see the “Empty value” note
for each field in the “Built-in Field
classes” section below.
You can write code to perform validation for particular form fields (based on
their name) or for the form as a whole (considering combinations of various
fields). More information about this is in Form and field validation.
Outputting forms as HTML¶
The second task of a Form
object is to render itself as HTML. To do so,
print
it:
>>> f = ContactForm() >>> print(f) <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr> <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr> <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr> <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>
If the form is bound to data, the HTML output will include that data
appropriately. For example, if a field is represented by an
<input type="text">
, the data will be in the value
attribute. If a
field is represented by an <input type="checkbox">
, then that HTML will
include checked
if appropriate:
>>> data = {'subject': 'hello', ... 'message': 'Hi there', ... 'sender': 'foo@example.com', ... 'cc_myself': True} >>> f = ContactForm(data) >>> print(f) <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" required></td></tr> <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" required></td></tr> <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" value="foo@example.com" required></td></tr> <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" checked></td></tr>
This default output is a two-column HTML table, with a <tr>
for each field.
Notice the following:
- For flexibility, the output does not include the
<table>
and
</table>
tags, nor does it include the<form>
and</form>
tags or an<input type="submit">
tag. It’s your job to do that. - Each field type has a default HTML representation.
CharField
is
represented by an<input type="text">
andEmailField
by an
<input type="email">
.BooleanField(null=False)
is represented by an
<input type="checkbox">
. Note these are merely sensible defaults; you can
specify which HTML to use for a given field by using widgets, which we’ll
explain shortly. - The HTML
name
for each tag is taken directly from its attribute name
in theContactForm
class. - The text label for each field – e.g.
'Subject:'
,'Message:'
and
'Cc myself:'
is generated from the field name by converting all
underscores to spaces and upper-casing the first letter. Again, note
these are merely sensible defaults; you can also specify labels manually. - Each text label is surrounded in an HTML
<label>
tag, which points
to the appropriate form field via itsid
. Itsid
, in turn, is
generated by prepending'id_'
to the field name. Theid
attributes and<label>
tags are included in the output by default, to
follow best practices, but you can change that behavior. - The output uses HTML5 syntax, targeting
<!DOCTYPE html>
. For example,
it uses boolean attributes such aschecked
rather than the XHTML style
ofchecked='checked'
.
Although <table>
output is the default output style when you print
a
form, other output styles are available. Each style is available as a method on
a form object, and each rendering method returns a string.
Default rendering¶
The default rendering when you print
a form uses the following methods and
attributes.
template_name
¶
New in Django 4.0.
-
Form.
template_name
¶
The name of the template rendered if the form is cast into a string, e.g. via
print(form)
or in a template via {{ form }}
.
By default, a property returning the value of the renderer’s
form_template_name
. You may set it
as a string template name in order to override that for a particular form
class.
Changed in Django 4.1:
In older versions template_name
defaulted to the string value
'django/forms/default.html'
.
render()
¶
New in Django 4.0.
-
Form.
render
(template_name=None, context=None, renderer=None)¶
The render method is called by __str__
as well as the
Form.as_table()
, Form.as_p()
, and Form.as_ul()
methods.
All arguments are optional and default to:
template_name
:Form.template_name
context
: Value returned byForm.get_context()
renderer
: Value returned byForm.default_renderer
By passing template_name
you can customize the template used for just a
single call.
get_context()
¶
New in Django 4.0.
-
Form.
get_context
()¶
Return the template context for rendering the form.
The available context is:
form
: The bound form.fields
: All bound fields, except the hidden fields.hidden_fields
: All hidden bound fields.errors
: All non field related or hidden field related form errors.
template_name_label
¶
New in Django 4.0.
-
Form.
template_name_label
¶
The template used to render a field’s <label>
, used when calling
BoundField.label_tag()
/legend_tag()
. Can be changed per
form by overriding this attribute or more generally by overriding the default
template, see also Overriding built-in form templates.
Output styles¶
As well as rendering the form directly, such as in a template with
{{ form }}
, the following helper functions serve as a proxy to
Form.render()
passing a particular template_name
value.
These helpers are most useful in a template, where you need to override the
form renderer or form provided value but cannot pass the additional parameter
to render()
. For example, you can render a form as an unordered
list using {{ form.as_ul }}
.
Each helper pairs a form method with an attribute giving the appropriate
template name.
as_div()
¶
-
Form.
template_name_div
¶
New in Django 4.1.
The template used by as_div()
. Default: 'django/forms/div.html'
.
-
Form.
as_div
()¶
New in Django 4.1.
as_div()
renders the form as a series of <div>
elements, with each
<div>
containing one field, such as:
>>> f = ContactForm() >>> f.as_div()
… gives HTML like:
<div> <label for="id_subject">Subject:</label> <input type="text" name="subject" maxlength="100" required id="id_subject"> </div> <div> <label for="id_message">Message:</label> <input type="text" name="message" required id="id_message"> </div> <div> <label for="id_sender">Sender:</label> <input type="email" name="sender" required id="id_sender"> </div> <div> <label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"> </div>
Note
Of the framework provided templates and output styles, as_div()
is
recommended over the as_p()
, as_table()
, and as_ul()
versions
as the template implements <fieldset>
and <legend>
to group related
inputs and is easier for screen reader users to navigate.
as_p()
¶
-
Form.
template_name_p
¶
The template used by as_p()
. Default: 'django/forms/p.html'
.
-
Form.
as_p
()¶
as_p()
renders the form as a series of <p>
tags, with each <p>
containing one field:
>>> f = ContactForm() >>> f.as_p() '<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p>n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p>n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" required></p>n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>' >>> print(f.as_p()) <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p> <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p> <p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></p> <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>
as_ul()
¶
-
Form.
template_name_ul
¶
The template used by as_ul()
. Default: 'django/forms/ul.html'
.
-
Form.
as_ul
()¶
as_ul()
renders the form as a series of <li>
tags, with each <li>
containing one field. It does not include the <ul>
or </ul>
, so that
you can specify any HTML attributes on the <ul>
for flexibility:
>>> f = ContactForm() >>> f.as_ul() '<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li>n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li>n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li>n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>' >>> print(f.as_ul()) <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li> <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li> <li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li> <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>
as_table()
¶
-
Form.
template_name_table
¶
The template used by as_table()
. Default: 'django/forms/table.html'
.
-
Form.
as_table
()¶
as_table()
renders the form as an HTML <table>
:
>>> f = ContactForm() >>> f.as_table() '<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>' >>> print(f) <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr> <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr> <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr> <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>
Styling required or erroneous form rows¶
-
Form.
error_css_class
¶
-
Form.
required_css_class
¶
It’s pretty common to style form rows and fields that are required or have
errors. For example, you might want to present required form rows in bold and
highlight errors in red.
The Form
class has a couple of hooks you can use to add class
attributes to required rows or to rows with errors: set the
Form.error_css_class
and/or Form.required_css_class
attributes:
from django import forms class ContactForm(forms.Form): error_css_class = 'error' required_css_class = 'required' # ... and the rest of your fields here
Once you’ve done that, rows will be given "error"
and/or "required"
classes, as needed. The HTML will look something like:
>>> f = ContactForm(data) >>> print(f.as_table()) <tr class="required"><th><label class="required" for="id_subject">Subject:</label> ... <tr class="required"><th><label class="required" for="id_message">Message:</label> ... <tr class="required error"><th><label class="required" for="id_sender">Sender:</label> ... <tr><th><label for="id_cc_myself">Cc myself:<label> ... >>> f['subject'].label_tag() <label class="required" for="id_subject">Subject:</label> >>> f['subject'].legend_tag() <legend class="required" for="id_subject">Subject:</legend> >>> f['subject'].label_tag(attrs={'class': 'foo'}) <label for="id_subject" class="foo required">Subject:</label> >>> f['subject'].legend_tag(attrs={'class': 'foo'}) <legend for="id_subject" class="foo required">Subject:</legend>
Notes on field ordering¶
In the as_p()
, as_ul()
and as_table()
shortcuts, the fields are
displayed in the order in which you define them in your form class. For
example, in the ContactForm
example, the fields are defined in the order
subject
, message
, sender
, cc_myself
. To reorder the HTML
output, change the order in which those fields are listed in the class.
There are several other ways to customize the order:
-
Form.
field_order
¶
By default Form.field_order=None
, which retains the order in which you
define the fields in your form class. If field_order
is a list of field
names, the fields are ordered as specified by the list and remaining fields are
appended according to the default order. Unknown field names in the list are
ignored. This makes it possible to disable a field in a subclass by setting it
to None
without having to redefine ordering.
You can also use the Form.field_order
argument to a Form
to
override the field order. If a Form
defines
field_order
and you include field_order
when instantiating
the Form
, then the latter field_order
will have precedence.
-
Form.
order_fields
(field_order)¶
You may rearrange the fields any time using order_fields()
with a list of
field names as in field_order
.
How errors are displayed¶
If you render a bound Form
object, the act of rendering will automatically
run the form’s validation if it hasn’t already happened, and the HTML output
will include the validation errors as a <ul class="errorlist">
near the
field. The particular positioning of the error messages depends on the output
method you’re using:
>>> data = {'subject': '', ... 'message': 'Hi there', ... 'sender': 'invalid email address', ... 'cc_myself': True} >>> f = ContactForm(data, auto_id=False) >>> print(f.as_div()) <div>Subject:<ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" required></div> <div>Message:<textarea name="message" cols="40" rows="10" required>Hi there</textarea></div> <div>Sender:<ul class="errorlist"><li>Enter a valid email address.</li></ul><input type="email" name="sender" value="invalid email address" required></div> <div>Cc myself:<input type="checkbox" name="cc_myself" checked></div> >>> print(f.as_table()) <tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" required></td></tr> <tr><th>Message:</th><td><textarea name="message" cols="40" rows="10" required></textarea></td></tr> <tr><th>Sender:</th><td><ul class="errorlist"><li>Enter a valid email address.</li></ul><input type="email" name="sender" value="invalid email address" required></td></tr> <tr><th>Cc myself:</th><td><input checked type="checkbox" name="cc_myself"></td></tr> >>> print(f.as_ul()) <li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" required></li> <li>Message: <textarea name="message" cols="40" rows="10" required></textarea></li> <li><ul class="errorlist"><li>Enter a valid email address.</li></ul>Sender: <input type="email" name="sender" value="invalid email address" required></li> <li>Cc myself: <input checked type="checkbox" name="cc_myself"></li> >>> print(f.as_p()) <p><ul class="errorlist"><li>This field is required.</li></ul></p> <p>Subject: <input type="text" name="subject" maxlength="100" required></p> <p>Message: <textarea name="message" cols="40" rows="10" required></textarea></p> <p><ul class="errorlist"><li>Enter a valid email address.</li></ul></p> <p>Sender: <input type="email" name="sender" value="invalid email address" required></p> <p>Cc myself: <input checked type="checkbox" name="cc_myself"></p>
Customizing the error list format¶
-
class
ErrorList
(initlist=None, error_class=None, renderer=None)¶ -
By default, forms use
django.forms.utils.ErrorList
to format validation
errors.ErrorList
is a list like object whereinitlist
is the
list of errors. In addition this class has the following attributes and
methods.-
error_class
¶ -
The CSS classes to be used when rendering the error list. Any provided
classes are added to the defaulterrorlist
class.
-
renderer
¶ -
New in Django 4.0.
Specifies the renderer to use for
ErrorList
.
Defaults toNone
which means to use the default renderer
specified by theFORM_RENDERER
setting.
-
template_name
¶ -
New in Django 4.0.
The name of the template used when calling
__str__
or
render()
. By default this is
'django/forms/errors/list/default.html'
which is a proxy for the
'ul.html'
template.
-
template_name_text
¶ -
New in Django 4.0.
The name of the template used when calling
as_text()
. By default
this is'django/forms/errors/list/text.html'
. This template renders
the errors as a list of bullet points.
-
template_name_ul
¶ -
New in Django 4.0.
The name of the template used when calling
as_ul()
. By default
this is'django/forms/errors/list/ul.html'
. This template renders
the errors in<li>
tags with a wrapping<ul>
with the CSS
classes as defined byerror_class
.
-
get_context
()¶ -
New in Django 4.0.
Return context for rendering of errors in a template.
The available context is:
errors
: A list of the errors.error_class
: A string of CSS classes.
-
render
(template_name=None, context=None, renderer=None)¶ -
New in Django 4.0.
The render method is called by
__str__
as well as by the
as_ul()
method.All arguments are optional and will default to:
template_name
: Value returned bytemplate_name
context
: Value returned byget_context()
renderer
: Value returned byrenderer
-
as_text
()¶ -
Renders the error list using the template defined by
template_name_text
.
-
as_ul
()¶ -
Renders the error list using the template defined by
template_name_ul
.
If you’d like to customize the rendering of errors this can be achieved by
overriding thetemplate_name
attribute or more generally by
overriding the default template, see also
Overriding built-in form templates. -
Changed in Django 4.0:
Rendering of ErrorList
was moved to the template engine.
Deprecated since version 4.0: The ability to return a str
when calling the __str__
method is
deprecated. Use the template engine instead which returns a SafeString
.
More granular output¶
The as_p()
, as_ul()
, and as_table()
methods are shortcuts –
they’re not the only way a form object can be displayed.
-
class
BoundField
¶ -
Used to display HTML or access attributes for a single field of a
Form
instance.The
__str__()
method of this object displays the HTML for this field.
To retrieve a single BoundField
, use dictionary lookup syntax on your form
using the field’s name as the key:
>>> form = ContactForm() >>> print(form['subject']) <input id="id_subject" type="text" name="subject" maxlength="100" required>
To retrieve all BoundField
objects, iterate the form:
>>> form = ContactForm() >>> for boundfield in form: print(boundfield) <input id="id_subject" type="text" name="subject" maxlength="100" required> <input type="text" name="message" id="id_message" required> <input type="email" name="sender" id="id_sender" required> <input type="checkbox" name="cc_myself" id="id_cc_myself">
The field-specific output honors the form object’s auto_id
setting:
>>> f = ContactForm(auto_id=False) >>> print(f['message']) <input type="text" name="message" required> >>> f = ContactForm(auto_id='id_%s') >>> print(f['message']) <input type="text" name="message" id="id_message" required>
Attributes of BoundField
¶
-
BoundField.
auto_id
¶ -
The HTML ID attribute for this
BoundField
. Returns an empty string
ifForm.auto_id
isFalse
.
-
BoundField.
data
¶ -
This property returns the data for this
BoundField
extracted by the widget’svalue_from_datadict()
method, orNone
if it wasn’t given:>>> unbound_form = ContactForm() >>> print(unbound_form['subject'].data) None >>> bound_form = ContactForm(data={'subject': 'My Subject'}) >>> print(bound_form['subject'].data) My Subject
-
BoundField.
errors
¶ -
A list-like object that is displayed
as an HTML<ul class="errorlist">
when printed:>>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''} >>> f = ContactForm(data, auto_id=False) >>> print(f['message']) <input type="text" name="message" required> >>> f['message'].errors ['This field is required.'] >>> print(f['message'].errors) <ul class="errorlist"><li>This field is required.</li></ul> >>> f['subject'].errors [] >>> print(f['subject'].errors) >>> str(f['subject'].errors) ''
-
BoundField.
field
¶ -
The form
Field
instance from the form class that
thisBoundField
wraps.
-
BoundField.
form
¶ -
The
Form
instance thisBoundField
is bound to.
-
BoundField.
help_text
¶ -
The
help_text
of the field.
-
BoundField.
html_name
¶ -
The name that will be used in the widget’s HTML
name
attribute. It takes
the formprefix
into account.
-
BoundField.
id_for_label
¶ -
Use this property to render the ID of this field. For example, if you are
manually constructing a<label>
in your template (despite the fact that
label_tag()
/legend_tag()
will do this
for you):<label for="{{ form.my_field.id_for_label }}">...</label>{{ my_field }}
By default, this will be the field’s name prefixed by
id_
(”id_my_field
” for the example above). You may modify the ID by setting
attrs
on the field’s widget. For example,
declaring a field like this:my_field = forms.CharField(widget=forms.TextInput(attrs={'id': 'myFIELD'}))
and using the template above, would render something like:
<label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" required>
-
BoundField.
initial
¶ -
Use
BoundField.initial
to retrieve initial data for a form field.
It retrieves the data fromForm.initial
if present, otherwise
tryingField.initial
. Callable values are evaluated. See
Initial form values for more examples.BoundField.initial
caches its return value, which is useful
especially when dealing with callables whose return values can change (e.g.
datetime.now
oruuid.uuid4
):>>> from datetime import datetime >>> class DatedCommentForm(CommentForm): ... created = forms.DateTimeField(initial=datetime.now) >>> f = DatedCommentForm() >>> f['created'].initial datetime.datetime(2021, 7, 27, 9, 5, 54) >>> f['created'].initial datetime.datetime(2021, 7, 27, 9, 5, 54)
Using
BoundField.initial
is recommended over
get_initial_for_field()
.
-
BoundField.
is_hidden
¶ -
Returns
True
if thisBoundField
’s widget is
hidden.
-
BoundField.
label
¶ -
The
label
of the field. This is used in
label_tag()
/legend_tag()
.
-
BoundField.
name
¶ -
The name of this field in the form:
>>> f = ContactForm() >>> print(f['subject'].name) subject >>> print(f['message'].name) message
-
BoundField.
use_fieldset
¶ -
New in Django 4.1.
Returns the value of this BoundField widget’s
use_fieldset
attribute.
-
BoundField.
widget_type
¶ -
Returns the lowercased class name of the wrapped field’s widget, with any
trailinginput
orwidget
removed. This may be used when building
forms where the layout is dependent upon the widget type. For example:{% for field in form %} {% if field.widget_type == 'checkbox' %} # render one way {% else %} # render another way {% endif %} {% endfor %}
Methods of BoundField
¶
-
BoundField.
as_hidden
(attrs=None, **kwargs)¶ -
Returns a string of HTML for representing this as an
<input type="hidden">
.**kwargs
are passed toas_widget()
.This method is primarily used internally. You should use a widget instead.
-
BoundField.
as_widget
(widget=None, attrs=None, only_initial=False)¶ -
Renders the field by rendering the passed widget, adding any HTML
attributes passed asattrs
. If no widget is specified, then the
field’s default widget will be used.only_initial
is used by Django internals and should not be set
explicitly.
-
BoundField.
css_classes
(extra_classes=None)¶ -
When you use Django’s rendering shortcuts, CSS classes are used to
indicate required form fields or fields that contain errors. If you’re
manually rendering a form, you can access these CSS classes using the
css_classes
method:>>> f = ContactForm(data={'message': ''}) >>> f['message'].css_classes() 'required'
If you want to provide some additional classes in addition to the
error and required classes that may be required, you can provide
those classes as an argument:>>> f = ContactForm(data={'message': ''}) >>> f['message'].css_classes('foo bar') 'foo bar required'
-
BoundField.
label_tag
(contents=None, attrs=None, label_suffix=None, tag=None)¶ -
Renders a label tag for the form field using the template specified by
Form.template_name_label
.The available context is:
field
: This instance of theBoundField
.contents
: By default a concatenated string of
BoundField.label
andForm.label_suffix
(or
Field.label_suffix
, if set). This can be overridden by the
contents
andlabel_suffix
arguments.attrs
: Adict
containingfor
,
Form.required_css_class
, andid
.id
is generated by the
field’s widgetattrs
orBoundField.auto_id
. Additional
attributes can be provided by theattrs
argument.use_tag
: A boolean which isTrue
if the label has anid
.
IfFalse
the default template omits thetag
.tag
: An optional string to customize the tag, defaults tolabel
.
Tip
In your template
field
is the instance of theBoundField
.
Thereforefield.field
accessesBoundField.field
being
the field you declare, e.g.forms.CharField
.To separately render the label tag of a form field, you can call its
label_tag()
method:>>> f = ContactForm(data={'message': ''}) >>> print(f['message'].label_tag()) <label for="id_message">Message:</label>
If you’d like to customize the rendering this can be achieved by overriding
theForm.template_name_label
attribute or more generally by
overriding the default template, see also
Overriding built-in form templates.Changed in Django 4.0:
The label is now rendered using the template engine.
Changed in Django 4.1:
The
tag
argument was added.
-
BoundField.
legend_tag
(contents=None, attrs=None, label_suffix=None)¶ -
New in Django 4.1.
Calls
label_tag()
withtag='legend'
to render the label with
<legend>
tags. This is useful when rendering radio and multiple
checkbox widgets where<legend>
may be more appropriate than a
<label>
.
-
BoundField.
value
()¶ -
Use this method to render the raw value of this field as it would be rendered
by aWidget
:>>> initial = {'subject': 'welcome'} >>> unbound_form = ContactForm(initial=initial) >>> bound_form = ContactForm(data={'subject': 'hi'}, initial=initial) >>> print(unbound_form['subject'].value()) welcome >>> print(bound_form['subject'].value()) hi
Customizing BoundField
¶
If you need to access some additional information about a form field in a
template and using a subclass of Field
isn’t
sufficient, consider also customizing BoundField
.
A custom form field can override get_bound_field()
:
-
Field.
get_bound_field
(form, field_name)¶ -
Takes an instance of
Form
and the name of the field.
The return value will be used when accessing the field in a template. Most
likely it will be an instance of a subclass of
BoundField
.
If you have a GPSCoordinatesField
, for example, and want to be able to
access additional information about the coordinates in a template, this could
be implemented as follows:
class GPSCoordinatesBoundField(BoundField): @property def country(self): """ Return the country the coordinates lie in or None if it can't be determined. """ value = self.value() if value: return get_country_from_coordinates(value) else: return None class GPSCoordinatesField(Field): def get_bound_field(self, form, field_name): return GPSCoordinatesBoundField(form, self, field_name)
Now you can access the country in a template with
{{ form.coordinates.country }}
.
Binding uploaded files to a form¶
Dealing with forms that have FileField
and ImageField
fields
is a little more complicated than a normal form.
Firstly, in order to upload files, you’ll need to make sure that your
<form>
element correctly defines the enctype
as
"multipart/form-data"
:
<form enctype="multipart/form-data" method="post" action="/foo/">
Secondly, when you use the form, you need to bind the file data. File
data is handled separately to normal form data, so when your form
contains a FileField
and ImageField
, you will need to specify
a second argument when you bind your form. So if we extend our
ContactForm to include an ImageField
called mugshot
, we
need to bind the file data containing the mugshot image:
# Bound form with an image field >>> from django.core.files.uploadedfile import SimpleUploadedFile >>> data = {'subject': 'hello', ... 'message': 'Hi there', ... 'sender': 'foo@example.com', ... 'cc_myself': True} >>> file_data = {'mugshot': SimpleUploadedFile('face.jpg', <file data>)} >>> f = ContactFormWithMugshot(data, file_data)
In practice, you will usually specify request.FILES
as the source
of file data (just like you use request.POST
as the source of
form data):
# Bound form with an image field, data from the request >>> f = ContactFormWithMugshot(request.POST, request.FILES)
Constructing an unbound form is the same as always – omit both form data and
file data:
# Unbound form with an image field >>> f = ContactFormWithMugshot()
Testing for multipart forms¶
-
Form.
is_multipart
()¶
If you’re writing reusable views or templates, you may not know ahead of time
whether your form is a multipart form or not. The is_multipart()
method
tells you whether the form requires multipart encoding for submission:
>>> f = ContactFormWithMugshot() >>> f.is_multipart() True
Here’s an example of how you might use this in a template:
{% if form.is_multipart %} <form enctype="multipart/form-data" method="post" action="/foo/"> {% else %} <form method="post" action="/foo/"> {% endif %} {{ form }} </form>
Subclassing forms¶
If you have multiple Form
classes that share fields, you can use
subclassing to remove redundancy.
When you subclass a custom Form
class, the resulting subclass will
include all fields of the parent class(es), followed by the fields you define
in the subclass.
In this example, ContactFormWithPriority
contains all the fields from
ContactForm
, plus an additional field, priority
. The ContactForm
fields are ordered first:
>>> class ContactFormWithPriority(ContactForm): ... priority = forms.CharField() >>> f = ContactFormWithPriority(auto_id=False) >>> print(f.as_div()) <div>Subject:<input type="text" name="subject" maxlength="100" required></div> <div>Message:<textarea name="message" cols="40" rows="10" required></textarea></div> <div>Sender:<input type="email" name="sender" required></div> <div>Cc myself:<input type="checkbox" name="cc_myself"></div> <div>Priority:<input type="text" name="priority" required></div>
It’s possible to subclass multiple forms, treating forms as mixins. In this
example, BeatleForm
subclasses both PersonForm
and InstrumentForm
(in that order), and its field list includes the fields from the parent
classes:
>>> from django import forms >>> class PersonForm(forms.Form): ... first_name = forms.CharField() ... last_name = forms.CharField() >>> class InstrumentForm(forms.Form): ... instrument = forms.CharField() >>> class BeatleForm(InstrumentForm, PersonForm): ... haircut_type = forms.CharField() >>> b = BeatleForm(auto_id=False) >>> print(b.as_div()) <div>First name:<input type="text" name="first_name" required></div> <div>Last name:<input type="text" name="last_name" required></div> <div>Instrument:<input type="text" name="instrument" required></div> <div>Haircut type:<input type="text" name="haircut_type" required></div>
It’s possible to declaratively remove a Field
inherited from a parent class
by setting the name of the field to None
on the subclass. For example:
>>> from django import forms >>> class ParentForm(forms.Form): ... name = forms.CharField() ... age = forms.IntegerField() >>> class ChildForm(ParentForm): ... name = None >>> list(ChildForm().fields) ['age']
Prefixes for forms¶
-
Form.
prefix
¶
You can put several Django forms inside one <form>
tag. To give each
Form
its own namespace, use the prefix
keyword argument:
>>> mother = PersonForm(prefix="mother") >>> father = PersonForm(prefix="father") >>> print(mother.as_div()) <div><label for="id_mother-first_name">First name:</label><input type="text" name="mother-first_name" required id="id_mother-first_name"></div> <div><label for="id_mother-last_name">Last name:</label><input type="text" name="mother-last_name" required id="id_mother-last_name"></div> >>> print(father.as_div()) <div><label for="id_father-first_name">First name:</label><input type="text" name="father-first_name" required id="id_father-first_name"></div> <div><label for="id_father-last_name">Last name:</label><input type="text" name="father-last_name" required id="id_father-last_name"></div>
The prefix can also be specified on the form class:
>>> class PersonForm(forms.Form): ... ... ... prefix = 'person'
Валидация форм и полей¶
Валидация формы происходит при очистке данных. Если вы хотите настроить этот процесс, есть различные места для внесения изменений, каждое из которых служит для разных целей. В процессе обработки формы выполняются три типа методов очистки. Обычно они выполняются, когда вы вызываете метод is_valid()
на форме. Есть и другие вещи, которые также могут вызвать очистку и проверку (обращение к атрибуту errors
или прямой вызов full_clean()
), но обычно они не нужны.
В общем, любой метод очистки может поднять ValidationError
, если есть проблема с данными, которые он обрабатывает, передавая соответствующую информацию конструктору ValidationError
. See below для лучшей практики поднятия ValidationError
. Если не поднимается ValidationError
, метод должен вернуть очищенные (нормализованные) данные в виде объекта Python.
Большинство валидаций можно выполнить с помощью validators — помощников, которые можно использовать повторно. Валидаторы — это функции (или callables), которые принимают один аргумент и вызывают ValidationError
при недопустимом вводе. Валидаторы запускаются после вызова методов to_python
и validate
поля.
Валидация формы разбита на несколько этапов, которые можно настроить или отменить:
-
Метод
to_python()
наField
является первым шагом в каждой валидации. Он преобразует значение к правильному типу данных и выдает сообщениеValidationError
, если это невозможно. Этот метод принимает необработанное значение от виджета и возвращает преобразованное значение. Например,FloatField
превратит данные в Pythonfloat
или выдастValidationError
. -
Метод
validate()
наField
обрабатывает специфическую для поля валидацию, которая не подходит для валидатора. Он принимает значение, которое было приведено к правильному типу данных, и при любой ошибке выдает сообщениеValidationError
. Этот метод ничего не возвращает и не должен изменять значение. Вы должны переопределить его для обработки логики валидации, которую вы не можете или не хотите поместить в валидатор. -
Метод
run_validators()
на полеField
запускает все валидаторы поля и объединяет все ошибки в одинValidationError
. Вам не нужно переопределять этот метод. -
Метод
clean()
в подклассеField
отвечает за выполнениеto_python()
,validate()
иrun_validators()
в правильном порядке и распространение их ошибок. Если в любой момент времени какой-либо из методов вызывает ошибкуValidationError
, валидация останавливается, и эта ошибка выдается. Этот метод возвращает чистые данные, которые затем вставляются в словарьcleaned_data
формы. -
Метод
clean_<fieldname>()
вызывается на подклассе формы – где<fieldname>
заменяется на имя атрибута поля формы. Этот метод выполняет любую очистку, специфичную для данного атрибута, не связанную с типом поля, которым он является. Этому методу не передаются никакие параметры. Вам нужно будет найти значение поля вself.cleaned_data
и помнить, что в этот момент это будет объект Python, а не исходная строка, представленная в форме (она будет вcleaned_data
, потому что метод general fieldclean()
, описанный выше, уже однажды очистил данные).Например, если вы хотите проверить, что содержимое
CharField
под названиемserialnumber
является уникальным,clean_serialnumber()
будет подходящим местом для этого. Вам не нужно конкретное поле (этоCharField
), но вам нужен специфический для поля формы фрагмент проверки и, возможно, очистки/нормализации данных.Возвращаемое значение этого метода заменяет существующее значение в
cleaned_data
, поэтому это должно быть значение поля изcleaned_data
(даже если этот метод не изменил его) или новое очищенное значение. -
Метод
clean()
подкласса формы может выполнять валидацию, требующую доступа к нескольким полям формы. Сюда можно отнести такие проверки, как «если полеA
предоставлено, то полеB
должно содержать действительный адрес электронной почты». При желании этот метод может вернуть совершенно другой словарь, который будет использован в качествеcleaned_data
.Поскольку методы валидации полей были запущены к моменту вызова
clean()
, у вас также есть доступ к атрибутуerrors
формы, который содержит все ошибки, возникшие при очистке отдельных полей.Обратите внимание, что любые ошибки, возникающие при переопределении
Form.clean()
, не будут связаны с каким-либо конкретным полем. Они попадают в специальное «поле» (называемое__all__
), к которому вы можете получить доступ через методnon_field_errors()
, если вам это необходимо. Если вы хотите прикрепить ошибки к определенному полю формы, вам нужно вызватьadd_error()
.Также обратите внимание, что существуют особые соображения при переопределении метода
clean()
подклассаModelForm
. (см. ModelForm documentation для получения дополнительной информации)
Эти методы выполняются в указанном выше порядке, по одному полю за раз. То есть, для каждого поля формы (в порядке их объявления в определении формы) выполняется метод Field.clean()
(или его переопределение), затем clean_<fieldname>()
. Наконец, когда эти два метода выполнены для каждого поля, выполняется метод Form.clean()
, или его переопределение, независимо от того, вызвали ли предыдущие методы ошибки.
Примеры каждого из этих методов приведены ниже.
Как уже упоминалось, любой из этих методов может вызвать ошибку ValidationError
. Для любого поля, если метод Field.clean()
вызывает ValidationError
, любой метод очистки, специфичный для данного поля, не вызывается. Однако методы очистки для всех оставшихся полей все равно выполняются.
Поднятие ValidationError
¶
Чтобы сделать сообщения об ошибках гибкими и легко переопределяемыми, примите во внимание следующие рекомендации:
-
Предоставить описательную ошибку
code
конструктору:# Good ValidationError(_('Invalid value'), code='invalid') # Bad ValidationError(_('Invalid value'))
-
Не вставляйте переменные в сообщение; используйте заполнители и аргумент
params
конструктора:# Good ValidationError( _('Invalid value: %(value)s'), params={'value': '42'}, ) # Bad ValidationError(_('Invalid value: %s') % value)
-
Используйте ключи отображения вместо позиционного форматирования. Это позволяет располагать переменные в любом порядке или вообще их не использовать при переписывании сообщения:
# Good ValidationError( _('Invalid value: %(value)s'), params={'value': '42'}, ) # Bad ValidationError( _('Invalid value: %s'), params=('42',), )
-
Оберните сообщение символом
gettext
, чтобы включить перевод:# Good ValidationError(_('Invalid value')) # Bad ValidationError('Invalid value')
Собираем все вместе:
raise ValidationError( _('Invalid value: %(value)s'), code='invalid', params={'value': '42'}, )
Следование этим рекомендациям особенно необходимо, если вы пишете многократно используемые формы, поля форм и поля моделей.
Хотя это и не рекомендуется, если вы находитесь в конце цепочки валидации (т.е. ваша форма clean()
метод) и вы знаете, что вам никогда не понадобится переопределять сообщение об ошибке, вы можете выбрать менее многословный вариант:
ValidationError(_('Invalid value: %s') % value)
Методы Form.errors.as_data()
и Form.errors.as_json()
значительно выигрывают от полнофункциональных ValidationError
s (с code
именем и params
словарем).
Возникновение множества ошибок¶
Если вы обнаружили несколько ошибок во время работы метода очистки и хотите сигнализировать обо всех из них отправителю формы, можно передать список ошибок конструктору ValidationError
.
Как и выше, рекомендуется передавать список экземпляров ValidationError
с code
s и params
, но подойдет и список строк:
# Good raise ValidationError([ ValidationError(_('Error 1'), code='error1'), ValidationError(_('Error 2'), code='error2'), ]) # Bad raise ValidationError([ _('Error 1'), _('Error 2'), ])
Использование валидации на практике¶
В предыдущих разделах объяснялось, как работает валидация в целом для форм. Поскольку иногда бывает проще понять, как работает каждая функция, здесь приведена серия небольших примеров, в которых используется каждая из предыдущих функций.
Использование валидаторов¶
Поля формы (и модели) Django поддерживают использование полезных функций и классов, известных как валидаторы. Валидатор — это вызываемый объект или функция, которая принимает значение и не возвращает ничего, если значение действительно, или выдает ошибку ValidationError
, если нет. Они могут быть переданы в конструктор поля через аргумент validators
или определены в самом классе Field
с помощью атрибута default_validators
.
Валидаторы могут использоваться для проверки значений внутри поля, давайте посмотрим на Django’s SlugField
:
from django.core import validators from django.forms import CharField class SlugField(CharField): default_validators = [validators.validate_slug]
Как вы можете видеть, SlugField
— это CharField
с настроенным валидатором, который проверяет, что отправленный текст соответствует некоторым правилам символов. Это также можно сделать при определении поля так:
эквивалентно:
slug = forms.CharField(validators=[validators.validate_slug])
Обычные случаи, такие как проверка по электронной почте или регулярному выражению, могут быть обработаны с помощью существующих классов валидаторов, доступных в Django. Например, validators.validate_slug
— это экземпляр RegexValidator
, построенный с первым аргументом в виде шаблона: ^[-a-zA-Z0-9_]+$
. Смотрите раздел writing validators, чтобы увидеть список того, что уже доступно, и пример того, как написать валидатор.
Очистка полей формы по умолчанию¶
Давайте сначала создадим поле пользовательской формы, которое проверяет, что его входные данные — это строка, содержащая адреса электронной почты, разделенные запятыми. Полный класс выглядит следующим образом:
from django import forms from django.core.validators import validate_email class MultiEmailField(forms.Field): def to_python(self, value): """Normalize data to a list of strings.""" # Return an empty list if no input was given. if not value: return [] return value.split(',') def validate(self, value): """Check if value consists only of valid emails.""" # Use the parent's handling of required fields, etc. super().validate(value) for email in value: validate_email(email)
В каждой форме, использующей это поле, эти методы будут выполняться до того, как с данными поля можно будет сделать что-либо еще. Это очистка, специфичная для данного типа поля, независимо от того, как оно будет использоваться в дальнейшем.
Давайте создадим ContactForm
, чтобы продемонстрировать, как вы будете использовать это поле:
class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() recipients = MultiEmailField() cc_myself = forms.BooleanField(required=False)
Используйте MultiEmailField
как любое другое поле формы. Когда на форме будет вызван метод is_valid()
, в процессе очистки будет запущен метод MultiEmailField.clean()
, который, в свою очередь, вызовет пользовательские методы to_python()
и validate()
.
Очистка определенного атрибута поля¶
Продолжая предыдущий пример, предположим, что в нашем ContactForm
мы хотим убедиться, что поле recipients
всегда содержит адрес "fred@example.com"
. Это проверка, специфичная для нашей формы, поэтому мы не хотим помещать ее в общий класс MultiEmailField
. Вместо этого мы напишем метод очистки, который работает с полем recipients
, следующим образом:
from django import forms from django.core.exceptions import ValidationError class ContactForm(forms.Form): # Everything as before. ... def clean_recipients(self): data = self.cleaned_data['recipients'] if "fred@example.com" not in data: raise ValidationError("You have forgotten about Fred!") # Always return a value to use as the new cleaned data, even if # this method didn't change it. return data
Очистка и проверка полей, которые зависят друг от друга¶
Предположим, мы добавим еще одно требование к нашей контактной форме: если поле cc_myself
является True
, то subject
должно содержать слово "help"
. Мы выполняем проверку более чем одного поля одновременно, поэтому метод формы clean()
является хорошим местом для этого. Обратите внимание, что здесь мы говорим о методе clean()
на форме, тогда как ранее мы писали метод clean()
на поле. Важно четко различать поля и формы, когда мы решаем, где проводить валидацию. Поля — это отдельные точки данных, а формы — это набор полей.
К моменту вызова метода clean()
формы будут запущены все методы очистки отдельных полей (предыдущие два раздела), поэтому self.cleaned_data
будет заполнен любыми данными, которые сохранились до сих пор. Поэтому вам также нужно помнить о том, что поля, которые вы хотите проверить, могут не выдержать первоначальной проверки отдельных полей.
Есть два способа сообщить о любых ошибках на этом этапе. Вероятно, самый распространенный способ — вывести ошибку в верхней части формы. Чтобы создать такую ошибку, вы можете поднять ValidationError
из метода clean()
. Например:
from django import forms from django.core.exceptions import ValidationError class ContactForm(forms.Form): # Everything as before. ... def clean(self): cleaned_data = super().clean() cc_myself = cleaned_data.get("cc_myself") subject = cleaned_data.get("subject") if cc_myself and subject: # Only do something if both fields are valid so far. if "help" not in subject: raise ValidationError( "Did not send for 'help' in the subject despite " "CC'ing yourself." )
В этом коде, если возникает ошибка валидации, форма выводит сообщение об ошибке в верхней части формы (обычно) с описанием проблемы. Такие ошибки являются не-полевыми ошибками, которые отображаются в шаблоне с помощью {{ form.non_field_errors }}
.
Вызов super().clean()
в коде примера гарантирует, что любая логика валидации в родительских классах будет сохранена. Если ваша форма наследует другую, которая не возвращает словарь cleaned_data
в своем методе clean()
(это необязательно), то не присваивайте cleaned_data
результату вызова super()
и используйте self.cleaned_data
вместо этого:
def clean(self): super().clean() cc_myself = self.cleaned_data.get("cc_myself") ...
Второй подход для сообщения об ошибках валидации может включать присвоение сообщения об ошибке одному из полей. В данном случае давайте присвоим сообщение об ошибке обеим строкам «subject» и «cc_myself» в отображении формы. Будьте осторожны, делая это на практике, так как это может привести к запутанному выводу формы. Мы показываем, что здесь возможно, и предоставляем вам и вашим дизайнерам самим решать, что будет эффективно работать в вашей конкретной ситуации. Наш новый код (заменяющий предыдущий пример) выглядит следующим образом:
from django import forms class ContactForm(forms.Form): # Everything as before. ... def clean(self): cleaned_data = super().clean() cc_myself = cleaned_data.get("cc_myself") subject = cleaned_data.get("subject") if cc_myself and subject and "help" not in subject: msg = "Must put 'help' in subject when cc'ing yourself." self.add_error('cc_myself', msg) self.add_error('subject', msg)
Вторым аргументом add_error()
может быть строка или, предпочтительно, экземпляр ValidationError
. Более подробную информацию смотрите в Поднятие ValidationError. Обратите внимание, что add_error()
автоматически удаляет поле из cleaned_data
.
Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments.
The error_messages
argument lets you specify manual error messages for attributes of the field. The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. For example, here is the default error message:
>>> from django import forms >>> generic = forms.CharField() >>> generic.clean('') Traceback (most recent call last): ... ValidationError: ['This field is required.']
And here is a custom error message:
>>> name = forms.CharField( error_messages={ 'required': 'Please enter your name' }) >>> name.clean('') Traceback (most recent call last): ... ValidationError: ['Please enter your name']
Syntax
field_name = models.Field(option = value)
Django Form Field Validation error_messages
Explanation
Illustration of error_messages using an Example. Consider a project named geeksforgeeks
having an app named geeks
.
Refer to the following articles to check how to create a project and an app in Django.
- How to Create a Basic Project using MVT in Django?
- How to Create an App in Django ?
Enter the following code into forms.py
file of geeks app. We will be using CharField for experimenting for all field options.
from
django
import
forms
class
GeeksForm(forms.Form):
geeks_field
=
forms.CharField(
error_messages
=
{
'required'
:
"Please Enter your Name"
})
Add the geeks app to INSTALLED_APPS
INSTALLED_APPS
=
[
'django.contrib.admin'
,
'django.contrib.auth'
,
'django.contrib.contenttypes'
,
'django.contrib.sessions'
,
'django.contrib.messages'
,
'django.contrib.staticfiles'
,
'geeks'
,
]
Now to render this form into a view we need a view and a URL mapped to that view. Let’s create a view first in views.py
of geeks app,
from
django.shortcuts
import
render
from
.forms
import
GeeksForm
def
home_view(request):
context
=
{}
form
=
GeeksForm(request.POST
or
None
)
context[
'form'
]
=
form
if
request.POST:
if
form.is_valid():
temp
=
form.cleaned_data.get(
"geeks_field"
)
print
(temp)
return
render(request,
"home.html"
, context)
Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.
Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html
.
<
form
method
=
"POST"
>
{% csrf_token %}
{{ form }}
<
input
type
=
"submit"
value
=
"Submit"
>
</
form
>
Finally, a URL to map to this view in urls.py
from
django.urls
import
path
from
.views
import
home_view
URLpatterns
=
[
path('', home_view ),
]
Let’s run the server and check what has actually happened, Run
Python manage.py runserver
Now let’s try to submit it empty and check if required error_message
has been overridden.
Thus the field is displaying a custom error message for required
attribute of Charfield.
More Built-in Form Validations
Field Options | Description |
---|---|
required | By default, each Field class assumes the value is required, so to make it not required you need to set required=False |
label | The label argument lets you specify the “human-friendly” label for this field. This is used when the Field is displayed in a Form. |
label_suffix | The label_suffix argument lets you override the form’s label_suffix on a per-field basis. |
widget | The widget argument lets you specify a Widget class to use when rendering this Field. See Widgets for more information. |
help_text | The help_text argument lets you specify descriptive text for this Field. If you provide help_text, it will be displayed next to the Field when the Field is rendered by one of the convenience Form methods. |
error_messages | The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. |
validators | The validators argument lets you provide a list of validation functions for this field. |
localize | The localize argument enables the localization of form data input, as well as the rendered output. |
disabled. | The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. |
In Django documentation https://docs.djangoproject.com/en/dev/ref/forms/validation/#raising-validationerror said that it is good practice to prodive error code while raising ValidationError exception.
# Good
ValidationError(_('Invalid value'), code='invalid')
# Bad
ValidationError(_('Invalid value'))
I have API in my application and I’m using form to validate input data.
If form is not valid, I whant to get these error codes (not error messages).
So I looked at source code of _clean_fields method of BaseForm:
https://github.com/django/django/blob/master/django/forms/forms.py#L278
except ValidationError as e:
self._errors[name] = self.error_class(e.messages)
if name in self.cleaned_data:
del self.cleaned_data[name]
As I understand this parameter (self.code
) is not passed anywhere and can not be obtained after the form validation.
Can someone explain what the purpose of using this error code?
asked Sep 13, 2013 at 8:17
2
In Django 1.7, you can now access the original error data from the form. You can call the as_data()
method on an ErrorList
or ErrorDict
. For example: my_form.errors.as_data()
. This basically gives you the original ValidationError
object instead of the message itself. From this you can access the .code
property, eg: my_form.errors["__all__"].as_data()[0].code
.
You can also serialize form errors, great for APIs:
>>> print(form.errors.as_json())
{"__all__": [
{"message": "Your account has not been activated.", "code": "inactive"}
]}
answered Jul 21, 2014 at 20:43
Ben DavisBen Davis
12.6k10 gold badges48 silver badges58 bronze badges
1
Take a look at ValidationError definition in django src, it’s used as a convenient way to pass additional identifier (similar to e.errno
in standard python exception), you can use it like this:
try:
...
raise ValidationError(u'Oops', code=0x800)
...
except ValidationError as e:
print "Error code: ", e.code
answered Sep 13, 2013 at 9:36
mariodevmariodev
13.7k3 gold badges49 silver badges61 bronze badges
2
- Previous
- Overview: Django
- Next
In this tutorial, we’ll show you how to work with HTML Forms in Django, and, in particular, the easiest way to write forms to create, update, and delete model instances. As part of this demonstration, we’ll extend the LocalLibrary website so that librarians can renew books, and create, update, and delete authors using our own forms (rather than using the admin application).
Prerequisites: |
Complete all previous tutorial topics, including Django Tutorial Part 8: User authentication and permissions. |
---|---|
Objective: |
To understand how to write forms to get information from users and update the database. To understand how the generic class-based editing views can vastly simplify creating forms for working with a single model. |
Overview
An HTML Form is a group of one or more fields/widgets on a web page, which can be used to collect information from users for submission to a server. Forms are a flexible mechanism for collecting user input because there are suitable widgets for entering many different types of data, including text boxes, checkboxes, radio buttons, date pickers and so on. Forms are also a relatively secure way of sharing data with the server, as they allow us to send data in POST
requests with cross-site request forgery protection.
While we haven’t created any forms in this tutorial so far, we’ve already encountered them in the Django Admin site — for example, the screenshot below shows a form for editing one of our Book models, comprised of a number of selection lists and text editors.
Working with forms can be complicated! Developers need to write HTML for the form, validate and properly sanitize entered data on the server (and possibly also in the browser), repost the form with error messages to inform users of any invalid fields, handle the data when it has successfully been submitted, and finally respond to the user in some way to indicate success. Django Forms take a lot of the work out of all these steps, by providing a framework that lets you define forms and their fields programmatically, and then use these objects to both generate the form HTML code and handle much of the validation and user interaction.
In this tutorial, we’re going to show you a few of the ways you can create and work with forms, and in particular, how the generic editing views can significantly reduce the amount of work you need to do to create forms to manipulate your models. Along the way, we’ll extend our LocalLibrary application by adding a form to allow librarians to renew library books, and we’ll create pages to create, edit and delete books and authors (reproducing a basic version of the form shown above for editing books).
HTML Forms
First, a brief overview of HTML Forms. Consider a simple HTML form, with a single text field for entering the name of some «team», and its associated label:
The form is defined in HTML as a collection of elements inside <form>…</form>
tags, containing at least one input
element of type="submit"
.
<form action="/team_name_url/" method="post">
<label for="team_name">Enter name: </label>
<input
id="team_name"
type="text"
name="name_field"
value="Default name for team." />
<input type="submit" value="OK" />
</form>
While here we just have one text field for entering the team name, a form may have any number of other input elements and their associated labels. The field’s type
attribute defines what sort of widget will be displayed. The name
and id
of the field are used to identify the field in JavaScript/CSS/HTML, while value
defines the initial value for the field when it is first displayed. The matching team label is specified using the label
tag (see «Enter name» above), with a for
field containing the id
value of the associated input
.
The submit
input will be displayed as a button by default.
This can be pressed to upload the data in all the other input elements in the form to the server (in this case, just the team_name
field).
The form attributes define the HTTP method
used to send the data and the destination of the data on the server (action
):
action
: The resource/URL where data is to be sent for processing when the form is submitted. If this is not set (or set to an empty string), then the form will be submitted back to the current page URL.method
: The HTTP method used to send the data: post or get.- The
POST
method should always be used if the data is going to result in a change to the server’s database, because it can be made more resistant to cross-site forgery request attacks. - The
GET
method should only be used for forms that don’t change user data (for example, a search form). It is recommended for when you want to be able to bookmark or share the URL.
- The
The role of the server is first to render the initial form state — either containing blank fields or pre-populated with initial values. After the user presses the submit button, the server will receive the form data with values from the web browser and must validate the information. If the form contains invalid data, the server should display the form again, this time with user-entered data in «valid» fields and messages to describe the problem for the invalid fields. Once the server gets a request with all valid form data, it can perform an appropriate action (such as: saving the data, returning the result of a search, uploading a file, etc.) and then notify the user.
As you can imagine, creating the HTML, validating the returned data, re-displaying the entered data with error reports if needed, and performing the desired operation on valid data can all take quite a lot of effort to «get right». Django makes this a lot easier by taking away some of the heavy lifting and repetitive code!
Django form handling process
Django’s form handling uses all of the same techniques that we learned about in previous tutorials (for displaying information about our models): the view gets a request, performs any actions required including reading data from the models, then generates and returns an HTML page (from a template, into which we pass a context containing the data to be displayed). What makes things more complicated is that the server also needs to be able to process data provided by the user, and redisplay the page if there are any errors.
A process flowchart of how Django handles form requests is shown below, starting with a request for a page containing a form (shown in green).
Based on the diagram above, the main things that Django’s form handling does are:
- Display the default form the first time it is requested by the user.
- The form may contain blank fields if you’re creating a new record, or it may be pre-populated with initial values (for example, if you are changing a record, or have useful default initial values).
- The form is referred to as unbound at this point, because it isn’t associated with any user-entered data (though it may have initial values).
- Receive data from a submit request and bind it to the form.
- Binding data to the form means that the user-entered data and any errors are available when we need to redisplay the form.
- Clean and validate the data.
- Cleaning the data performs sanitization of the input fields, such as removing invalid characters that might be used to send malicious content to the server, and converts them into consistent Python types.
- Validation checks that the values are appropriate for the field (for example, that they are in the right date range, aren’t too short or too long, etc.)
- If any data is invalid, re-display the form, this time with any user populated values and error messages for the problem fields.
- If all data is valid, perform required actions (such as save the data, send an email, return the result of a search, upload a file, and so on).
- Once all actions are complete, redirect the user to another page.
Django provides a number of tools and approaches to help you with the tasks detailed above. The most fundamental is the Form
class, which simplifies both generation of form HTML and data cleaning/validation. In the next section, we describe how forms work using the practical example of a page to allow librarians to renew books.
Note: Understanding how Form
is used will help you when we discuss Django’s more «high level» form framework classes.
Renew-book form using a Form and function view
Next, we’re going to add a page to allow librarians to renew borrowed books. To do this we’ll create a form that allows users to enter a date value. We’ll seed the field with an initial value 3 weeks from the current date (the normal borrowing period), and add some validation to ensure that the librarian can’t enter a date in the past or a date too far in the future. When a valid date has been entered, we’ll write it to the current record’s BookInstance.due_back
field.
The example will use a function-based view and a Form
class. The following sections explain how forms work, and the changes you need to make to our ongoing LocalLibrary project.
Form
The Form
class is the heart of Django’s form handling system. It specifies the fields in the form, their layout, display widgets, labels, initial values, valid values, and (once validated) the error messages associated with invalid fields. The class also provides methods for rendering itself in templates using predefined formats (tables, lists, etc.) or for getting the value of any element (enabling fine-grained manual rendering).
Declaring a Form
The declaration syntax for a Form
is very similar to that for declaring a Model
, and shares the same field types (and some similar parameters). This makes sense because in both cases we need to ensure that each field handles the right types of data, is constrained to valid data, and has a description for display/documentation.
Form data is stored in an application’s forms.py file, inside the application directory. Create and open the file locallibrary/catalog/forms.py. To create a Form
, we import the forms
library, derive from the Form
class, and declare the form’s fields. A very basic form class for our library book renewal form is shown below — add this to your new file:
from django import forms
class RenewBookForm(forms.Form):
renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).")
Form fields
In this case, we have a single DateField
for entering the renewal date that will render in HTML with a blank value, the default label «Renewal date:«, and some helpful usage text: «Enter a date between now and 4 weeks (default 3 weeks).» As none of the other optional arguments are specified the field will accept dates using the input_formats: YYYY-MM-DD (2016-11-06), MM/DD/YYYY (02/26/2016), MM/DD/YY (10/25/16), and will be rendered using the default widget: DateInput.
There are many other types of form fields, which you will largely recognize from their similarity to the equivalent model field classes:
BooleanField
CharField
ChoiceField
TypedChoiceField
DateField
DateTimeField
DecimalField
DurationField
EmailField
FileField
FilePathField
FloatField
ImageField
IntegerField
GenericIPAddressField
MultipleChoiceField
TypedMultipleChoiceField
NullBooleanField
RegexField
SlugField
TimeField
URLField
UUIDField
ComboField
MultiValueField
SplitDateTimeField
ModelMultipleChoiceField
ModelChoiceField
The arguments that are common to most fields are listed below (these have sensible default values):
required
: IfTrue
, the field may not be left blank or given aNone
value. Fields are required by default, so you would setrequired=False
to allow blank values in the form.label
: The label to use when rendering the field in HTML. If a label is not specified, Django will create one from the field name by capitalizing the first letter and replacing underscores with spaces (e.g. Renewal date).label_suffix
: By default, a colon is displayed after the label (e.g. Renewal date:). This argument allows you to specify a different suffix containing other character(s).initial
: The initial value for the field when the form is displayed.widget
: The display widget to use.help_text
(as seen in the example above): Additional text that can be displayed in forms to explain how to use the field.error_messages
: A list of error messages for the field. You can override these with your own messages if needed.validators
: A list of functions that will be called on the field when it is validated.localize
: Enables the localization of form data input (see link for more information).disabled
: The field is displayed but its value cannot be edited if this isTrue
. The default isFalse
.
Validation
Django provides numerous places where you can validate your data. The easiest way to validate a single field is to override the method clean_<fieldname>()
for the field you want to check. So for example, we can validate that entered renewal_date
values are between now and 4 weeks by implementing clean_renewal_date()
as shown below.
Update your forms.py file so it looks like this:
import datetime
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
class RenewBookForm(forms.Form):
renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).")
def clean_renewal_date(self):
data = self.cleaned_data['renewal_date']
# Check if a date is not in the past.
if data < datetime.date.today():
raise ValidationError(_('Invalid date - renewal in past'))
# Check if a date is in the allowed range (+4 weeks from today).
if data > datetime.date.today() + datetime.timedelta(weeks=4):
raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))
# Remember to always return the cleaned data.
return data
There are two important things to note. The first is that we get our data using self.cleaned_data['renewal_date']
and that we return this data whether or not we change it at the end of the function.
This step gets us the data «cleaned» and sanitized of potentially unsafe input using the default validators, and converted into the correct standard type for the data (in this case a Python datetime.datetime
object).
The second point is that if a value falls outside our range we raise a ValidationError
, specifying the error text that we want to display in the form if an invalid value is entered.
The example above also wraps this text in one of Django’s translation functions, gettext_lazy()
(imported as _()
), which is good practice if you want to translate your site later.
Note: There are numerous other methods and examples for validating forms in Form and field validation (Django docs). For example, in cases where you have multiple fields that depend on each other, you can override the Form.clean() function and again raise a ValidationError
.
That’s all we need for the form in this example!
URL configuration
Before we create our view, let’s add a URL configuration for the renew-books page. Copy the following configuration to the bottom of locallibrary/catalog/urls.py:
urlpatterns += [
path('book/<uuid:pk>/renew/', views.renew_book_librarian, name='renew-book-librarian'),
]
The URL configuration will redirect URLs with the format /catalog/book/<bookinstance_id>/renew/ to the function named renew_book_librarian()
in views.py, and send the BookInstance
id as the parameter named pk
. The pattern only matches if pk
is a correctly formatted uuid
.
Note: We can name our captured URL data «pk
» anything we like, because we have complete control over the view function (we’re not using a generic detail view class that expects parameters with a certain name). However, pk
short for «primary key», is a reasonable convention to use!
View
As discussed in the Django form handling process above, the view has to render the default form when it is first called and then either re-render it with error messages if the data is invalid, or process the data and redirect to a new page if the data is valid. In order to perform these different actions, the view has to be able to know whether it is being called for the first time to render the default form, or a subsequent time to validate data.
For forms that use a POST
request to submit information to the server, the most common pattern is for the view to test against the POST
request type (if request.method == 'POST':
) to identify form validation requests and GET
(using an else
condition) to identify the initial form creation request. If you want to submit your data using a GET
request, then a typical approach for identifying whether this is the first or subsequent view invocation is to read the form data (e.g. to read a hidden value in the form).
The book renewal process will be writing to our database, so, by convention, we use the POST
request approach.
The code fragment below shows the (very standard) pattern for this sort of function view.
import datetime
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from catalog.forms import RenewBookForm
def renew_book_librarian(request, pk):
book_instance = get_object_or_404(BookInstance, pk=pk)
# If this is a POST request then process the Form data
if request.method == 'POST':
# Create a form instance and populate it with data from the request (binding):
form = RenewBookForm(request.POST)
# Check if the form is valid:
if form.is_valid():
# process the data in form.cleaned_data as required (here we just write it to the model due_back field)
book_instance.due_back = form.cleaned_data['renewal_date']
book_instance.save()
# redirect to a new URL:
return HttpResponseRedirect(reverse('all-borrowed'))
# If this is a GET (or any other method) create the default form.
else:
proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
form = RenewBookForm(initial={'renewal_date': proposed_renewal_date})
context = {
'form': form,
'book_instance': book_instance,
}
return render(request, 'catalog/book_renew_librarian.html', context)
First, we import our form (RenewBookForm
) and a number of other useful objects/methods used in the body of the view function:
get_object_or_404()
: Returns a specified object from a model based on its primary key value, and raises anHttp404
exception (not found) if the record does not exist.HttpResponseRedirect
: This creates a redirect to a specified URL (HTTP status code 302).reverse()
: This generates a URL from a URL configuration name and a set of arguments. It is the Python equivalent of theurl
tag that we’ve been using in our templates.datetime
: A Python library for manipulating dates and times.
In the view, we first use the pk
argument in get_object_or_404()
to get the current BookInstance
(if this does not exist, the view will immediately exit and the page will display a «not found» error).
If this is not a POST
request (handled by the else
clause) then we create the default form passing in an initial
value for the renewal_date
field, 3 weeks from the current date.
book_instance = get_object_or_404(BookInstance, pk=pk)
# If this is a GET (or any other method) create the default form
else:
proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
form = RenewBookForm(initial={'renewal_date': proposed_renewal_date})
context = {
'form': form,
'book_instance': book_instance,
}
return render(request, 'catalog/book_renew_librarian.html', context)
After creating the form, we call render()
to create the HTML page, specifying the template and a context that contains our form. In this case, the context also contains our BookInstance
, which we’ll use in the template to provide information about the book we’re renewing.
However, if this is a POST
request, then we create our form
object and populate it with data from the request. This process is called «binding» and allows us to validate the form.
We then check if the form is valid, which runs all the validation code on all of the fields — including both the generic code to check that our date field is actually a valid date and our specific form’s clean_renewal_date()
function to check the date is in the right range.
book_instance = get_object_or_404(BookInstance, pk=pk)
# If this is a POST request then process the Form data
if request.method == 'POST':
# Create a form instance and populate it with data from the request (binding):
form = RenewBookForm(request.POST)
# Check if the form is valid:
if form.is_valid():
# process the data in form.cleaned_data as required (here we just write it to the model due_back field)
book_instance.due_back = form.cleaned_data['renewal_date']
book_instance.save()
# redirect to a new URL:
return HttpResponseRedirect(reverse('all-borrowed'))
context = {
'form': form,
'book_instance': book_instance,
}
return render(request, 'catalog/book_renew_librarian.html', context)
If the form is not valid we call render()
again, but this time the form value passed in the context will include error messages.
If the form is valid, then we can start to use the data, accessing it through the form.cleaned_data
attribute (e.g. data = form.cleaned_data['renewal_date']
). Here, we just save the data into the due_back
value of the associated BookInstance
object.
Warning: While you can also access the form data directly through the request (for example, request.POST['renewal_date']
or request.GET['renewal_date']
if using a GET request), this is NOT recommended. The cleaned data is sanitized, validated, and converted into Python-friendly types.
The final step in the form-handling part of the view is to redirect to another page, usually a «success» page. In this case, we use HttpResponseRedirect
and reverse()
to redirect to the view named 'all-borrowed'
(this was created as the «challenge» in Django Tutorial Part 8: User authentication and permissions). If you didn’t create that page consider redirecting to the home page at URL ‘/
‘).
That’s everything needed for the form handling itself, but we still need to restrict access to the view to just logged-in librarians who have permission to renew books. We use @login_required
to require that the user is logged in, and the @permission_required
function decorator with our existing can_mark_returned
permission to allow access (decorators are processed in order). Note that we probably should have created a new permission setting in BookInstance
(«can_renew
«), but we will reuse the existing one to keep the example simple.
The final view is therefore as shown below. Please copy this into the bottom of locallibrary/catalog/views.py.
import datetime
from django.contrib.auth.decorators import login_required, permission_required
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from catalog.forms import RenewBookForm
@login_required
@permission_required('catalog.can_mark_returned', raise_exception=True)
def renew_book_librarian(request, pk):
"""View function for renewing a specific BookInstance by librarian."""
book_instance = get_object_or_404(BookInstance, pk=pk)
# If this is a POST request then process the Form data
if request.method == 'POST':
# Create a form instance and populate it with data from the request (binding):
form = RenewBookForm(request.POST)
# Check if the form is valid:
if form.is_valid():
# process the data in form.cleaned_data as required (here we just write it to the model due_back field)
book_instance.due_back = form.cleaned_data['renewal_date']
book_instance.save()
# redirect to a new URL:
return HttpResponseRedirect(reverse('all-borrowed'))
# If this is a GET (or any other method) create the default form.
else:
proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
form = RenewBookForm(initial={'renewal_date': proposed_renewal_date})
context = {
'form': form,
'book_instance': book_instance,
}
return render(request, 'book_renew_librarian.html', context)
The template
Create the template referenced in the view (/catalog/templates/catalog/book_renew_librarian.html) and copy the code below into it:
{% extends "base_generic.html" %}
{% block content %}
<h1>Renew: {{ book_instance.book.title }}</h1>
<p>Borrower: {{ book_instance.borrower }}</p>
<p{% if book_instance.is_overdue %} class="text-danger"{% endif %}>Due date: {{ book_instance.due_back }}</p>
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
{% endblock %}
Most of this will be completely familiar from previous tutorials.
We extend the base template and then redefine the content block. We are able to reference {{ book_instance }}
(and its variables) because it was passed into the context object in the render()
function, and we use these to list the book title, borrower, and the original due date.
The form code is relatively simple. First, we declare the form
tags, specifying where the form is to be submitted (action
) and the method
for submitting the data (in this case an «HTTP POST
«) — if you recall the HTML Forms overview at the top of the page, an empty action
as shown, means that the form data will be posted back to the current URL of the page (which is what we want). Inside the tags, we define the submit
input, which a user can press to submit the data. The {% csrf_token %}
added just inside the form tags is part of Django’s cross-site forgery protection.
Note: Add the {% csrf_token %}
to every Django template you create that uses POST
to submit data. This will reduce the chance of forms being hijacked by malicious users.
All that’s left is the {{ form }}
template variable, which we passed to the template in the context dictionary. Perhaps unsurprisingly, when used as shown this provides the default rendering of all the form fields, including their labels, widgets, and help text — the rendering is as shown below:
<tr>
<th><label for="id_renewal_date">Renewal date:</label></th>
<td>
<input
id="id_renewal_date"
name="renewal_date"
type="text"
value="2016-11-08"
required />
<br />
<span class="helptext">Enter date between now and 4 weeks (default 3 weeks).</span>
</td>
</tr>
Note: It is perhaps not obvious because we only have one field, but, by default, every field is defined in its own table row. This same rendering is provided if you reference the template variable {{ form.as_table }}
.
If you were to enter an invalid date, you’d additionally get a list of the errors rendered on the page (see errorlist
below).
<tr>
<th><label for="id_renewal_date">Renewal date:</label></th>
<td>
<ul class="errorlist">
<li>Invalid date - renewal in past</li>
</ul>
<input
id="id_renewal_date"
name="renewal_date"
type="text"
value="2015-11-08"
required />
<br />
<span class="helptext">Enter date between now and 4 weeks (default 3 weeks).</span>
</td>
</tr>
Other ways of using form template variable
Using {{ form.as_table }}
as shown above, each field is rendered as a table row. You can also render each field as a list item (using {{ form.as_ul }}
) or as a paragraph (using {{ form.as_p }}
).
It is also possible to have complete control over the rendering of each part of the form, by indexing its properties using dot notation. So, for example, we can access a number of separate items for our renewal_date
field:
{{ form.renewal_date }}:
The whole field.{{ form.renewal_date.errors }}
: The list of errors.{{ form.renewal_date.id_for_label }}
: The id of the label.{{ form.renewal_date.help_text }}
: The field help text.
For more examples of how to manually render forms in templates and dynamically loop over template fields, see Working with forms > Rendering fields manually (Django docs).
Testing the page
If you accepted the «challenge» in Django Tutorial Part 8: User authentication and permissions you’ll have a list of all books on loan in the library, which is only visible to library staff. We can add a link to our renew page next to each item using the template code below.
{% if perms.catalog.can_mark_returned %}- <a href="{% url 'renew-book-librarian' bookinst.id %}">Renew</a> {% endif %}
Note: Remember that your test login will need to have the permission «catalog.can_mark_returned
» in order to access the renew book page (perhaps use your superuser account).
You can alternatively manually construct a test URL like this — http://127.0.0.1:8000/catalog/book/<bookinstance_id>/renew/
(a valid bookinstance_id
can be obtained by navigating to a book detail page in your library, and copying the id
field).
What does it look like?
If you are successful, the default form will look like this:
The form with an invalid value entered will look like this:
The list of all books with renew links will look like this:
ModelForms
Creating a Form
class using the approach described above is very flexible, allowing you to create whatever sort of form page you like and associate it with any model or models.
However, if you just need a form to map the fields of a single model then your model will already define most of the information that you need in your form: fields, labels, help text and so on. Rather than recreating the model definitions in your form, it is easier to use the ModelForm helper class to create the form from your model. This ModelForm
can then be used within your views in exactly the same way as an ordinary Form
.
A basic ModelForm
containing the same field as our original RenewBookForm
is shown below. All you need to do to create the form is add class Meta
with the associated model
(BookInstance
) and a list of the model fields
to include in the form.
from django.forms import ModelForm
from catalog.models import BookInstance
class RenewBookModelForm(ModelForm):
class Meta:
model = BookInstance
fields = ['due_back']
Note: You can also include all fields in the form using fields = '__all__'
, or you can use exclude
(instead of fields
) to specify the fields not to include from the model).
Neither approach is recommended because new fields added to the model are then automatically included in the form (without the developer necessarily considering possible security implications).
Note: This might not look all that much simpler than just using a Form
(and it isn’t in this case, because we just have one field). However, if you have a lot of fields, it can reduce the amount of code quite significantly!
The rest of the information comes from the model field definitions (e.g. labels, widgets, help text, error messages). If these aren’t quite right, then we can override them in our class Meta
, specifying a dictionary containing the field to change and its new value. For example, in this form, we might want a label for our field of «Renewal date» (rather than the default based on the field name: Due Back), and we also want our help text to be specific to this use case.
The Meta
below shows you how to override these fields, and you can similarly set widgets
and error_messages
if the defaults aren’t sufficient.
class Meta:
model = BookInstance
fields = ['due_back']
labels = {'due_back': _('New renewal date')}
help_texts = {'due_back': _('Enter a date between now and 4 weeks (default 3).')}
To add validation you can use the same approach as for a normal Form
— you define a function named clean_<field_name>()
and raise ValidationError
exceptions for invalid values.
The only difference with respect to our original form is that the model field is named due_back
and not «renewal_date
«.
This change is necessary since the corresponding field in BookInstance
is called due_back
.
from django.forms import ModelForm
from catalog.models import BookInstance
class RenewBookModelForm(ModelForm):
def clean_due_back(self):
data = self.cleaned_data['due_back']
# Check if a date is not in the past.
if data < datetime.date.today():
raise ValidationError(_('Invalid date - renewal in past'))
# Check if a date is in the allowed range (+4 weeks from today).
if data > datetime.date.today() + datetime.timedelta(weeks=4):
raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))
# Remember to always return the cleaned data.
return data
class Meta:
model = BookInstance
fields = ['due_back']
labels = {'due_back': _('Renewal date')}
help_texts = {'due_back': _('Enter a date between now and 4 weeks (default 3).')}
The class RenewBookModelForm
above is now functionally equivalent to our original RenewBookForm
. You could import and use it wherever you currently use RenewBookForm
as long as you also update the corresponding form variable name from renewal_date
to due_back
as in the second form declaration: RenewBookModelForm(initial={'due_back': proposed_renewal_date}
.
Generic editing views
The form handling algorithm we used in our function view example above represents an extremely common pattern in form editing views. Django abstracts much of this «boilerplate» for you, by creating generic editing views for creating, editing, and deleting views based on models. Not only do these handle the «view» behavior, but they automatically create the form class (a ModelForm
) for you from the model.
Note: In addition to the editing views described here, there is also a FormView class, which lies somewhere between our function view and the other generic views in terms of «flexibility» vs. «coding effort». Using FormView
, you still need to create your Form
, but you don’t have to implement all of the standard form-handling patterns. Instead, you just have to provide an implementation of the function that will be called once the submission is known to be valid.
In this section, we’re going to use generic editing views to create pages to add functionality to create, edit, and delete Author
records from our library — effectively providing a basic reimplementation of parts of the Admin site (this could be useful if you need to offer admin functionality in a more flexible way than can be provided by the admin site).
Views
Open the views file (locallibrary/catalog/views.py) and append the following code block to the bottom of it:
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from catalog.models import Author
class AuthorCreate(CreateView):
model = Author
fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']
initial = {'date_of_death': '11/06/2020'}
class AuthorUpdate(UpdateView):
model = Author
fields = '__all__' # Not recommended (potential security issue if more fields added)
class AuthorDelete(DeleteView):
model = Author
success_url = reverse_lazy('authors')
As you can see, to create, update, or delete the views you need to derive from CreateView
, UpdateView
, and DeleteView
(respectively) and then define the associated model.
For the «create» and «update» cases you also need to specify the fields to display in the form (using the same syntax as for ModelForm
). In this case, we show how to list them individually and the syntax to list «all» fields. You can also specify initial values for each of the fields using a dictionary of field_name/value pairs (here we arbitrarily set the date of death for demonstration purposes — you might want to remove that). By default, these views will redirect on success to a page displaying the newly created/edited model item, which in our case will be the author detail view we created in a previous tutorial. You can specify an alternative redirect location by explicitly declaring parameter success_url
(as done for the AuthorDelete
class).
The AuthorDelete
class doesn’t need to display any of the fields, so these don’t need to be specified. You do however need to specify the success_url
, because there is no obvious default value for Django to use. In this case, we use the reverse_lazy()
function to redirect to our author list after an author has been deleted — reverse_lazy()
is a lazily executed version of reverse()
, used here because we’re providing a URL to a class-based view attribute.
Templates
The «create» and «update» views use the same template by default, which will be named after your model: model_name_form.html
(you can change the suffix to something other than _form using the template_name_suffix
field in your view, for example, template_name_suffix = '_other_suffix'
)
Create the template file locallibrary/catalog/templates/catalog/author_form.html
and copy the text below.
{% extends "base_generic.html" %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit" />
</form>
{% endblock %}
This is similar to our previous forms and renders the fields using a table. Note also how again we declare the {% csrf_token %}
to ensure that our forms are resistant to CSRF attacks.
The «delete» view expects to find a template named with the format _model_name_confirm_delete.html
(again, you can change the suffix using template_name_suffix
in your view). Create the template file locallibrary/catalog/templates/catalog/author_confirm_delete.html
and copy the text below.
{% extends "base_generic.html" %}
{% block content %}
<h1>Delete Author</h1>
<p>Are you sure you want to delete the author: {{ author }}?</p>
<form action="" method="POST">
{% csrf_token %}
<input type="submit" value="Yes, delete." />
</form>
{% endblock %}
URL configurations
Open your URL configuration file (locallibrary/catalog/urls.py) and add the following configuration to the bottom of the file:
urlpatterns += [
path('author/create/', views.AuthorCreate.as_view(), name='author-create'),
path('author/<int:pk>/update/', views.AuthorUpdate.as_view(), name='author-update'),
path('author/<int:pk>/delete/', views.AuthorDelete.as_view(), name='author-delete'),
]
There is nothing particularly new here! You can see that the views are classes, and must hence be called via .as_view()
, and you should be able to recognize the URL patterns in each case. We must use pk
as the name for our captured primary key value, as this is the parameter name expected by the view classes.
The author create, update, and delete pages are now ready to test (we won’t bother hooking them into the site sidebar in this case, although you can do so if you wish).
Note: Observant users will have noticed that we didn’t do anything to prevent unauthorized users from accessing the pages! We leave that as an exercise for you (hint: you could use the PermissionRequiredMixin
and either create a new permission or reuse our can_mark_returned
permission).
Testing the page
First, log in to the site with an account that has whatever permissions you decided are needed to access the author editing pages.
Then navigate to the author create page, http://127.0.0.1:8000/catalog/author/create/
, which should look like the screenshot below.
Enter values for the fields and then press Submit to save the author record. You should now be taken to a detail view for your new author, with a URL of something like http://127.0.0.1:8000/catalog/author/10
.
You can test editing records by appending /update/ to the end of the detail view URL (e.g. http://127.0.0.1:8000/catalog/author/10/update/
) — we don’t show a screenshot because it looks just like the «create» page!
Finally, we can delete the page by appending delete to the end of the author detail-view URL (e.g. http://127.0.0.1:8000/catalog/author/10/delete/
). Django should display the delete page shown below. Press «Yes, delete.» to remove the record and be taken to the list of all authors.
Challenge yourself
Create some forms to create, edit, and delete Book
records. You can use exactly the same structure as for Authors
. If your book_form.html template is just a copy-renamed version of the author_form.html template, then the new «create book» page will look like the screenshot below:
Summary
Creating and handling forms can be a complicated process! Django makes it much easier by providing programmatic mechanisms to declare, render, and validate forms. Furthermore, Django provides generic form editing views that can do almost all the work to define pages that can create, edit, and delete records associated with a single model instance.
There is a lot more that can be done with forms (check out our See also list below), but you should now understand how to add basic forms and form-handling code to your own websites.
See also
In this module
source |
---|
exceptions.py |
Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.
— Doug Hellmann, Python Exception Handling Techniques
Exception handling in REST framework views
REST framework’s views handle various exceptions, and deal with returning appropriate error responses.
The handled exceptions are:
- Subclasses of
APIException
raised inside REST framework. - Django’s
Http404
exception. - Django’s
PermissionDenied
exception.
In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error.
Most error responses will include a key detail
in the body of the response.
For example, the following request:
DELETE http://api.example.com/foo/bar HTTP/1.1
Accept: application/json
Might receive an error response indicating that the DELETE
method is not allowed on that resource:
HTTP/1.1 405 Method Not Allowed
Content-Type: application/json
Content-Length: 42
{"detail": "Method 'DELETE' not allowed."}
Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the «non_field_errors» key, or whatever string value has been set for the NON_FIELD_ERRORS_KEY
setting.
An example validation error might look like this:
HTTP/1.1 400 Bad Request
Content-Type: application/json
Content-Length: 94
{"amount": ["A valid integer is required."], "description": ["This field may not be blank."]}
Custom exception handling
You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API.
The function must take a pair of arguments, the first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a Response
object, or return None
if the exception cannot be handled. If the handler returns None
then the exception will be re-raised and Django will return a standard HTTP 500 ‘server error’ response.
For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so:
HTTP/1.1 405 Method Not Allowed
Content-Type: application/json
Content-Length: 62
{"status_code": 405, "detail": "Method 'DELETE' not allowed."}
In order to alter the style of the response, you could write the following custom exception handler:
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if response is not None:
response.data['status_code'] = response.status_code
return response
The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as context['view']
.
The exception handler must also be configured in your settings, using the EXCEPTION_HANDLER
setting key. For example:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
If not specified, the 'EXCEPTION_HANDLER'
setting defaults to the standard exception handler provided by REST framework:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}
Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST
responses that are returned by the generic views when serializer validation fails.
API Reference
APIException
Signature: APIException()
The base class for all exceptions raised inside an APIView
class or @api_view
.
To provide a custom exception, subclass APIException
and set the .status_code
, .default_detail
, and default_code
attributes on the class.
For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the «503 Service Unavailable» HTTP response code. You could do this like so:
from rest_framework.exceptions import APIException
class ServiceUnavailable(APIException):
status_code = 503
default_detail = 'Service temporarily unavailable, try again later.'
default_code = 'service_unavailable'
Inspecting API exceptions
There are a number of different properties available for inspecting the status
of an API exception. You can use these to build custom exception handling
for your project.
The available attributes and methods are:
.detail
— Return the textual description of the error..get_codes()
— Return the code identifier of the error..get_full_details()
— Return both the textual description and the code identifier.
In most cases the error detail will be a simple item:
>>> print(exc.detail)
You do not have permission to perform this action.
>>> print(exc.get_codes())
permission_denied
>>> print(exc.get_full_details())
{'message':'You do not have permission to perform this action.','code':'permission_denied'}
In the case of validation errors the error detail will be either a list or
dictionary of items:
>>> print(exc.detail)
{"name":"This field is required.","age":"A valid integer is required."}
>>> print(exc.get_codes())
{"name":"required","age":"invalid"}
>>> print(exc.get_full_details())
{"name":{"message":"This field is required.","code":"required"},"age":{"message":"A valid integer is required.","code":"invalid"}}
ParseError
Signature: ParseError(detail=None, code=None)
Raised if the request contains malformed data when accessing request.data
.
By default this exception results in a response with the HTTP status code «400 Bad Request».
AuthenticationFailed
Signature: AuthenticationFailed(detail=None, code=None)
Raised when an incoming request includes incorrect authentication.
By default this exception results in a response with the HTTP status code «401 Unauthenticated», but it may also result in a «403 Forbidden» response, depending on the authentication scheme in use. See the authentication documentation for more details.
NotAuthenticated
Signature: NotAuthenticated(detail=None, code=None)
Raised when an unauthenticated request fails the permission checks.
By default this exception results in a response with the HTTP status code «401 Unauthenticated», but it may also result in a «403 Forbidden» response, depending on the authentication scheme in use. See the authentication documentation for more details.
PermissionDenied
Signature: PermissionDenied(detail=None, code=None)
Raised when an authenticated request fails the permission checks.
By default this exception results in a response with the HTTP status code «403 Forbidden».
NotFound
Signature: NotFound(detail=None, code=None)
Raised when a resource does not exists at the given URL. This exception is equivalent to the standard Http404
Django exception.
By default this exception results in a response with the HTTP status code «404 Not Found».
MethodNotAllowed
Signature: MethodNotAllowed(method, detail=None, code=None)
Raised when an incoming request occurs that does not map to a handler method on the view.
By default this exception results in a response with the HTTP status code «405 Method Not Allowed».
NotAcceptable
Signature: NotAcceptable(detail=None, code=None)
Raised when an incoming request occurs with an Accept
header that cannot be satisfied by any of the available renderers.
By default this exception results in a response with the HTTP status code «406 Not Acceptable».
UnsupportedMediaType
Signature: UnsupportedMediaType(media_type, detail=None, code=None)
Raised if there are no parsers that can handle the content type of the request data when accessing request.data
.
By default this exception results in a response with the HTTP status code «415 Unsupported Media Type».
Throttled
Signature: Throttled(wait=None, detail=None, code=None)
Raised when an incoming request fails the throttling checks.
By default this exception results in a response with the HTTP status code «429 Too Many Requests».
ValidationError
Signature: ValidationError(detail=None, code=None)
The ValidationError
exception is slightly different from the other APIException
classes:
- The
detail
argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in thevalidate()
method of a serializer. For example.raise serializers.ValidationError({'name': 'Please enter a valid name.'})
- By convention you should import the serializers module and use a fully qualified
ValidationError
style, in order to differentiate it from Django’s built-in validation error. For example.raise serializers.ValidationError('This field must be an integer value.')
The ValidationError
class should be used for serializer and field validation, and by validator classes. It is also raised when calling serializer.is_valid
with the raise_exception
keyword argument:
serializer.is_valid(raise_exception=True)
The generic views use the raise_exception=True
flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.
By default this exception results in a response with the HTTP status code «400 Bad Request».
Generic Error Views
Django REST Framework provides two error views suitable for providing generic JSON 500
Server Error and
400
Bad Request responses. (Django’s default error views provide HTML responses, which may not be appropriate for an
API-only application.)
Use these as per Django’s Customizing error views documentation.
rest_framework.exceptions.server_error
Returns a response with status code 500
and application/json
content type.
Set as handler500
:
handler500 = 'rest_framework.exceptions.server_error'
rest_framework.exceptions.bad_request
Returns a response with status code 400
and application/json
content type.
Set as handler400
:
handler400 = 'rest_framework.exceptions.bad_request'
Third party packages
The following third-party packages are also available.
DRF Standardized Errors
The drf-standardized-errors package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.