2016-01-03 18:56:22 +08:00
|
|
|
=========================
|
2008-08-24 15:22:30 +08:00
|
|
|
Form and field validation
|
|
|
|
=========================
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2016-01-03 18:56:22 +08:00
|
|
|
.. currentmodule:: django.forms
|
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
Form validation happens when the data is cleaned. If you want to customize
|
2015-05-24 09:57:02 +08:00
|
|
|
this process, there are various places to make changes, each one serving a
|
2008-08-24 06:25:40 +08:00
|
|
|
different purpose. Three types of cleaning methods are run during form
|
|
|
|
processing. These are normally executed when you call the ``is_valid()``
|
2015-05-24 09:57:02 +08:00
|
|
|
method on a form. There are other things that can also trigger cleaning and
|
2008-08-24 06:25:40 +08:00
|
|
|
validation (accessing the ``errors`` attribute or calling ``full_clean()``
|
|
|
|
directly), but normally they won't be needed.
|
|
|
|
|
|
|
|
In general, any cleaning method can raise ``ValidationError`` if there is a
|
2013-06-06 02:55:05 +08:00
|
|
|
problem with the data it is processing, passing the relevant information to
|
|
|
|
the ``ValidationError`` constructor. :ref:`See below <raising-validation-error>`
|
|
|
|
for the best practice in raising ``ValidationError``. If no ``ValidationError``
|
|
|
|
is raised, the method should return the cleaned (normalized) data as a Python
|
|
|
|
object.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
Most validation can be done using `validators`_ - simple helpers that can be
|
|
|
|
reused easily. Validators are simple functions (or callables) that take a single
|
|
|
|
argument and raise ``ValidationError`` on invalid input. Validators are run
|
|
|
|
after the field's ``to_python`` and ``validate`` methods have been called.
|
|
|
|
|
2015-05-24 09:57:02 +08:00
|
|
|
Validation of a form is split into several steps, which can be customized or
|
2010-01-05 11:56:19 +08:00
|
|
|
overridden:
|
|
|
|
|
2015-05-24 09:57:02 +08:00
|
|
|
* The ``to_python()`` method on a ``Field`` is the first step in every
|
|
|
|
validation. It coerces the value to a correct datatype and raises
|
2011-10-14 08:12:01 +08:00
|
|
|
``ValidationError`` if that is not possible. This method accepts the raw
|
|
|
|
value from the widget and returns the converted value. For example, a
|
2015-05-24 09:57:02 +08:00
|
|
|
``FloatField`` will turn the data into a Python ``float`` or raise a
|
2011-10-14 08:12:01 +08:00
|
|
|
``ValidationError``.
|
|
|
|
|
2015-05-24 09:57:02 +08:00
|
|
|
* The ``validate()`` method on a ``Field`` handles field-specific validation
|
2015-02-03 21:03:05 +08:00
|
|
|
that is not suitable for a validator. It takes a value that has been
|
2015-05-24 09:57:02 +08:00
|
|
|
coerced to a correct datatype and raises ``ValidationError`` on any error.
|
2011-10-14 08:12:01 +08:00
|
|
|
This method does not return anything and shouldn't alter the value. You
|
|
|
|
should override it to handle validation logic that you can't or don't
|
|
|
|
want to put in a validator.
|
|
|
|
|
2015-05-24 09:57:02 +08:00
|
|
|
* The ``run_validators()`` method on a ``Field`` runs all of the field's
|
2011-10-14 08:12:01 +08:00
|
|
|
validators and aggregates all the errors into a single
|
|
|
|
``ValidationError``. You shouldn't need to override this method.
|
|
|
|
|
2015-05-24 09:57:02 +08:00
|
|
|
* The ``clean()`` method on a ``Field`` subclass is responsible for running
|
|
|
|
``to_python()``, ``validate()``, and ``run_validators()`` in the correct
|
2011-10-14 08:12:01 +08:00
|
|
|
order and propagating their errors. If, at any time, any of the methods
|
|
|
|
raise ``ValidationError``, the validation stops and that error is raised.
|
|
|
|
This method returns the clean data, which is then inserted into the
|
|
|
|
``cleaned_data`` dictionary of the form.
|
|
|
|
|
2015-05-24 09:57:02 +08:00
|
|
|
* The ``clean_<fieldname>()`` method is called on a form subclass -- where
|
2011-10-14 08:12:01 +08:00
|
|
|
``<fieldname>`` is replaced with the name of the form field attribute.
|
|
|
|
This method does any cleaning that is specific to that particular
|
|
|
|
attribute, unrelated to the type of field that it is. This method is not
|
|
|
|
passed any parameters. You will need to look up the value of the field
|
|
|
|
in ``self.cleaned_data`` and remember that it will be a Python object
|
|
|
|
at this point, not the original string submitted in the form (it will be
|
|
|
|
in ``cleaned_data`` because the general field ``clean()`` method, above,
|
|
|
|
has already cleaned the data once).
|
|
|
|
|
|
|
|
For example, if you wanted to validate that the contents of a
|
|
|
|
``CharField`` called ``serialnumber`` was unique,
|
|
|
|
``clean_serialnumber()`` would be the right place to do this. You don't
|
|
|
|
need a specific field (it's just a ``CharField``), but you want a
|
|
|
|
formfield-specific piece of validation and, possibly,
|
|
|
|
cleaning/normalizing the data.
|
|
|
|
|
2015-05-24 09:57:02 +08:00
|
|
|
This method should return the cleaned value obtained from ``cleaned_data``,
|
2012-09-07 22:43:55 +08:00
|
|
|
regardless of whether it changed anything or not.
|
2011-10-14 08:12:01 +08:00
|
|
|
|
2015-05-24 09:57:02 +08:00
|
|
|
* The form subclass's ``clean()`` method can perform validation that requires
|
|
|
|
access to multiple form fields. This is where you might put in checks such as
|
2015-12-09 18:43:20 +08:00
|
|
|
"if field ``A`` is supplied, field ``B`` must contain a valid email address".
|
2015-05-24 09:57:02 +08:00
|
|
|
This method can return a completely different dictionary if it wishes, which
|
|
|
|
will be used as the ``cleaned_data``.
|
2011-10-14 08:12:01 +08:00
|
|
|
|
2013-11-13 03:42:44 +08:00
|
|
|
Since the field validation methods have been run by the time ``clean()`` is
|
2014-11-20 23:35:36 +08:00
|
|
|
called, you also have access to the form's ``errors`` attribute which
|
2013-11-13 03:42:44 +08:00
|
|
|
contains all the errors raised by cleaning of individual fields.
|
2013-11-13 03:27:21 +08:00
|
|
|
|
2014-07-01 04:30:57 +08:00
|
|
|
Note that any errors raised by your :meth:`Form.clean()` override will not
|
2011-10-14 08:12:01 +08:00
|
|
|
be associated with any field in particular. They go into a special
|
|
|
|
"field" (called ``__all__``), which you can access via the
|
2014-04-06 06:14:53 +08:00
|
|
|
:meth:`~django.forms.Form.non_field_errors` method if you need to. If you
|
|
|
|
want to attach errors to a specific field in the form, you need to call
|
2013-11-12 22:18:09 +08:00
|
|
|
:meth:`~django.forms.Form.add_error()`.
|
2011-10-14 08:12:01 +08:00
|
|
|
|
|
|
|
Also note that there are special considerations when overriding
|
|
|
|
the ``clean()`` method of a ``ModelForm`` subclass. (see the
|
|
|
|
:ref:`ModelForm documentation
|
|
|
|
<overriding-modelform-clean-method>` for more information)
|
2010-05-09 13:49:14 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
These methods are run in the order given above, one field at a time. That is,
|
|
|
|
for each field in the form (in the order they are declared in the form
|
|
|
|
definition), the ``Field.clean()`` method (or its override) is run, then
|
|
|
|
``clean_<fieldname>()``. Finally, once those two methods are run for every
|
2014-09-01 08:06:38 +08:00
|
|
|
field, the :meth:`Form.clean()` method, or its override, is executed whether
|
2014-07-01 04:30:57 +08:00
|
|
|
or not the previous methods have raised errors.
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2008-10-06 19:21:11 +08:00
|
|
|
Examples of each of these methods are provided below.
|
|
|
|
|
|
|
|
As mentioned, any of these methods can raise a ``ValidationError``. For any
|
|
|
|
field, if the ``Field.clean()`` method raises a ``ValidationError``, any
|
2008-08-24 06:25:40 +08:00
|
|
|
field-specific cleaning method is not called. However, the cleaning methods
|
|
|
|
for all remaining fields are still executed.
|
|
|
|
|
2013-06-06 02:55:05 +08:00
|
|
|
.. _raising-validation-error:
|
|
|
|
|
|
|
|
Raising ``ValidationError``
|
2016-01-03 18:56:22 +08:00
|
|
|
===========================
|
2013-06-06 02:55:05 +08:00
|
|
|
|
|
|
|
In order to make error messages flexible and easy to override, consider the
|
|
|
|
following guidelines:
|
|
|
|
|
|
|
|
* Provide a descriptive error ``code`` to the constructor::
|
|
|
|
|
|
|
|
# Good
|
|
|
|
ValidationError(_('Invalid value'), code='invalid')
|
|
|
|
|
|
|
|
# Bad
|
|
|
|
ValidationError(_('Invalid value'))
|
|
|
|
|
|
|
|
* Don't coerce variables into the message; use placeholders and the ``params``
|
|
|
|
argument of the constructor::
|
|
|
|
|
|
|
|
# Good
|
|
|
|
ValidationError(
|
|
|
|
_('Invalid value: %(value)s'),
|
|
|
|
params={'value': '42'},
|
|
|
|
)
|
|
|
|
|
|
|
|
# Bad
|
|
|
|
ValidationError(_('Invalid value: %s') % value)
|
|
|
|
|
|
|
|
* Use mapping keys instead of positional formatting. This enables putting
|
|
|
|
the variables in any order or omitting them altogether when rewriting the
|
|
|
|
message::
|
|
|
|
|
|
|
|
# Good
|
|
|
|
ValidationError(
|
|
|
|
_('Invalid value: %(value)s'),
|
|
|
|
params={'value': '42'},
|
|
|
|
)
|
|
|
|
|
|
|
|
# Bad
|
|
|
|
ValidationError(
|
|
|
|
_('Invalid value: %s'),
|
|
|
|
params=('42',),
|
|
|
|
)
|
|
|
|
|
|
|
|
* Wrap the message with ``gettext`` to enable translation::
|
|
|
|
|
|
|
|
# Good
|
|
|
|
ValidationError(_('Invalid value'))
|
|
|
|
|
|
|
|
# Bad
|
|
|
|
ValidationError('Invalid value')
|
|
|
|
|
|
|
|
Putting it all together::
|
|
|
|
|
2013-07-30 06:41:08 +08:00
|
|
|
raise ValidationError(
|
2013-06-06 02:55:05 +08:00
|
|
|
_('Invalid value: %(value)s'),
|
|
|
|
code='invalid',
|
|
|
|
params={'value': '42'},
|
|
|
|
)
|
|
|
|
|
|
|
|
Following these guidelines is particularly necessary if you write reusable
|
|
|
|
forms, form fields, and model fields.
|
|
|
|
|
|
|
|
While not recommended, if you are at the end of the validation chain
|
|
|
|
(i.e. your form ``clean()`` method) and you know you will *never* need
|
|
|
|
to override your error message you can still opt for the less verbose::
|
|
|
|
|
|
|
|
ValidationError(_('Invalid value: %s') % value)
|
|
|
|
|
2014-02-14 02:19:13 +08:00
|
|
|
The :meth:`Form.errors.as_data() <django.forms.Form.errors.as_data()>` and
|
|
|
|
:meth:`Form.errors.as_json() <django.forms.Form.errors.as_json()>` methods
|
|
|
|
greatly benefit from fully featured ``ValidationError``\s (with a ``code`` name
|
|
|
|
and a ``params`` dictionary).
|
|
|
|
|
2013-06-06 02:55:05 +08:00
|
|
|
Raising multiple errors
|
2016-01-03 18:56:22 +08:00
|
|
|
-----------------------
|
2013-06-06 02:55:05 +08:00
|
|
|
|
|
|
|
If you detect multiple errors during a cleaning method and wish to signal all
|
|
|
|
of them to the form submitter, it is possible to pass a list of errors to the
|
|
|
|
``ValidationError`` constructor.
|
|
|
|
|
|
|
|
As above, it is recommended to pass a list of ``ValidationError`` instances
|
|
|
|
with ``code``\s and ``params`` but a list of strings will also work::
|
|
|
|
|
|
|
|
# Good
|
|
|
|
raise ValidationError([
|
|
|
|
ValidationError(_('Error 1'), code='error1'),
|
|
|
|
ValidationError(_('Error 2'), code='error2'),
|
|
|
|
])
|
|
|
|
|
|
|
|
# Bad
|
|
|
|
raise ValidationError([
|
|
|
|
_('Error 1'),
|
|
|
|
_('Error 2'),
|
|
|
|
])
|
|
|
|
|
2008-10-06 19:21:11 +08:00
|
|
|
Using validation in practice
|
2016-01-03 18:56:22 +08:00
|
|
|
============================
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2008-10-06 19:21:11 +08:00
|
|
|
The previous sections explained how validation works in general for forms.
|
|
|
|
Since it can sometimes be easier to put things into place by seeing each
|
|
|
|
feature in use, here are a series of small examples that use each of the
|
|
|
|
previous features.
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
.. _validators:
|
|
|
|
|
|
|
|
Using validators
|
2016-01-03 18:56:22 +08:00
|
|
|
----------------
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
Django's form (and model) fields support use of simple utility functions and
|
2013-09-23 21:46:19 +08:00
|
|
|
classes known as validators. A validator is merely a callable object or
|
|
|
|
function that takes a value and simply returns nothing if the value is valid or
|
|
|
|
raises a :exc:`~django.core.exceptions.ValidationError` if not. These can be
|
|
|
|
passed to a field's constructor, via the field's ``validators`` argument, or
|
|
|
|
defined on the :class:`~django.forms.Field` class itself with the
|
|
|
|
``default_validators`` attribute.
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
Simple validators can be used to validate values inside the field, let's have
|
2013-03-14 23:19:59 +08:00
|
|
|
a look at Django's ``SlugField``::
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2013-05-19 17:15:35 +08:00
|
|
|
from django.forms import CharField
|
|
|
|
from django.core import validators
|
|
|
|
|
2013-03-14 23:19:59 +08:00
|
|
|
class SlugField(CharField):
|
|
|
|
default_validators = [validators.validate_slug]
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2013-03-14 23:19:59 +08:00
|
|
|
As you can see, ``SlugField`` is just a ``CharField`` with a customized
|
|
|
|
validator that validates that submitted text obeys to some character rules.
|
|
|
|
This can also be done on field definition so::
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2013-03-14 23:19:59 +08:00
|
|
|
slug = forms.SlugField()
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
is equivalent to::
|
|
|
|
|
2013-03-14 23:19:59 +08:00
|
|
|
slug = forms.CharField(validators=[validators.validate_slug])
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2013-09-23 21:46:19 +08:00
|
|
|
Common cases such as validating against an email or a regular expression can be
|
|
|
|
handled using existing validator classes available in Django. For example,
|
|
|
|
``validators.validate_slug`` is an instance of
|
|
|
|
a :class:`~django.core.validators.RegexValidator` constructed with the first
|
|
|
|
argument being the pattern: ``^[-a-zA-Z0-9_]+$``. See the section on
|
|
|
|
:doc:`writing validators </ref/validators>` to see a list of what is already
|
|
|
|
available and for an example of how to write a validator.
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2008-10-06 19:21:11 +08:00
|
|
|
Form field default cleaning
|
2016-01-03 18:56:22 +08:00
|
|
|
---------------------------
|
2008-10-06 19:21:11 +08:00
|
|
|
|
2015-02-03 21:03:05 +08:00
|
|
|
Let's first create a custom form field that validates its input is a string
|
2011-04-02 00:10:22 +08:00
|
|
|
containing comma-separated email addresses. The full class looks like this::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
from django import forms
|
2010-01-05 11:56:19 +08:00
|
|
|
from django.core.validators import validate_email
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
class MultiEmailField(forms.Field):
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
"Normalize data to a list of strings."
|
|
|
|
|
|
|
|
# Return an empty list if no input was given.
|
2008-08-24 06:25:40 +08:00
|
|
|
if not value:
|
2010-01-05 11:56:19 +08:00
|
|
|
return []
|
|
|
|
return value.split(',')
|
|
|
|
|
|
|
|
def validate(self, value):
|
|
|
|
"Check if value consists only of valid emails."
|
|
|
|
|
|
|
|
# Use the parent's handling of required fields, etc.
|
|
|
|
super(MultiEmailField, self).validate(value)
|
2008-10-06 19:21:11 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
for email in value:
|
|
|
|
validate_email(email)
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
Every form that uses this field will have these methods run before anything
|
|
|
|
else can be done with the field's data. This is cleaning that is specific to
|
|
|
|
this type of field, regardless of how it is subsequently used.
|
2008-10-06 19:21:11 +08:00
|
|
|
|
|
|
|
Let's create a simple ``ContactForm`` to demonstrate how you'd use this
|
|
|
|
field::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
class ContactForm(forms.Form):
|
|
|
|
subject = forms.CharField(max_length=100)
|
|
|
|
message = forms.CharField()
|
2008-10-06 19:21:11 +08:00
|
|
|
sender = forms.EmailField()
|
|
|
|
recipients = MultiEmailField()
|
2008-08-24 06:25:40 +08:00
|
|
|
cc_myself = forms.BooleanField(required=False)
|
2008-10-06 19:21:11 +08:00
|
|
|
|
|
|
|
Simply use ``MultiEmailField`` like any other form field. When the
|
|
|
|
``is_valid()`` method is called on the form, the ``MultiEmailField.clean()``
|
2010-01-05 11:56:19 +08:00
|
|
|
method will be run as part of the cleaning process and it will, in turn, call
|
|
|
|
the custom ``to_python()`` and ``validate()`` methods.
|
2008-10-06 19:21:11 +08:00
|
|
|
|
|
|
|
Cleaning a specific field attribute
|
2016-01-03 18:56:22 +08:00
|
|
|
-----------------------------------
|
2008-10-06 19:21:11 +08:00
|
|
|
|
|
|
|
Continuing on from the previous example, suppose that in our ``ContactForm``,
|
|
|
|
we want to make sure that the ``recipients`` field always contains the address
|
|
|
|
``"fred@example.com"``. This is validation that is specific to our form, so we
|
|
|
|
don't want to put it into the general ``MultiEmailField`` class. Instead, we
|
|
|
|
write a cleaning method that operates on the ``recipients`` field, like so::
|
|
|
|
|
2013-05-19 17:15:35 +08:00
|
|
|
from django import forms
|
|
|
|
|
2008-10-06 19:21:11 +08:00
|
|
|
class ContactForm(forms.Form):
|
|
|
|
# Everything as before.
|
|
|
|
...
|
|
|
|
|
|
|
|
def clean_recipients(self):
|
|
|
|
data = self.cleaned_data['recipients']
|
|
|
|
if "fred@example.com" not in data:
|
|
|
|
raise forms.ValidationError("You have forgotten about Fred!")
|
|
|
|
|
|
|
|
# Always return the cleaned data, whether you have changed it or
|
|
|
|
# not.
|
|
|
|
return data
|
|
|
|
|
2014-07-01 04:30:57 +08:00
|
|
|
.. _validating-fields-with-clean:
|
|
|
|
|
2008-10-06 19:21:11 +08:00
|
|
|
Cleaning and validating fields that depend on each other
|
2016-01-03 18:56:22 +08:00
|
|
|
--------------------------------------------------------
|
2008-10-06 19:21:11 +08:00
|
|
|
|
|
|
|
Suppose we add another requirement to our contact form: if the ``cc_myself``
|
|
|
|
field is ``True``, the ``subject`` must contain the word ``"help"``. We are
|
|
|
|
performing validation on more than one field at a time, so the form's
|
2014-07-01 04:30:57 +08:00
|
|
|
:meth:`~Form.clean()` method is a good spot to do this. Notice that we are
|
|
|
|
talking about the ``clean()`` method on the form here, whereas earlier we were
|
|
|
|
writing a ``clean()`` method on a field. It's important to keep the field and
|
|
|
|
form difference clear when working out where to validate things. Fields are
|
|
|
|
single data points, forms are a collection of fields.
|
2008-10-06 19:21:11 +08:00
|
|
|
|
|
|
|
By the time the form's ``clean()`` method is called, all the individual field
|
|
|
|
clean methods will have been run (the previous two sections), so
|
|
|
|
``self.cleaned_data`` will be populated with any data that has survived so
|
|
|
|
far. So you also need to remember to allow for the fact that the fields you
|
|
|
|
are wanting to validate might not have survived the initial individual field
|
|
|
|
checks.
|
|
|
|
|
2011-01-31 03:09:44 +08:00
|
|
|
There are two ways to report any errors from this step. Probably the most
|
2008-10-06 19:21:11 +08:00
|
|
|
common method is to display the error at the top of the form. To create such
|
|
|
|
an error, you can raise a ``ValidationError`` from the ``clean()`` method. For
|
|
|
|
example::
|
|
|
|
|
2013-05-19 17:15:35 +08:00
|
|
|
from django import forms
|
|
|
|
|
2008-10-06 19:21:11 +08:00
|
|
|
class ContactForm(forms.Form):
|
|
|
|
# Everything as before.
|
|
|
|
...
|
|
|
|
|
|
|
|
def clean(self):
|
2012-02-05 00:05:30 +08:00
|
|
|
cleaned_data = super(ContactForm, self).clean()
|
2008-10-06 19:21:11 +08:00
|
|
|
cc_myself = cleaned_data.get("cc_myself")
|
|
|
|
subject = cleaned_data.get("subject")
|
|
|
|
|
|
|
|
if cc_myself and subject:
|
|
|
|
# Only do something if both fields are valid so far.
|
|
|
|
if "help" not in subject:
|
2015-06-11 21:34:03 +08:00
|
|
|
raise forms.ValidationError(
|
|
|
|
"Did not send for 'help' in the subject despite "
|
|
|
|
"CC'ing yourself."
|
|
|
|
)
|
2008-10-06 19:21:11 +08:00
|
|
|
|
|
|
|
In this code, if the validation error is raised, the form will display an
|
|
|
|
error message at the top of the form (normally) describing the problem.
|
|
|
|
|
2015-10-22 01:50:48 +08:00
|
|
|
The call to ``super(ContactForm, self).clean()`` in the example code ensures
|
|
|
|
that any validation logic in parent classes is maintained. If your form
|
|
|
|
inherits another that doesn't return a ``cleaned_data`` dictionary in its
|
|
|
|
``clean()`` method (doing so is optional), then don't assign ``cleaned_data``
|
|
|
|
to the result of the ``super()`` call and use ``self.cleaned_data`` instead::
|
|
|
|
|
|
|
|
def clean(self):
|
|
|
|
super(ContactForm, self).clean()
|
|
|
|
cc_myself = self.cleaned_data.get("cc_myself")
|
|
|
|
...
|
|
|
|
|
|
|
|
The second approach for reporting validation errors might involve assigning the
|
|
|
|
error message to one of the fields. In this case, let's assign an error message
|
|
|
|
to both the "subject" and "cc_myself" rows in the form display. Be careful when
|
|
|
|
doing this in practice, since it can lead to confusing form output. We're
|
|
|
|
showing what is possible here and leaving it up to you and your designers to
|
|
|
|
work out what works effectively in your particular situation. Our new code
|
|
|
|
(replacing the previous sample) looks like this::
|
2008-10-06 19:21:11 +08:00
|
|
|
|
2013-05-19 17:15:35 +08:00
|
|
|
from django import forms
|
|
|
|
|
2013-11-12 01:56:01 +08:00
|
|
|
class ContactForm(forms.Form):
|
|
|
|
# Everything as before.
|
|
|
|
...
|
|
|
|
|
|
|
|
def clean(self):
|
|
|
|
cleaned_data = super(ContactForm, self).clean()
|
|
|
|
cc_myself = cleaned_data.get("cc_myself")
|
|
|
|
subject = cleaned_data.get("subject")
|
|
|
|
|
|
|
|
if cc_myself and subject and "help" not in subject:
|
2014-03-23 04:30:49 +08:00
|
|
|
msg = "Must put 'help' in subject when cc'ing yourself."
|
2013-11-12 01:56:01 +08:00
|
|
|
self.add_error('cc_myself', msg)
|
|
|
|
self.add_error('subject', msg)
|
|
|
|
|
|
|
|
The second argument of ``add_error()`` can be a simple string, or preferably
|
|
|
|
an instance of ``ValidationError``. See :ref:`raising-validation-error` for
|
2014-06-12 05:13:34 +08:00
|
|
|
more details. Note that ``add_error()`` automatically removes the field
|
2013-11-12 01:56:01 +08:00
|
|
|
from ``cleaned_data``.
|