Django forms error class

The web framework for perfectionists with deadlines.

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 ValidationErrors 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 CharFields 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"> and EmailField 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 the ContactForm 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 its id. Its id, in turn, is
    generated by prepending 'id_' to the field name. The id
    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 as checked rather than the XHTML style
    of checked='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 by Form.get_context()
  • renderer: Value returned by Form.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 where initlist 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 default errorlist class.

renderer

New in Django 4.0.

Specifies the renderer to use for ErrorList.
Defaults to None which means to use the default renderer
specified by the FORM_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 by error_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 by template_name
  • context: Value returned by get_context()
  • renderer: Value returned by renderer
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 the template_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
if Form.auto_id is False.

BoundField.data

This property returns the data for this BoundField
extracted by the widget’s value_from_datadict()
method, or None 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
this BoundField wraps.

BoundField.form

The Form instance this BoundField
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 form prefix 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 from Form.initial if present, otherwise
trying Field.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 or uuid.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 this BoundField’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
trailing input or widget 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 to as_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 as attrs. 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 the BoundField.
  • contents: By default a concatenated string of
    BoundField.label and Form.label_suffix (or
    Field.label_suffix, if set). This can be overridden by the
    contents and label_suffix arguments.
  • attrs: A dict containing for,
    Form.required_css_class, and id. id is generated by the
    field’s widget attrs or BoundField.auto_id. Additional
    attributes can be provided by the attrs argument.
  • use_tag: A boolean which is True if the label has an id.
    If False the default template omits the tag.
  • tag: An optional string to customize the tag, defaults to label.

Tip

In your template field is the instance of the BoundField.
Therefore field.field accesses BoundField.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
the Form.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() with tag='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 a Widget:

>>> 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 there a way to give a form a special error rendering function in the form definition? In the docs under customizing-the-error-list-format it shows how you can give a form a special error rendering function, but it seems like you have to declare it when you instantiate the form, not when you define it.

So you can define some ErrorList class like:

from django.forms.util import ErrorList
 class DivErrorList(ErrorList):
     def __unicode__(self):
         return self.as_divs()
     def as_divs(self):
         if not self: return u''
         return u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' % e for e in self])

And then when you instantiate your form you can instantiate it with that error_class:

 f = ContactForm(data, auto_id=False, error_class=DivErrorList)
 f.as_p()

<div class="errorlist"><div class="error">This field is required.</div></div>
<p>Subject: <input type="text" name="subject" maxlength="100" /></p>
<p>Message: <input type="text" name="message" value="Hi there" /></p>
<div class="errorlist"><div class="error">Enter a valid e-mail address.</div></div>
<p>Sender: <input type="text" name="sender" value="invalid e-mail address" /></p>
<p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>

But I don’t want to name the error class every time I instantiate a form, is there a way to just define the custom error renderer inside the form definition?

API форм¶

Заполненные и незаполненные формы¶

Экземпляр класса Form может быть заполнен набором данных или не заполнен.

  • Если он заполнен, то у него есть возможность валидации полученных данных и генерации заполненной формы в виде HTML кода.

  • Если он не заполнен, то выполнить валидацию невозможно (так как нет для этого данных!), но есть возможность сгенерировать HTML код пустой формы.

class Form¶

Для создания незаполненного экземпляра Form, просто создайте объект:

Для привязки данных к форме, передайте данные в виде словаря в качестве первого параметра конструктора класса Form:

>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data)

В этом словаре, ключами являются имена полей, которые соответствуют атрибутам в вашем классе Form. Значения словаря являются данными, которые вам требуется проверить. Обычно значения представлены строками, но это требование не является обязательным. Тип переданных данных зависит от класса Field, это мы сейчас рассмотрим.

Form.is_bound¶

Если вам требуется определять заполненность экземпляров форм во время работы программы, обратитесь к значению атрибута формы is_bound:

>>> f = ContactForm()
>>> f.is_bound
False
>>> f = ContactForm({'subject': 'hello'})
>>> f.is_bound
True

Следует отметить, что передача форме пустого словаря создаёт заполненную форму без данных:

>>> f = ContactForm({})
>>> f.is_bound
True

Если есть заполненный экземпляр Form и требуется как-то изменить его данные или если требуется привязать данные к незаполненному экземпляру Form, то создаёте другой экземпляр Form. Нет способа изменить данные в экземпляре Form. После создания экземпляра Form, его данные следует рассматривать как неизменные, независимо от его заполненности.

Использование форм для проверки данных¶

Form.clean()¶

Добавьте метод clean() в вашу форму Form, если необходимо проверить независимые поля вместе. Смотрите Очистка и проверка полей, которые зависят друг от друга.

Form.is_valid()¶

Главной задачей объекта Form является проверка данных. У заполненного экземпляра Form вызовите метод is_valid() для выполнения проверки и получения её результата:

>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
True

Начнём с неправильных данных. В этом случае поле subject будет пустым (ошибка, так как по умолчанию все поля должны быть заполнены), а поле sender содержит неправильный адрес электронной почты:

>>> data = {'subject': '',
...         'message': 'Hi there',
...         'sender': 'invalid email address',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
False
Form.errors¶

Обратитесь к атрибуту errors для получения словаря с сообщениями об ошибках:

>>> f.errors
{'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}

В этом словаре, ключами являются имена полей, а значениями – списки юникодных строк, представляющих сообщения об ошибках. Сообщения хранятся в виде списков, так как поле может иметь множество таких сообщений.

Обращаться к атрибуту errors можно без предварительного вызова методе call is_valid(). Данные формы будут проверены при вызове метода is_valid() или при обращении к errors.

Процедуры проверки выполняются один раз, независимо от количества обращений к атрибуту errors или вызова метода is_valid(). Это означает, что если проверка данных имеет побочное влияние на состояние формы, то оно проявится только один раз.

Form.errors.as_data()¶

Возвращает dict, который содержит поля и объекты ValidationError.

>>> f.errors.as_data()
{'sender': [ValidationError(['Enter a valid email address.'])],
'subject': [ValidationError(['This field is required.'])]}

Используйте этот метод, если вам необходимо определить тип ошибки по её code. Это позволяет переопределить сообщение об ошибке, или добавить дополнительную логику обработки некоторых ошибок. Также позволяет преобразовать ошибки в другой формат (например, XML). Например, as_json() использует as_data().

Метод as_data() добавлен для обратной совместимости. В предыдущих версиях объекты ValidationError терялись при получении сообщения с ошибкой и добавления его в словарь Form.errors. В идеале Form.errors должен содержать объекты ValidationError и метод с префиксом as_ должен преобразовать их в текстовые сообщения, но нам пришлось пойти другим путем, чтобы не сломать существующий код, который ожидает получить сообщения с ошибками из Form.errors.

Form.errors.as_json(escape_html=False

Возвращает ошибки в JSON формате.

>>> f.errors.as_json()
{"sender": [{"message": "Enter a valid email address.", "code": "invalid"}],
"subject": [{"message": "This field is required.", "code": "required"}]}

По умолчанию, as_json() не экранирует результат. Если вы используете, например, AJAX запросы для отправки формы, и показываете ошибки на странице, вам следует экранировать результат на клиенте, чтобы избежать XSS атак. Это просто сделать, используя JavaScript библиотеку, например, jQuery – просто используйте $(el).text(errorText) вместо .html().

Если вы не хотите использовать экранирование на стороне клиента, можете передать аргумент escape_html=True и все ошибки будет экранированы, теперь их можно вставлять непосредственно в HTML.

Form.add_error(field, error

Этот метод позволяет добавить ошибки конкретному полю в методе Form.clean(), или вне формы. Например, из представления.

Аргумент field указывает поле, для которого необходимо добавить ошибку. Если равен None, ошибка будет добавлена к общим ошибкам формы, которые можно получить через метод Form.non_field_errors().

Аргумент error может быть просто строкой, но лучше передавать объект ValidationError. Смотрите Вызов ValidationError.

Обратите внимание, Form.add_error() автоматически удалит поле из cleaned_data.

Form.has_error(field, code=None

Добавлено в Django 1.8.

Этот метод возвращает True, если поле содержит ошибку с кодом code. Если code равен None, вернет True, если поле содержит любую ошибку.

Чтобы проверить наличие ошибок, которые не относятся ни к одному из полей, передайте NON_FIELD_ERRORS в параметре field.

Form.non_field_errors()¶

Этот метод возвращает список ошибок из Form.errors, которые не привязаны к конкретному полю. Сюда входят ошибки ValidationError, вызванные в Form.clean(), и ошибки, добавленные через Form.add_error(None, «…»).

Поведение незаполненных форм¶

Бессмысленно проводить проверку незаполненной формы, но покажем, что происходит с такой формой:

>>> f = ContactForm()
>>> f.is_valid()
False
>>> f.errors
{}

Динамические начальные значения¶

Form.initial¶

Используйте атрибут initial для определения начальных значений полей формы во время работы приложения. Например, вам может потребоваться заполнить поле username именем текущего пользователя.

Для этого следует использовать аргумент initial конструктора класса Form. Этот аргумент, если он передан, должен содержать словарь, связывающий имена полей с их значениями. Указывайте в словаре только те поля, значения которых вы желаете определить. Например:

>>> f = ContactForm(initial={'subject': 'Hi there!'})

Эти значения только отображаются на незаполненных формах, они не будут доступны пока форма не будет отправлена пользователем.

Следует отметить, что если класс Field определяет атрибут initial и вы используете аргумент initial при создании экземпляра Form, то последний initial будет иметь преимущество. В этом примере, initial указан на уровнях поля и экземпляра формы, и последний будет иметь преимущество:

>>> 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" /></td></tr>
<tr><th>Url:</th><td><input type="url" name="url" /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>

Проверяем какие данные формы были изменены¶

Form.has_changed()¶

Используйте метод has_changed(), если необходимо проверить были ли изначальные данные изменены.

>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data, initial=data)
>>> f.has_changed()
False

После отправки формы, мы создаем ее, предоставляя изначальные данные, и теперь может проверить изменились ли они:

>>> f = ContactForm(request.POST, initial=data)
>>> f.has_changed()

has_changed() вернет True, если данные из request.POST отличаются от данных из initial, иначе вернет False. Результат вычисляется путем вызова Field.has_changed() для каждого поля формы.

Form.changed_data¶

Атрибут changed_data возвращает список полей, чии значения из переданных данных (обычно request.POST) отличаются от значений из initial. Возвращает пустой список, если данные не поменялись.

>>> f = ContactForm(request.POST, initial=data)
>>> if f.has_changed():
...     print("The following fields changed: %s" % ", ".join(f.changed_data))

Обращение к полям из формы¶

Form.fields¶

Вы можете обращаться к полям объекта Form, используя атрибут fields:

>>> 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>

Вы можете изменить поле:

>>> f.as_table().split('n')[0]
'<tr><th>Name:</th><td><input name="name" type="text" value="instance" /></td></tr>'
>>> f.fields['name'].label = "Username"
>>> f.as_table().split('n')[0]
'<tr><th>Username:</th><td><input name="name" type="text" value="instance" /></td></tr>'

Будьте осторожны, не изменяйте атрибут base_fields т.к. эти изменения повлияют на все экземпляры ContactForm в текущем процессе Python:

>>> f.base_fields['name'].label = "Username"
>>> another_f = CommentForm(auto_id=False)
>>> another_f.as_table().split('n')[0]
'<tr><th>Username:</th><td><input name="name" type="text" value="class" /></td></tr>'

Доступ к “чистым” данным¶

Form.cleaned_data¶

Каждое поле в классе Form отвечает не только за проверку, но и за нормализацию данных. Это приятная особенность, так как она позволяет вводить данные в определённые поля различными способами, всегда получая правильный результат.

Например, класс DateField нормализует введённое значение к объекту datetime.date. Независимо от того, передали ли вы строку в формате ‘1994-07-15’, объект datetime.date или число в других форматах, DateField всегда преобразует его в объект datetime.date, если при этом не произойдёт ошибка.

После создания экземпляра Form, привязки данных и их проверки, вы можете обращаться к “чистым” данным через атрибут cleaned_data:

>>> 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'}

Следует отметить, что любое текстовое поле, такое как CharField или EmailField, всегда преобразует текст в юникодную строку. Мы рассмотрим применения кодировок далее.

Если данные не прошли проверку, то атрибут cleaned_data будет содержать только значения тех полей, что прошли проверку:

>>> 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 всегда содержит только данные для полей, определённых в классе Form, даже если вы передали дополнительные данные при определении Form. В этом примере, мы передаём набор дополнительных полей в конструктор ContactForm, но cleaned_data содержит только поля формы:

>>> 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'}

Если Form прошла проверку, то cleaned_data будет содержать ключ и значение для всех полей формы, даже если данные не включают в себя значение для некоторых необязательных полей. В данном примере, словарь данных не содержит значение для поля nick_name, но cleaned_data содержит пустое значение для него:

>>> from django.forms import Form
>>> class OptionalPersonForm(Form):
...     first_name = CharField()
...     last_name = CharField()
...     nick_name = 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'}

В приведённом выше примере, значением атрибута cleaned_data для поля nick_name является пустая строка, так как nick_name – это CharField, а CharField рассматривает пустые значения как пустые строки. Каждый тип поля знает, что такое “пустое” значение, т.е. для DateField – это None, на не пустая строка. Для получения подробностей о поведении каждого типа поля обращайте внимание на заметку “Пустое значение” для каждого поля в разделе “Встроенные поля”, которые приведён далее.

Вы можете написать код для выполнения проверки определённых полей формы (используя их имена) или для проверки всей формы (рассматривая её как комбинацию полей). Подробная информация изложена в Проверка форм и полей формы.

Выдача формы в виде HTML¶

Второй задачей объекта Form является представление себя в виде HTML кода. Для этого объект надо просто “распечатать”:

>>> f = ContactForm()
>>> print(f)
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></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>

Если форма заполнена данными, то полученный HTML код будет включать себя эти данные. Например, если поле представлено тегом <input type=»text»>, то его данные будут подставлены в атрибут value. Если поле представлено тегом <input type=»checkbox»>, то HTML код будет содержать checked=»checked»:

>>> 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" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" value="foo@example.com" /></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="checked" /></td></tr>

По умолчанию в HTML форма представляется в виде таблицы, т.е. каждое поле обёрнуто в <tr>. Обратите внимание на:

  • Для гибкости, выводимый код не включает в себя ни теги <table> и </table>, ни теги <form> and </form>, ни тег <input type=»submit»>. Не забывайте их добавлять.

  • Каждый тип поля имеет стандартное HTML представление. Тип CharField«представлен как «<input type=»text»>, а EmailField как <input type=»email»>. Тип BooleanField представлен <input type=»checkbox»>. Следует отметить, что эти представления достаточно гибкие, так как вы можете влиять на них, указав для поля виджет. Далее мы покажем как это делается.

  • Атрибут name каждого тега совпадает напрямую с именем атрибута в классе ContactForm.

  • Текстовая метка каждого поля, т.е. ‘Subject:’, ‘Message:’ и ‘Cc myself:’, генерируется из имени поля, конвертируя символы подчёркивания в пробелы и переводя первый символ в верхний регистр. Также, вы можете явно назначить текстовую метку для поля.

  • Каждая текстовая метка выводится с помощью тега <label>, который указывает на соответствующее поле формы с помощью атрибута id. Атрибут id генерируется путём добавления префикса ‘id_’ к имени поля. Атрибуты id и теги <label> включаются в HTML представление формы по умолчанию, но можете изменить такое поведение формы.

Несмотря на то, что по умолчанию форма выводится в табличном виде, существует ряд других представлений. Каждое представление доступно через метод объекта формы, возвращая объект Unicode.

as_p()

Form.as_p()¶

Метод as_p() представляет форму в виде последовательности тегов <p>, по одному на каждое поле:

>>> f = ContactForm()
>>> f.as_p()
'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></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" /></p>
<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>
<p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></p>
<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>

as_ul()

Form.as_ul()¶

Метод as_ul() представляет форму в виде последовательности тегов <li>, по одному на каждое поле. Представление не включает в себя теги <ul> или </ul>, таким образом вы можете указать любой атрибут для тега <ul>:

>>> f = ContactForm()
>>> f.as_ul()
'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></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" /></li>
<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>
<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></li>
<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>

as_table()

Form.as_table()¶

Наконец, метод as_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" /></td></tr>n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></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.as_table())
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></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>

Стилизация обязательных полей или полей с ошибкой¶

Form.error_css_class¶
Form.required_css_class¶

Стилизация полей формы, обязательных для заполнения или имеющих ошибку, является общей практикой. Например, вы можете выделять обязательные поля жирным шрифтом, а поля с ошибкой выводить на красном.

Класс Form имеет ряд возможностей, которые вы можете использовать для добавления атрибутов class к обязательным полям и полям с ошибками: просто определите атрибут Form.error_css_class и/или Form.required_css_class attributes:

from django.forms import Form

class ContactForm(Form):
    error_css_class = 'error'
    required_css_class = 'required'

    # ... and the rest of your fields here

После этого к полям будут добавлены классы «error» и/или «required». В результате HTML код будет выглядеть таким образом:

>>> 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'].label_tag(attrs={'class': 'foo'})
<label for="id_subject" class="foo required">Subject:</label>

Изменено в Django 1.8:

required_css_class будет также добавлен к тегу <label>, как это показано выше.

Порядок полей¶

При использовании методов as_p(), as_ul() и as_table() поля отображаются в порядке их определения в классе формы. Например, в нашей форме ContactForm поля определены в порядке subject, message, sender, cc_myself. Для изменения их порядка на форме, просто поменяйте их местами в классе.

Есть и другие способы переопределить порядок полей в форме:

Form.field_order¶

Добавлено в Django 1.9.

По умолчанию Form.field_order=None, при этом поля формы будут в порядке их определения. Если field_order содержит список названий полей формы, поля будут выведены в указанном порядке, а оставшиеся – в порядке по умолчанию. Неизвестные названия полей будут проигнорированы. Это позволяете удалить поле в классе-наследние, установив его в None, и при это вам не нужно переопределять field_order.

Также можно передать аргумент Form.field_order в Form, чтобы переопределить порядок полей. Если Form содержит field_order и и передать аргумент field_order при создании Form, будет использоваться последний field_order.

Form.order_fields(field_order

Добавлено в Django 1.9.

Вы можете изменить порядок полей, используя метод order_fields() и передав в него список полей, как и для field_order.

Отображение ошибок¶

При отображении заполненного объекта Form, процесс генерации HTML кода автоматически выполняет проверку данных формы, если она ещё не была произведена. Если проверка выявила ошибки, то HTML код формы будет включать в себя список ошибок в виде списка <ul class=»errorlist»> у соответствующего поля. Точная позиция списка сообщений с ошибками проверки зависит от метода, который вы используете:

>>> data = {'subject': '',
...         'message': 'Hi there',
...         'sender': 'invalid email address',
...         'cc_myself': True}
>>> f = ContactForm(data, auto_id=False)
>>> 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" /></td></tr>
<tr><th>Message:</th><td><input type="text" name="message" value="Hi there" /></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" /></td></tr>
<tr><th>Cc myself:</th><td><input checked="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" /></li>
<li>Message: <input type="text" name="message" value="Hi there" /></li>
<li><ul class="errorlist"><li>Enter a valid email address.</li></ul>Sender: <input type="email" name="sender" value="invalid email address" /></li>
<li>Cc myself: <input checked="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" /></p>
<p>Message: <input type="text" name="message" value="Hi there" /></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" /></p>
<p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>

Настройка формата списка ошибок¶

По умолчанию, формы используют django.forms.utils.ErrorList для форматирования списка с ошибками . Если вам требуется использовать другой класс для отображения ошибок, вы можете передать его во время создания объекта формы (замените __str__ на __unicode__ для Python 2):

>>> from django.forms.utils import ErrorList
>>> class DivErrorList(ErrorList):
...     def __str__(self):              # __unicode__ on Python 2
...         return self.as_divs()
...     def as_divs(self):
...         if not self: return ''
...         return '<div class="errorlist">%s</div>' % ''.join(['<div class="error">%s</div>' % e for e in self])
>>> f = ContactForm(data, auto_id=False, error_class=DivErrorList)
>>> f.as_p()
<div class="errorlist"><div class="error">This field is required.</div></div>
<p>Subject: <input type="text" name="subject" maxlength="100" /></p>
<p>Message: <input type="text" name="message" value="Hi there" /></p>
<div class="errorlist"><div class="error">Enter a valid email address.</div></div>
<p>Sender: <input type="email" name="sender" value="invalid email address" /></p>
<p>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></p>

Точное управление выводом¶

Методы as_p(), as_ul() и as_table() являются упрошенными методами отображения формы. Это не единственные способы отображения формы.

class BoundField¶

Используется для отображения HTML или для доступа к атрибутам отдельного поля экземпляра Form.

Метод __str__() (__unicode__ в Python 2) этого объекта возвращают HTML для данного поля.

Для получение одного BoundField используйте синтаксис поиска в словаре, применяя имя поля в качестве ключа:

>>> form = ContactForm()
>>> print(form['subject'])
<input id="id_subject" type="text" name="subject" maxlength="100" />

Для получения всех объектов BoundField, пройдите циклом по форме:

>>> form = ContactForm()
>>> for boundfield in form: print(boundfield)
<input id="id_subject" type="text" name="subject" maxlength="100" />
<input type="text" name="message" id="id_message" />
<input type="email" name="sender" id="id_sender" />
<input type="checkbox" name="cc_myself" id="id_cc_myself" />

Вывод указанного поля соответствует настройке auto_id:

>>> f = ContactForm(auto_id=False)
>>> print(f['message'])
<input type="text" name="message" />
>>> f = ContactForm(auto_id='id_%s')
>>> print(f['message'])
<input type="text" name="message" id="id_message" />

Атрибуты BoundField

BoundField.data¶

Это свойство возвращает данные для текущего BoundField, полученные из метода value_from_datadict() виджета, или None, если данные отсутствуют:

>>> 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¶

Объект со свойствами списка, который при отображении представляется в виде <ul class=»errorlist»>:

>>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
>>> f = ContactForm(data, auto_id=False)
>>> print(f['message'])
<input type="text" name="message" />
>>> 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¶

Экземпляр Field из класса формы, который оборачивает текущий BoundField.

BoundField.form¶

Экземпляр Form, к которому привязан текущий BoundField.

BoundField.help_text¶

help_text поля.

BoundField.html_name¶

Название, которое будет использоваться в HTML атрибуте name виджета. Учитывает prefix формы.

BoundField.id_for_label¶

Этот атрибут рендерит ID поля. Например, вы можете использовать его, если вы самостоятельно создаете <label> для поля (несмотря на то, что label_tag() делает это для вас):

<label for="{{ form.my_field.id_for_label }}">...</label>{{ my_field }}

По умолчанию, он равен названию поля с префиксом id_ (“id_my_field” для примера выше). Вы можете изменить ID, передав его в параметре attrs виджета. Например, определив поле следующим образом:

my_field = forms.CharField(widget=forms.TextInput(attrs={'id': 'myFIELD'}))

и используя пример выше, получите следующий результат:

<label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" />
BoundField.is_hidden¶

Возвращает True, если виджет BoundField‘ скрыт.

BoundField.label¶

label поля. Используется в label_tag().

BoundField.name¶

Название текущего поля в форме:

>>> f = ContactForm()
>>> print(f['subject'].name)
subject
>>> print(f['message'].name)
message

Методы BoundField

BoundField.as_hidden(attrs=None, **kwargs

Возвращает HTML строку, которая представляет текущее поля как <input type=»hidden»>.

**kwargs передается в as_widget().

Этот метод в основном используется внутренним кодом. Вам следует использовать виджет вместо него.

BoundField.as_widget(widget=None, attrs=None, only_initial=False

Рендерит поле, используя переданный виджет, добавляете HTML атрибуты из attrs. Если виджет не указан, будет использоваться виджет по умолчанию поля.

only_initial используется Django и не должен указываться явно.

BoundField.css_classes()¶

Когда вы применяете общие методы для отображения формы, для выделения обязательных полей формы или полей, которые содержат ошибки, используются CSS классы. Если вы вручную выводите форму, вы можете получить доступ к этим классам через метод css_classes:

>>> f = ContactForm(data={'message': ''})
>>> f['message'].css_classes()
'required'

Если потребуется предоставить дополнительные классы для ошибок и обязательных полей, вы можете указать эти классы в качестве аргумента:

>>> f = ContactForm(data={'message': ''})
>>> f['message'].css_classes('foo bar')
'foo bar required'
BoundField.label_tag(contents=None, attrs=None, label_suffix=None

Чтобы отдельно отрендерить label поля, вызовите метод label_tag():

>>> f = ContactForm(data={'message': ''})
>>> print(f['message'].label_tag())
<label for="id_message">Message:</label>

Вы можете передать параметр contents, который заменит автоматически генерируемый тег <label>. Необязательный параметр attrs, который является словарем, может передавать дополнительные атрибуты для тега <label>.

Сгенерированный HTML содержит label_suffix формы (двоеточие по умолчанию), или label_suffix поля, если этот атрибут установлен. Необязательный аргумент label_suffix позволяет переопределить установленный ранее суфикс. Например, можно использовать пустую строку, чтобы скрыть метку поля. Если это необходимо сделать в шаблоне, создайте собственный фильтр, который позволяет передавать значение в label_tag.

Изменено в Django 1.8:

Метка поля содержит required_css_class, если поле обязательно.

BoundField.value()¶

Используйте этот метод для выдачи “сырого” значения данного поля, как будто бы оно было отображено через Widget:

>>> 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

Настройка BoundField

Добавлено в Django 1.9.

Если вам необходима дополнительная информация про поле формы в шаблоне, и наследоваться от Field не достаточно, вы можете переопределить BoundField.

В собственном поле формы можно переопределить метод get_bound_field():

Field.get_bound_field(form, field_name

Принимает экземпляр Form и название поля. Возвращаемое значение будет использоваться при доступе к полю в шаблоне. Обычно это экземпляр BoundField.

Например у вас есть поле GPSCoordinatesField, и вы хотите получать дополнительную информацию про координаты в шаблоне, это можно сделать следующим образом:

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)

Теперь вы можете получить страну в шаблоне через {{ form.coordinates.country }}.

Привязка загруженных файлов к форме¶

Работа с формами, которые содержат поля FileField и ImageField немного отличается от работы с обычными формами.

Сначала, для того, чтобы загружать файлы, вам потребуется назначить форме атрибут enctype:

<form enctype="multipart/form-data" method="post" action="/foo/">

Затем, при использовании формы следует привязывать данные к форме. Файлы обрабатываются отдельно от данных формы. Таким образом, если ваша форма содержит поля FileField и ImageField, потребуется указать второй аргумент у конструктора. Если мы добавим в нашу ContactForm поле ImageField с именем mugshot, придётся сделать следующее:

# 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)

На практике вы будете просто указывать request.FILES в качестве источника данных файлов аналогично тому, как вы указываете request.POST в качестве источника данных формы:

# Bound form with an image field, data from the request
>>> f = ContactFormWithMugshot(request.POST, request.FILES)

Создание незаполненной формы аналогично обычной форме – просто не указывайте никаких данных для неё:

# Unbound form with an image field
>>> f = ContactFormWithMugshot()

Определение таких форм¶

Form.is_multipart()¶

Если вы пишете представления и шаблоны в расчёте на их неоднократное использование в будущем, вы не можете знать, будет ли ваша форма обычной или будет работать с файлами. В этом случае вам поможет метод is_multipart(), который точно ответит на этот вопрос:

>>> f = ContactFormWithMugshot()
>>> f.is_multipart()
True

Покажем пример использования этого метода в шаблоне:

{% if form.is_multipart %}
    <form enctype="multipart/form-data" method="post" action="/foo/">
{% else %}
    <form method="post" action="/foo/">
{% endif %}
{{ form }}
</form>

Наследование форм¶

Если у вас есть несколько классов Form с одинаковыми полями, вы можете воспользоваться наследованием форм, чтобы убрать дублирование кода.

При наследовании определённого класса Form, результирующий класс будет обладать всеми полями родительского класса (-ов), включая поля, которые определены в нём самом.

В этом примере, ContactFormWithPriority содержит все поля из ContactForm, и собственное поле, priority. Поля ContactForm выводятся первыми:

>>> class ContactFormWithPriority(ContactForm):
...     priority = forms.CharField()
>>> f = ContactFormWithPriority(auto_id=False)
>>> print(f.as_ul())
<li>Subject: <input type="text" name="subject" maxlength="100" /></li>
<li>Message: <input type="text" name="message" /></li>
<li>Sender: <input type="email" name="sender" /></li>
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
<li>Priority: <input type="text" name="priority" /></li>

Также можно наследовать несколько форм, рассматривая формы как “смесь”(mixin). В этом примере форма BeatleForm наследует формы PersonForm и InstrumentForm (именно в этом порядке) и её список полей включает в себя поля из родительских классов:

>>> from django.forms import Form
>>> class PersonForm(Form):
...     first_name = CharField()
...     last_name = CharField()
>>> class InstrumentForm(Form):
...     instrument = CharField()
>>> class BeatleForm(PersonForm, InstrumentForm):
...     haircut_type = CharField()
>>> b = BeatleForm(auto_id=False)
>>> print(b.as_ul())
<li>First name: <input type="text" name="first_name" /></li>
<li>Last name: <input type="text" name="last_name" /></li>
<li>Instrument: <input type="text" name="instrument" /></li>
<li>Haircut type: <input type="text" name="haircut_type" /></li>

Добавлена возможность декларативно удалить Field, унаследованное от родительского класса, указав None. Например:

>>> from django import forms

>>> class ParentForm(forms.Form):
...     name = forms.CharField()
...     age = forms.IntegerField()

>>> class ChildForm(ParentForm):
...     name = None

>>> ChildForm().fields.keys()
... ['age']

Префиксы для форм¶

Form.prefix¶

Вы можете размещать несколько форм в одном теге <form>. Для размещения каждой формы в собственном пространстве имён следует использовать именованный аргумент prefix:

>>> mother = PersonForm(prefix="mother")
>>> father = PersonForm(prefix="father")
>>> print(mother.as_ul())
<li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" /></li>
<li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" /></li>
>>> print(father.as_ul())
<li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" /></li>
<li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" /></li>

Префикс также можно указать в классе формы:

>>> class PersonForm(forms.Form):
...     ...
...     prefix = 'person'

Добавлено в Django 1.9:

Была добавлена возможность определить prefix в классе формы.

«»» Form classes «»» import copy import datetime from django.core.exceptions import NON_FIELD_ERRORS, ValidationError from django.forms.fields import Field, FileField from django.forms.utils import ErrorDict, ErrorList, RenderableFormMixin from django.forms.widgets import Media, MediaDefiningClass from django.utils.datastructures import MultiValueDict from django.utils.functional import cached_property from django.utils.translation import gettext as _ from .renderers import get_default_renderer __all__ = («BaseForm», «Form») class DeclarativeFieldsMetaclass(MediaDefiningClass): «»»Collect Fields declared on the base classes.»»» def __new__(mcs, name, bases, attrs): # Collect fields from current class and remove them from attrs. attrs[«declared_fields»] = { key: attrs.pop(key) for key, value in list(attrs.items()) if isinstance(value, Field) } new_class = super().__new__(mcs, name, bases, attrs) # Walk through the MRO. declared_fields = {} for base in reversed(new_class.__mro__): # Collect fields from base class. if hasattr(base, «declared_fields»): declared_fields.update(base.declared_fields) # Field shadowing. for attr, value in base.__dict__.items(): if value is None and attr in declared_fields: declared_fields.pop(attr) new_class.base_fields = declared_fields new_class.declared_fields = declared_fields return new_class class BaseForm(RenderableFormMixin): «»» The main implementation of all the Form logic. Note that this class is different than Form. See the comments by the Form class for more info. Any improvements to the form API should be made to this class, not to the Form class. «»» default_renderer = None field_order = None prefix = None use_required_attribute = True template_name_div = «django/forms/div.html» template_name_p = «django/forms/p.html» template_name_table = «django/forms/table.html» template_name_ul = «django/forms/ul.html» template_name_label = «django/forms/label.html» def __init__( self, data=None, files=None, auto_id=«id_%s», prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None, ): self.is_bound = data is not None or files is not None self.data = MultiValueDict() if data is None else data self.files = MultiValueDict() if files is None else files self.auto_id = auto_id if prefix is not None: self.prefix = prefix self.initial = initial or {} self.error_class = error_class # Translators: This is the default suffix added to form field labels self.label_suffix = label_suffix if label_suffix is not None else _(«:») self.empty_permitted = empty_permitted self._errors = None # Stores the errors after clean() has been called. # The base_fields class attribute is the *class-wide* definition of # fields. Because a particular *instance* of the class might want to # alter self.fields, we create self.fields here by copying base_fields. # Instances should always modify self.fields; they should not modify # self.base_fields. self.fields = copy.deepcopy(self.base_fields) self._bound_fields_cache = {} self.order_fields(self.field_order if field_order is None else field_order) if use_required_attribute is not None: self.use_required_attribute = use_required_attribute if self.empty_permitted and self.use_required_attribute: raise ValueError( «The empty_permitted and use_required_attribute arguments may « «not both be True.» ) # Initialize form renderer. Use a global default if not specified # either as an argument or as self.default_renderer. if renderer is None: if self.default_renderer is None: renderer = get_default_renderer() else: renderer = self.default_renderer if isinstance(self.default_renderer, type): renderer = renderer() self.renderer = renderer def order_fields(self, field_order): «»» Rearrange the fields according to field_order. field_order is a list of field names specifying the order. Append fields not included in the list in the default order for backward compatibility with subclasses not overriding field_order. If field_order is None, keep all fields in the order defined in the class. Ignore unknown fields in field_order to allow disabling fields in form subclasses without redefining ordering. «»» if field_order is None: return fields = {} for key in field_order: try: fields[key] = self.fields.pop(key) except KeyError: # ignore unknown fields pass fields.update(self.fields) # add remaining fields in original order self.fields = fields def __repr__(self): if self._errors is None: is_valid = «Unknown» else: is_valid = self.is_bound and not self._errors return «<%(cls)s bound=%(bound)s, valid=%(valid)s, fields=(%(fields)s)>» % { «cls»: self.__class__.__name__, «bound»: self.is_bound, «valid»: is_valid, «fields»: «;».join(self.fields), } def _bound_items(self): «»»Yield (name, bf) pairs, where bf is a BoundField object.»»» for name in self.fields: yield name, self[name] def __iter__(self): «»»Yield the form’s fields as BoundField objects.»»» for name in self.fields: yield self[name] def __getitem__(self, name): «»»Return a BoundField with the given name.»»» try: field = self.fields[name] except KeyError: raise KeyError( «Key ‘%s’ not found in ‘%s’. Choices are: %s.» % ( name, self.__class__.__name__, «, «.join(sorted(self.fields)), ) ) if name not in self._bound_fields_cache: self._bound_fields_cache[name] = field.get_bound_field(self, name) return self._bound_fields_cache[name] @property def errors(self): «»»Return an ErrorDict for the data provided for the form.»»» if self._errors is None: self.full_clean() return self._errors def is_valid(self): «»»Return True if the form has no errors, or False otherwise.»»» return self.is_bound and not self.errors def add_prefix(self, field_name): «»» Return the field name with a prefix appended, if this Form has a prefix set. Subclasses may wish to override. «»» return «%s-%s» % (self.prefix, field_name) if self.prefix else field_name def add_initial_prefix(self, field_name): «»»Add an ‘initial’ prefix for checking dynamic initial values.»»» return «initial-%s» % self.add_prefix(field_name) def _widget_data_value(self, widget, html_name): # value_from_datadict() gets the data from the data dictionaries. # Each widget type knows how to retrieve its own data, because some # widgets split data over several HTML fields. return widget.value_from_datadict(self.data, self.files, html_name) @property def template_name(self): return self.renderer.form_template_name def get_context(self): fields = [] hidden_fields = [] top_errors = self.non_field_errors().copy() for name, bf in self._bound_items(): bf_errors = self.error_class(bf.errors, renderer=self.renderer) if bf.is_hidden: if bf_errors: top_errors += [ _(«(Hidden field %(name)s) %(error)s») % {«name»: name, «error»: str(e)} for e in bf_errors ] hidden_fields.append(bf) else: errors_str = str(bf_errors) fields.append((bf, errors_str)) return { «form»: self, «fields»: fields, «hidden_fields»: hidden_fields, «errors»: top_errors, } def non_field_errors(self): «»» Return an ErrorList of errors that aren’t associated with a particular field — i.e., from Form.clean(). Return an empty ErrorList if there are none. «»» return self.errors.get( NON_FIELD_ERRORS, self.error_class(error_class=«nonfield», renderer=self.renderer), ) def add_error(self, field, error): «»» Update the content of `self._errors`. The `field` argument is the name of the field to which the errors should be added. If it’s None, treat the errors as NON_FIELD_ERRORS. The `error` argument can be a single error, a list of errors, or a dictionary that maps field names to lists of errors. An «error» can be either a simple string or an instance of ValidationError with its message attribute set and a «list or dictionary» can be an actual `list` or `dict` or an instance of ValidationError with its `error_list` or `error_dict` attribute set. If `error` is a dictionary, the `field` argument *must* be None and errors will be added to the fields that correspond to the keys of the dictionary. «»» if not isinstance(error, ValidationError): # Normalize to ValidationError and let its constructor # do the hard work of making sense of the input. error = ValidationError(error) if hasattr(error, «error_dict»): if field is not None: raise TypeError( «The argument `field` must be `None` when the `error` « «argument contains errors for multiple fields.» ) else: error = error.error_dict else: error = {field or NON_FIELD_ERRORS: error.error_list} for field, error_list in error.items(): if field not in self.errors: if field != NON_FIELD_ERRORS and field not in self.fields: raise ValueError( «‘%s’ has no field named ‘%s’.» % (self.__class__.__name__, field) ) if field == NON_FIELD_ERRORS: self._errors[field] = self.error_class( error_class=«nonfield», renderer=self.renderer ) else: self._errors[field] = self.error_class(renderer=self.renderer) self._errors[field].extend(error_list) if field in self.cleaned_data: del self.cleaned_data[field] def has_error(self, field, code=None): return field in self.errors and ( code is None or any(error.code == code for error in self.errors.as_data()[field]) ) def full_clean(self): «»» Clean all of self.data and populate self._errors and self.cleaned_data. «»» self._errors = ErrorDict() if not self.is_bound: # Stop further processing. return self.cleaned_data = {} # If the form is permitted to be empty, and none of the form data has # changed from the initial data, short circuit any validation. if self.empty_permitted and not self.has_changed(): return self._clean_fields() self._clean_form() self._post_clean() def _clean_fields(self): for name, bf in self._bound_items(): field = bf.field value = bf.initial if field.disabled else bf.data try: if isinstance(field, FileField): value = field.clean(value, bf.initial) else: value = field.clean(value) self.cleaned_data[name] = value if hasattr(self, «clean_%s» % name): value = getattr(self, «clean_%s» % name)() self.cleaned_data[name] = value except ValidationError as e: self.add_error(name, e) def _clean_form(self): try: cleaned_data = self.clean() except ValidationError as e: self.add_error(None, e) else: if cleaned_data is not None: self.cleaned_data = cleaned_data def _post_clean(self): «»» An internal hook for performing additional cleaning after form cleaning is complete. Used for model validation in model forms. «»» pass def clean(self): «»» Hook for doing any extra form-wide cleaning after Field.clean() has been called on every field. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field named ‘__all__’. «»» return self.cleaned_data def has_changed(self): «»»Return True if data differs from initial.»»» return bool(self.changed_data) @cached_property def changed_data(self): return [name for name, bf in self._bound_items() if bf._has_changed()] @property def media(self): «»»Return all media required to render the widgets on this form.»»» media = Media() for field in self.fields.values(): media += field.widget.media return media def is_multipart(self): «»» Return True if the form needs to be multipart-encoded, i.e. it has FileInput, or False otherwise. «»» return any(field.widget.needs_multipart_form for field in self.fields.values()) def hidden_fields(self): «»» Return a list of all the BoundField objects that are hidden fields. Useful for manual form layout in templates. «»» return [field for field in self if field.is_hidden] def visible_fields(self): «»» Return a list of BoundField objects that aren’t hidden fields. The opposite of the hidden_fields() method. «»» return [field for field in self if not field.is_hidden] def get_initial_for_field(self, field, field_name): «»» Return initial data for field on form. Use initial data from the form or the field, in that order. Evaluate callable values. «»» value = self.initial.get(field_name, field.initial) if callable(value): value = value() # If this is an auto-generated default date, nix the microseconds # for standardized handling. See #22502. if ( isinstance(value, (datetime.datetime, datetime.time)) and not field.widget.supports_microseconds ): value = value.replace(microsecond=0) return value class Form(BaseForm, metaclass=DeclarativeFieldsMetaclass): «A collection of Fields, plus their associated data.» # This is a separate class from BaseForm in order to abstract the way # self.fields is specified. This class (Form) is the one that does the # fancy metaclass stuff purely for the semantic sugar — it allows one # to define a form using declarative syntax. # BaseForm itself has no way of designating self.fields.

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

error_messages - Django Form Field Validation

Now let’s try to submit it empty and check if required error_message has been overridden.

error_messages-Django-Form-Field-Validation

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.

Понравилась статья? Поделить с друзьями:
  • Django form error text
  • Django form error messages
  • Django form error message
  • Django form error list
  • Django form error css