Меню

Django обработка ошибок формы

Form and field validation¶

Form validation happens when the data is cleaned. If you want to customize
this process, there are various places to make changes, each one serving a
different purpose. Three types of cleaning methods are run during form
processing. These are normally executed when you call the is_valid()
method on a form. There are other things that can also trigger cleaning and
validation (accessing the errors attribute or calling full_clean()
directly), but normally they won’t be needed.

In general, any cleaning method can raise ValidationError if there is a
problem with the data it is processing, passing the relevant information to
the ValidationError constructor. See below
for the best practice in raising ValidationError. If no ValidationError
is raised, the method should return the cleaned (normalized) data as a Python
object.

Most validation can be done using validators — helpers that can be reused.
Validators are functions (or callables) that take a single argument and raise
ValidationError on invalid input. Validators are run after the field’s
to_python and validate methods have been called.

Validation of a form is split into several steps, which can be customized or
overridden:

  • The to_python() method on a Field is the first step in every
    validation. It coerces the value to a correct datatype and raises
    ValidationError if that is not possible. This method accepts the raw
    value from the widget and returns the converted value. For example, a
    FloatField will turn the data into a Python float or raise a
    ValidationError.

  • The validate() method on a Field handles field-specific validation
    that is not suitable for a validator. It takes a value that has been
    coerced to a correct datatype and raises ValidationError on any error.
    This method does not return anything and shouldn’t alter the value. You
    should override it to handle validation logic that you can’t or don’t
    want to put in a validator.

  • The run_validators() method on a Field runs all of the field’s
    validators and aggregates all the errors into a single
    ValidationError. You shouldn’t need to override this method.

  • The clean() method on a Field subclass is responsible for running
    to_python(), validate(), and run_validators() in the correct
    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.

  • The clean_<fieldname>() method is called on a form subclass – where
    <fieldname> is replaced with the name of the form field attribute.
    This method does any cleaning that is specific to that particular
    attribute, unrelated to the type of field that it is. This method is not
    passed any parameters. You will need to look up the value of the field
    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 a CharField), but you want a
    formfield-specific piece of validation and, possibly, cleaning/normalizing
    the data.

    The return value of this method replaces the existing value in
    cleaned_data, so it must be the field’s value from cleaned_data (even
    if this method didn’t change it) or a new cleaned value.

  • The form subclass’s clean() method can perform validation that requires
    access to multiple form fields. This is where you might put in checks such as
    “if field A is supplied, field B must contain a valid email address”.
    This method can return a completely different dictionary if it wishes, which
    will be used as the cleaned_data.

    Since the field validation methods have been run by the time clean() is
    called, you also have access to the form’s errors attribute which
    contains all the errors raised by cleaning of individual fields.

    Note that any errors raised by your Form.clean() override will not
    be associated with any field in particular. They go into a special
    “field” (called __all__), which you can access via the
    non_field_errors() method if you need to. If you
    want to attach errors to a specific field in the form, you need to call
    add_error().

    Also note that there are special considerations when overriding
    the clean() method of a ModelForm subclass. (see the
    ModelForm documentation for more information)

These methods are run in the order given above, one field at a time. That is,
for each field in the form (in the order they are declared in the form
definition), the Field.clean() method (or its override) is run, then
clean_<fieldname>(). Finally, once those two methods are run for every
field, the Form.clean() method, or its override, is executed whether
or not the previous methods have raised errors.

Examples of each of these methods are provided below.

As mentioned, any of these methods can raise a ValidationError. For any
field, if the Field.clean() method raises a ValidationError, any
field-specific cleaning method is not called. However, the cleaning methods
for all remaining fields are still executed.

Raising ValidationError

In order to make error messages flexible and easy to override, consider the
following guidelines:

  • Provide a descriptive error code to the constructor:

    # Good
    ValidationError(_('Invalid value'), code='invalid')
    
    # Bad
    ValidationError(_('Invalid value'))
    
  • Don’t coerce variables into the message; use placeholders and the params
    argument of the constructor:

    # Good
    ValidationError(
        _('Invalid value: %(value)s'),
        params={'value': '42'},
    )
    
    # Bad
    ValidationError(_('Invalid value: %s') % value)
    
  • Use mapping keys instead of positional formatting. This enables putting
    the variables in any order or omitting them altogether when rewriting the
    message:

    # Good
    ValidationError(
        _('Invalid value: %(value)s'),
        params={'value': '42'},
    )
    
    # Bad
    ValidationError(
        _('Invalid value: %s'),
        params=('42',),
    )
    
  • Wrap the message with gettext to enable translation:

    # Good
    ValidationError(_('Invalid value'))
    
    # Bad
    ValidationError('Invalid value')
    

Putting it all together:

raise ValidationError(
    _('Invalid value: %(value)s'),
    code='invalid',
    params={'value': '42'},
)

Following these guidelines is particularly necessary if you write reusable
forms, form fields, and model fields.

While not recommended, if you are at the end of the validation chain
(i.e. your form clean() method) and you know you will never need
to override your error message you can still opt for the less verbose:

ValidationError(_('Invalid value: %s') % value)

The Form.errors.as_data() and
Form.errors.as_json() methods
greatly benefit from fully featured ValidationErrors (with a code name
and a params dictionary).

Raising multiple errors¶

If you detect multiple errors during a cleaning method and wish to signal all
of them to the form submitter, it is possible to pass a list of errors to the
ValidationError constructor.

As above, it is recommended to pass a list of ValidationError instances
with codes and params but a list of strings will also work:

# Good
raise ValidationError([
    ValidationError(_('Error 1'), code='error1'),
    ValidationError(_('Error 2'), code='error2'),
])

# Bad
raise ValidationError([
    _('Error 1'),
    _('Error 2'),
])

Using validation in practice¶

The previous sections explained how validation works in general for forms.
Since it can sometimes be easier to put things into place by seeing each
feature in use, here are a series of small examples that use each of the
previous features.

Using validators¶

Django’s form (and model) fields support use of utility functions and classes
known as validators. A validator is a callable object or function that takes a
value and returns nothing if the value is valid or raises a
ValidationError if not. These can be passed to a
field’s constructor, via the field’s validators argument, or defined on the
Field class itself with the default_validators
attribute.

Validators can be used to validate values inside the field, let’s have a look
at Django’s SlugField:

from django.core import validators
from django.forms import CharField

class SlugField(CharField):
    default_validators = [validators.validate_slug]

As you can see, SlugField is a CharField with a customized validator
that validates that submitted text obeys to some character rules. This can also
be done on field definition so:

is equivalent to:

slug = forms.CharField(validators=[validators.validate_slug])

Common cases such as validating against an email or a regular expression can be
handled using existing validator classes available in Django. For example,
validators.validate_slug is an instance of
a RegexValidator constructed with the first
argument being the pattern: ^[-a-zA-Z0-9_]+$. See the section on
writing validators to see a list of what is already
available and for an example of how to write a validator.

Form field default cleaning¶

Let’s first create a custom form field that validates its input is a string
containing comma-separated email addresses. The full class looks like this:

from django import forms
from django.core.validators import validate_email

class MultiEmailField(forms.Field):
    def to_python(self, value):
        """Normalize data to a list of strings."""
        # Return an empty list if no input was given.
        if not value:
            return []
        return value.split(',')

    def validate(self, value):
        """Check if value consists only of valid emails."""
        # Use the parent's handling of required fields, etc.
        super().validate(value)
        for email in value:
            validate_email(email)

Every form that uses this field will have these methods run before anything
else can be done with the field’s data. This is cleaning that is specific to
this type of field, regardless of how it is subsequently used.

Let’s create a ContactForm to demonstrate how you’d use this field:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    recipients = MultiEmailField()
    cc_myself = forms.BooleanField(required=False)

Use MultiEmailField like any other form field. When the is_valid()
method is called on the form, the MultiEmailField.clean() method will be
run as part of the cleaning process and it will, in turn, call the custom
to_python() and validate() methods.

Cleaning a specific field attribute¶

Continuing on from the previous example, suppose that in our ContactForm,
we want to make sure that the recipients field always contains the address
"fred@example.com". This is validation that is specific to our form, so we
don’t want to put it into the general MultiEmailField class. Instead, we
write a cleaning method that operates on the recipients field, like so:

from django import forms
from django.core.exceptions import ValidationError

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean_recipients(self):
        data = self.cleaned_data['recipients']
        if "fred@example.com" not in data:
            raise ValidationError("You have forgotten about Fred!")

        # Always return a value to use as the new cleaned data, even if
        # this method didn't change it.
        return data

Cleaning and validating fields that depend on each other¶

Suppose we add another requirement to our contact form: if the cc_myself
field is True, the subject must contain the word "help". We are
performing validation on more than one field at a time, so the form’s
clean() method is a good spot to do this. Notice that we are
talking about the clean() method on the form here, whereas earlier we were
writing a clean() method on a field. It’s important to keep the field and
form difference clear when working out where to validate things. Fields are
single data points, forms are a collection of fields.

By the time the form’s clean() method is called, all the individual field
clean methods will have been run (the previous two sections), so
self.cleaned_data will be populated with any data that has survived so
far. So you also need to remember to allow for the fact that the fields you
are wanting to validate might not have survived the initial individual field
checks.

There are two ways to report any errors from this step. Probably the most
common method is to display the error at the top of the form. To create such
an error, you can raise a ValidationError from the clean() method. For
example:

from django import forms
from django.core.exceptions import ValidationError

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super().clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject:
            # Only do something if both fields are valid so far.
            if "help" not in subject:
                raise ValidationError(
                    "Did not send for 'help' in the subject despite "
                    "CC'ing yourself."
                )

In this code, if the validation error is raised, the form will display an
error message at the top of the form (normally) describing the problem. Such
errors are non-field errors, which are displayed in the template with
{{ form.non_field_errors }}.

The call to super().clean() in the example code ensures that any validation
logic in parent classes is maintained. If your form inherits another that
doesn’t return a cleaned_data dictionary in its clean() method (doing
so is optional), then don’t assign cleaned_data to the result of the
super() call and use self.cleaned_data instead:

def clean(self):
    super().clean()
    cc_myself = self.cleaned_data.get("cc_myself")
    ...

The second approach for reporting validation errors might involve assigning the
error message to one of the fields. In this case, let’s assign an error message
to both the “subject” and “cc_myself” rows in the form display. Be careful when
doing this in practice, since it can lead to confusing form output. We’re
showing what is possible here and leaving it up to you and your designers to
work out what works effectively in your particular situation. Our new code
(replacing the previous sample) looks like this:

from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super().clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject and "help" not in subject:
            msg = "Must put 'help' in subject when cc'ing yourself."
            self.add_error('cc_myself', msg)
            self.add_error('subject', msg)

The second argument of add_error() can be a string, or preferably an
instance of ValidationError. See Raising ValidationError for more
details. Note that add_error() automatically removes the field from
cleaned_data.

Валидация форм и полей¶

Валидация формы происходит при очистке данных. Если вы хотите настроить этот процесс, есть различные места для внесения изменений, каждое из которых служит для разных целей. В процессе обработки формы выполняются три типа методов очистки. Обычно они выполняются, когда вы вызываете метод is_valid() на форме. Есть и другие вещи, которые также могут вызвать очистку и проверку (обращение к атрибуту errors или прямой вызов full_clean()), но обычно они не нужны.

В общем, любой метод очистки может поднять ValidationError, если есть проблема с данными, которые он обрабатывает, передавая соответствующую информацию конструктору ValidationError. See below для лучшей практики поднятия ValidationError. Если не поднимается ValidationError, метод должен вернуть очищенные (нормализованные) данные в виде объекта Python.

Большинство валидаций можно выполнить с помощью validators — помощников, которые можно использовать повторно. Валидаторы — это функции (или callables), которые принимают один аргумент и вызывают ValidationError при недопустимом вводе. Валидаторы запускаются после вызова методов to_python и validate поля.

Валидация формы разбита на несколько этапов, которые можно настроить или отменить:

  • Метод to_python() на Field является первым шагом в каждой валидации. Он преобразует значение к правильному типу данных и выдает сообщение ValidationError, если это невозможно. Этот метод принимает необработанное значение от виджета и возвращает преобразованное значение. Например, FloatField превратит данные в Python float или выдаст ValidationError.

  • Метод validate() на Field обрабатывает специфическую для поля валидацию, которая не подходит для валидатора. Он принимает значение, которое было приведено к правильному типу данных, и при любой ошибке выдает сообщение ValidationError. Этот метод ничего не возвращает и не должен изменять значение. Вы должны переопределить его для обработки логики валидации, которую вы не можете или не хотите поместить в валидатор.

  • Метод run_validators() на поле Field запускает все валидаторы поля и объединяет все ошибки в один ValidationError. Вам не нужно переопределять этот метод.

  • Метод clean() в подклассе Field отвечает за выполнение to_python(), validate() и run_validators() в правильном порядке и распространение их ошибок. Если в любой момент времени какой-либо из методов вызывает ошибку ValidationError, валидация останавливается, и эта ошибка выдается. Этот метод возвращает чистые данные, которые затем вставляются в словарь cleaned_data формы.

  • Метод clean_<fieldname>() вызывается на подклассе формы – где <fieldname> заменяется на имя атрибута поля формы. Этот метод выполняет любую очистку, специфичную для данного атрибута, не связанную с типом поля, которым он является. Этому методу не передаются никакие параметры. Вам нужно будет найти значение поля в self.cleaned_data и помнить, что в этот момент это будет объект Python, а не исходная строка, представленная в форме (она будет в cleaned_data, потому что метод general field clean(), описанный выше, уже однажды очистил данные).

    Например, если вы хотите проверить, что содержимое CharField под названием serialnumber является уникальным, clean_serialnumber() будет подходящим местом для этого. Вам не нужно конкретное поле (это CharField), но вам нужен специфический для поля формы фрагмент проверки и, возможно, очистки/нормализации данных.

    Возвращаемое значение этого метода заменяет существующее значение в cleaned_data, поэтому это должно быть значение поля из cleaned_data (даже если этот метод не изменил его) или новое очищенное значение.

  • Метод clean() подкласса формы может выполнять валидацию, требующую доступа к нескольким полям формы. Сюда можно отнести такие проверки, как «если поле A предоставлено, то поле B должно содержать действительный адрес электронной почты». При желании этот метод может вернуть совершенно другой словарь, который будет использован в качестве cleaned_data.

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

    Обратите внимание, что любые ошибки, возникающие при переопределении Form.clean(), не будут связаны с каким-либо конкретным полем. Они попадают в специальное «поле» (называемое __all__), к которому вы можете получить доступ через метод non_field_errors(), если вам это необходимо. Если вы хотите прикрепить ошибки к определенному полю формы, вам нужно вызвать add_error().

    Также обратите внимание, что существуют особые соображения при переопределении метода clean() подкласса ModelForm. (см. ModelForm documentation для получения дополнительной информации)

Эти методы выполняются в указанном выше порядке, по одному полю за раз. То есть, для каждого поля формы (в порядке их объявления в определении формы) выполняется метод Field.clean() (или его переопределение), затем clean_<fieldname>(). Наконец, когда эти два метода выполнены для каждого поля, выполняется метод Form.clean(), или его переопределение, независимо от того, вызвали ли предыдущие методы ошибки.

Примеры каждого из этих методов приведены ниже.

Как уже упоминалось, любой из этих методов может вызвать ошибку ValidationError. Для любого поля, если метод Field.clean() вызывает ValidationError, любой метод очистки, специфичный для данного поля, не вызывается. Однако методы очистки для всех оставшихся полей все равно выполняются.

Поднятие ValidationError

Чтобы сделать сообщения об ошибках гибкими и легко переопределяемыми, примите во внимание следующие рекомендации:

  • Предоставить описательную ошибку code конструктору:

    # Good
    ValidationError(_('Invalid value'), code='invalid')
    
    # Bad
    ValidationError(_('Invalid value'))
    
  • Не вставляйте переменные в сообщение; используйте заполнители и аргумент params конструктора:

    # Good
    ValidationError(
        _('Invalid value: %(value)s'),
        params={'value': '42'},
    )
    
    # Bad
    ValidationError(_('Invalid value: %s') % value)
    
  • Используйте ключи отображения вместо позиционного форматирования. Это позволяет располагать переменные в любом порядке или вообще их не использовать при переписывании сообщения:

    # Good
    ValidationError(
        _('Invalid value: %(value)s'),
        params={'value': '42'},
    )
    
    # Bad
    ValidationError(
        _('Invalid value: %s'),
        params=('42',),
    )
    
  • Оберните сообщение символом gettext, чтобы включить перевод:

    # Good
    ValidationError(_('Invalid value'))
    
    # Bad
    ValidationError('Invalid value')
    

Собираем все вместе:

raise ValidationError(
    _('Invalid value: %(value)s'),
    code='invalid',
    params={'value': '42'},
)

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

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

ValidationError(_('Invalid value: %s') % value)

Методы Form.errors.as_data() и Form.errors.as_json() значительно выигрывают от полнофункциональных ValidationErrors (с code именем и params словарем).

Возникновение множества ошибок¶

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

Как и выше, рекомендуется передавать список экземпляров ValidationError с codes и params, но подойдет и список строк:

# Good
raise ValidationError([
    ValidationError(_('Error 1'), code='error1'),
    ValidationError(_('Error 2'), code='error2'),
])

# Bad
raise ValidationError([
    _('Error 1'),
    _('Error 2'),
])

Использование валидации на практике¶

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

Использование валидаторов¶

Поля формы (и модели) Django поддерживают использование полезных функций и классов, известных как валидаторы. Валидатор — это вызываемый объект или функция, которая принимает значение и не возвращает ничего, если значение действительно, или выдает ошибку ValidationError, если нет. Они могут быть переданы в конструктор поля через аргумент validators или определены в самом классе Field с помощью атрибута default_validators.

Валидаторы могут использоваться для проверки значений внутри поля, давайте посмотрим на Django’s SlugField:

from django.core import validators
from django.forms import CharField

class SlugField(CharField):
    default_validators = [validators.validate_slug]

Как вы можете видеть, SlugField — это CharField с настроенным валидатором, который проверяет, что отправленный текст соответствует некоторым правилам символов. Это также можно сделать при определении поля так:

эквивалентно:

slug = forms.CharField(validators=[validators.validate_slug])

Обычные случаи, такие как проверка по электронной почте или регулярному выражению, могут быть обработаны с помощью существующих классов валидаторов, доступных в Django. Например, validators.validate_slug — это экземпляр RegexValidator, построенный с первым аргументом в виде шаблона: ^[-a-zA-Z0-9_]+$. Смотрите раздел writing validators, чтобы увидеть список того, что уже доступно, и пример того, как написать валидатор.

Очистка полей формы по умолчанию¶

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

from django import forms
from django.core.validators import validate_email

class MultiEmailField(forms.Field):
    def to_python(self, value):
        """Normalize data to a list of strings."""
        # Return an empty list if no input was given.
        if not value:
            return []
        return value.split(',')

    def validate(self, value):
        """Check if value consists only of valid emails."""
        # Use the parent's handling of required fields, etc.
        super().validate(value)
        for email in value:
            validate_email(email)

В каждой форме, использующей это поле, эти методы будут выполняться до того, как с данными поля можно будет сделать что-либо еще. Это очистка, специфичная для данного типа поля, независимо от того, как оно будет использоваться в дальнейшем.

Давайте создадим ContactForm, чтобы продемонстрировать, как вы будете использовать это поле:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    recipients = MultiEmailField()
    cc_myself = forms.BooleanField(required=False)

Используйте MultiEmailField как любое другое поле формы. Когда на форме будет вызван метод is_valid(), в процессе очистки будет запущен метод MultiEmailField.clean(), который, в свою очередь, вызовет пользовательские методы to_python() и validate().

Очистка определенного атрибута поля¶

Продолжая предыдущий пример, предположим, что в нашем ContactForm мы хотим убедиться, что поле recipients всегда содержит адрес "fred@example.com". Это проверка, специфичная для нашей формы, поэтому мы не хотим помещать ее в общий класс MultiEmailField. Вместо этого мы напишем метод очистки, который работает с полем recipients, следующим образом:

from django import forms
from django.core.exceptions import ValidationError

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean_recipients(self):
        data = self.cleaned_data['recipients']
        if "fred@example.com" not in data:
            raise ValidationError("You have forgotten about Fred!")

        # Always return a value to use as the new cleaned data, even if
        # this method didn't change it.
        return data

Очистка и проверка полей, которые зависят друг от друга¶

Предположим, мы добавим еще одно требование к нашей контактной форме: если поле cc_myself является True, то subject должно содержать слово "help". Мы выполняем проверку более чем одного поля одновременно, поэтому метод формы clean() является хорошим местом для этого. Обратите внимание, что здесь мы говорим о методе clean() на форме, тогда как ранее мы писали метод clean() на поле. Важно четко различать поля и формы, когда мы решаем, где проводить валидацию. Поля — это отдельные точки данных, а формы — это набор полей.

К моменту вызова метода clean() формы будут запущены все методы очистки отдельных полей (предыдущие два раздела), поэтому self.cleaned_data будет заполнен любыми данными, которые сохранились до сих пор. Поэтому вам также нужно помнить о том, что поля, которые вы хотите проверить, могут не выдержать первоначальной проверки отдельных полей.

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

from django import forms
from django.core.exceptions import ValidationError

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super().clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject:
            # Only do something if both fields are valid so far.
            if "help" not in subject:
                raise ValidationError(
                    "Did not send for 'help' in the subject despite "
                    "CC'ing yourself."
                )

В этом коде, если возникает ошибка валидации, форма выводит сообщение об ошибке в верхней части формы (обычно) с описанием проблемы. Такие ошибки являются не-полевыми ошибками, которые отображаются в шаблоне с помощью {{ form.non_field_errors }}.

Вызов super().clean() в коде примера гарантирует, что любая логика валидации в родительских классах будет сохранена. Если ваша форма наследует другую, которая не возвращает словарь cleaned_data в своем методе clean() (это необязательно), то не присваивайте cleaned_data результату вызова super() и используйте self.cleaned_data вместо этого:

def clean(self):
    super().clean()
    cc_myself = self.cleaned_data.get("cc_myself")
    ...

Второй подход для сообщения об ошибках валидации может включать присвоение сообщения об ошибке одному из полей. В данном случае давайте присвоим сообщение об ошибке обеим строкам «subject» и «cc_myself» в отображении формы. Будьте осторожны, делая это на практике, так как это может привести к запутанному выводу формы. Мы показываем, что здесь возможно, и предоставляем вам и вашим дизайнерам самим решать, что будет эффективно работать в вашей конкретной ситуации. Наш новый код (заменяющий предыдущий пример) выглядит следующим образом:

from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super().clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject and "help" not in subject:
            msg = "Must put 'help' in subject when cc'ing yourself."
            self.add_error('cc_myself', msg)
            self.add_error('subject', msg)

Вторым аргументом add_error() может быть строка или, предпочтительно, экземпляр ValidationError. Более подробную информацию смотрите в Поднятие ValidationError. Обратите внимание, что add_error() автоматически удаляет поле из cleaned_data.

In Django forms, it can check whether the form is valid:

if form.is_valid(): 
    return HttpResponseRedirect('/thanks/')

But I’m missing what to do if it isn’t valid? How do I return the form with the error messages? I’m not seeing the «else» in any of the examples.

alias51's user avatar

alias51

7,85922 gold badges90 silver badges162 bronze badges

asked Feb 1, 2013 at 13:48

user984003's user avatar

user984003user984003

27.3k61 gold badges182 silver badges278 bronze badges

If you render the same view when the form is not valid then in template you can access the form errors using form.errors.

{% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            <div class="alert alert-danger">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    {% endfor %}
    {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}
{% endif %}

An example:

def myView(request):
    form = myForm(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
    return render(request, 'my_template.html', {'form': form})

melwil's user avatar

melwil

2,5171 gold badge19 silver badges32 bronze badges

answered Feb 1, 2013 at 13:50

Aamir Rind's user avatar

Aamir RindAamir Rind

38.1k22 gold badges123 silver badges160 bronze badges

6

views.py

from django.contrib import messages 

def view_name(request):
    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks'/)
        else:
            messages.error(request, "Error")
return render(request, 'page.html', {'form':form_class()})

If you want to show the errors of the form other than that not valid just put {{form.as_p}} like what I did below

page.html

<html>
    <head>
        <script>
            {% if messages %}
                {% for message in messages %}
                    alert('{{message}}')
                {% endfor %}
            {% endif %}
        </script>
    </head>
    <body>
        {{form.as_p}}
    </body>
</html> 

Drubio's user avatar

Drubio

1,0883 gold badges14 silver badges29 bronze badges

answered Feb 1, 2013 at 13:51

catherine's user avatar

4

UPDATE:
Added a more detailed description of the formset errors.


Form.errors combines all field and non_field_errors. Therefore you can simplify the html to this:

template

    {% load form_tags %}

    {% if form.errors %}
    <div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
        <div id="form_errors">
            {% for key, value in form.errors.items %}
                <span class="fieldWrapper">
                    {{ key }}:{{ value }}
                </span>
            {% endfor %}
        </div>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    {% endif %}


If you want to generalise it you can create a list_errors.html which you include in every form template. It handles form and formset errors:

    {% if form.errors %}
    <div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
        <div id="form_errors">

            {% for key, value in form.errors.items %}
                <span class="fieldWrapper">
                    {{ key }}:{{ value }}
                </span>
            {% endfor %}
        </div>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    {% elif formset.total_error_count %}
    <div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
        <div id="form_errors">
            {% if formset.non_form_errors %}
                {{ formset.non_form_errors }}
            {% endif %}
            {% for form in formset.forms %}
                {% if form.errors %}
                    Form number {{ forloop.counter }}:
                    <ul class="errorlist">
                    {% for key, error in form.errors.items %}
                        <li>{{form.fields|get_label:key}}
                            <ul class="errorlist">
                                <li>{{error}}</li>
                            </ul>
                        </li>
                    {% endfor %}
                    </ul>
                {% endif %}
            {% endfor %}

        </div>
    </div>

    {% endif %}

form_tags.py

from django import template

register = template.Library()


def get_label(a_dict, key):
    return getattr(a_dict.get(key), 'label', 'No label')


register.filter("get_label", get_label)

One caveat: In contrast to forms Formset.errors does not include non_field_errors.

answered Jan 14, 2020 at 11:10

P. Maino's user avatar

P. MainoP. Maino

1732 silver badges11 bronze badges

def some_view(request):
    if request.method == 'POST':
        form = SomeForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks'/)
    else:
        form = SomeForm()
    return render(request, 'some_form.html', {'form': form})

answered Feb 1, 2013 at 13:58

Lukasz Koziara's user avatar

Lukasz KoziaraLukasz Koziara

4,2645 gold badges32 silver badges43 bronze badges

1

This answer is correct but has a problem: fields not defined.
If you have more then one field, you can not recognize which one has error.

with this change you can display field name:

{% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            <div class="alert alert-danger">
                <strong>{{ field.label }}</strong><span>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    {% endfor %}
    {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}
{% endif %}
 

answered Feb 1, 2021 at 16:56

Chalist's user avatar

ChalistChalist

3,0605 gold badges39 silver badges67 bronze badges

@AamirAdnan’s answer missing field.label; the other way to show the errors in few lines.

{% if form.errors %}
    <!-- Error messaging -->
    <div id="errors">
        <div class="inner">
            <p>There were some errors in the information you entered. Please correct the following:</p>
            <ul>
                {% for field in form %}
                    {% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
                {% endfor %}
            </ul>
        </div>
    </div>
    <!-- /Error messaging -->
{% endif %}

answered Aug 25, 2020 at 7:09

Laxmikant Ratnaparkhi's user avatar

1

simply you can do like this because when you initialized the form in contains form data and invalid data as well:

def some_func(request):
    form = MyForm(request.POST)
    if form.is_valid():
         //other stuff
    return render(request,template_name,{'form':form})

if will raise the error in the template if have any but the form data will still remain as :

error_demo_here

answered Mar 14, 2020 at 5:55

Dinesh Kc's user avatar

You can put simply a flag variable, in this case is_successed.

def preorder_view(request, pk, template_name='preorders/preorder_form.html'):
    is_successed=0
    formset = PreorderHasProductsForm(request.POST)
    client= get_object_or_404(Client, pk=pk)
    if request.method=='POST':
        #populate the form with data from the request
       # formset = PreorderHasProductsForm(request.POST)
        if formset.is_valid():
            is_successed=1
            preorder_date=formset.cleaned_data['preorder_date']
            product=formset.cleaned_data['preorder_has_products']
            return render(request, template_name, {'preorder_date':preorder_date,'product':product,'is_successed':is_successed,'formset':formset})



    return render(request, template_name, {'object':client,'formset':formset})

afterwards in your template you can just put the code below

{%if is_successed == 1 %}
<h1>{{preorder_date}}</h1>
<h2> {{product}}</h2>
{%endif %}

answered Nov 22, 2018 at 13:36

gtopal's user avatar

gtopalgtopal

5047 silver badges31 bronze badges

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.

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.

Проверка форм и полей формы¶

Проверка формы происходит при нормализации её данных. При возникновении необходимости вмешаться в этот процесс, есть много мест, где можно это сделать и которые влияют на разные этапы проверки. Во время обработки формы вызываются три типа методов для нормализации данных. Процесс проверки запускается при вызове метода is_valid() формы. Существуют ситуации, которые запускают нормализацию и проверку данных (обращение к свойству errors или прямой вызов метода full_clean()), но они возникают достаточно редко.

В общем случае, любой нормализующий метод может вызвать исключение ValidationError при наличии проблем с данными, передавая соответствующее сообщение об ошибке в конструктор исключения. Смотрите ниже примеры, как правильно вызывать ValidationError. Если проблем не выявлено, то метод должен возвращать нормализованное значение в виде объекта языка Python.

Большая часть проверок может быть выполнена с помощью validators, которые являются простыми в использовании вспомогательными объектами. Валидатор — это простая функция (или вызываемый объект, callable), которая принимает единственный аргумент и вызывает исключение ValidationError в случае проблем с полученным значением. Валидаторы запускаются после вызова методов поля: to_python и validate.

Проверка формы состоит из нескольких этапов, каждый из которых может быть настроен или переопределён:

  • Вызов метода поля to_python() является первым этапом каждой проверки. Он приводит значение к соответствующему типу данных или вызывает исключение ValidationError, если это невозможно. Метод принимает сырое значение от виджета и возвращает нормализованное значение. Например, поле типа FloatField преобразовывает данные в тип float языка Python или вызывает исключение ValidationError.

  • Метод validate() поля выполняет специфическую для поля проверку данных и приводит значение к правильному типу данных, или вызывает исключение ValidationError на любую ошибку. Этот метод не возвращает значение и не должен изменять проверяемые данные. Если вам надо обеспечить логику, которую невозможно или нежелательно выносить в валидатор, то вам следует переопределить этот метод.

  • Метод поля run_validators() запускает все валидаторы и аккумулирует все возникающие ошибки в одно исключение ValidationError. Вам не стоит переопределять этот метод.

  • Метод clean() поля отвечает за вызов методов to_python(), validate() и run_validators() в правильном порядке и передачу их ошибок. Как только любой из этих методов вызовет исключение ValidationError, процесс проверки прекращается и ошибка передаётся выше. Этот метод возвращает проверенные данные, которые затем помещаются в словарь cleaned_data формы.

  • Для проверки значения поля используется метод clean_<fieldname>(), где <fieldname> заменяется на имя поля. Этот метод выполняет проверку значения. Метод не принимает аргументы. Для получения значения поля обращайтесь к словарю
    self.cleaned_data и помните, что там будет объект языка Python, а не строка, переданная формой (значение находится в cleaned_data т.к. уже была выполнена проверка методом clean() поля).

    Например, если требуется проверить, что содержимое CharField поля с именем serialnumber является уникальным, то метод clean_serialnumber() будет правильным местом для такого функционала. Вам не нужно специальное поле (пусть будет CharField), но требуется хитрая проверка данных и, возможно, очистка/нормализация данных.

    Этот метод должен возвращать очищенное значение, полученное из cleaned_data независимо, изменилось оно или нет.

  • Метод clean() потомка формы. Этот метод может выполнять любую проверку, которая нуждается в одновременном доступе к данным нескольких полей. Именно здесь вы можете проверять, что если поле A заполнено, то поле B должно содержать правильный адрес электронной почты и так далее. Данные, которые возвращает этот метод, помещаются в свойство cleaned_data формы.

    Так как валидация полей выполняется перед вызовом clean(), вы можете получить доступ к атрибуту формы errors, который содержит уже полученные ошибки валидации.

    Следует отметить, что любая ошибка, вызванная методом Form.clean() формы, не будет ассоциирована ни с каким полем. Такие ошибки привязываются к «особому» полю (__all__), доступ к которому можно получить через метод non_field_errors(). Если вам потребуется добавить ошибки к определённому полю формы, используйте add_error().

    Также следует отметить, что существует ряд соглашений, которым необходимо следовать при переопределении метода clean() в вашем классе ModelForm. (Обратитесь к документации на ModelForm для получения подробностей.)

Эти методы вызываются в порядке, указанном выше, по одному полю за раз. Для каждого поля формы (в порядке их определения в классе формы) вызывается сначала метод Field.clean(), затем вызывается метод clean_<fieldname>(). После того, как пара этих методов будет вызвана для каждого поля формы, наступает очередь метода Form.clean() формы. Он будет вызыван в любом случае, даже если предыдущие методы вызывали ошибку.

Примеры для каждого из этих методов показаны ниже.

Как упоминалось ранее, любой из этих методов может вызвать исключение ValidationError. Для любого поля, если его метод clean() вызвал исключение ValidationError, то следующий метод для этого поля не вызывается. Тем не менее, методы для остальных полей отрабатывают в штатном режиме.

Вызов ValidationError

Для удобной работы с ошибками валидации используйте следующие правила:

  • Передайте при создании код ошибки через аргумент code:

    # Good
    ValidationError(_('Invalid value'), code='invalid')
    
    # Bad
    ValidationError(_('Invalid value'))
    
  • Переменные лучше передавать в аргументе params, а в сообщении указать места для подстановки:

    # Good
    ValidationError(
        _('Invalid value: %(value)s'),
        params={'value': '42'},
    )
    
    # Bad
    ValidationError(_('Invalid value: %s') % value)
    
  • Используйте именованные параметры в сообщении. Это позволит использовать переменные в любом параметре при переопределении сообщения:

    # Good
    ValidationError(
        _('Invalid value: %(value)s'),
        params={'value': '42'},
    )
    
    # Bad
    ValidationError(
        _('Invalid value: %s'),
        params=('42',),
    )
    
  • Оберните сообщения в gettext для последующего перевода:

    # Good
    ValidationError(_('Invalid value'))
    
    # Bad
    ValidationError('Invalid value')
    

Все вместе:

raise ValidationError(
    _('Invalid value: %(value)s'),
    code='invalid',
    params={'value': '42'},
)

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

Не рекомендуется, но если вы в конце цепочки валидации(например, метод clean() формы) и никогда не будете переопределять сообщение, можно просто сделать:

ValidationError(_('Invalid value: %s') % value)

Методы Form.errors.as_data() и Form.errors.as_json() используют все возможности ValidationError (включая code и params).

Вызов нескольких ошибок¶

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

Рекомендуется использовать список объектов ValidationError с code и params, но можно использовать просто список строк:

# Good
raise ValidationError([
    ValidationError(_('Error 1'), code='error1'),
    ValidationError(_('Error 2'), code='error2'),
])

# Bad
raise ValidationError([
    _('Error 1'),
    _('Error 2'),
])

Использование проверки на практике¶

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

Использование валидаторов¶

Поля форм (и моделей) Django поддерживают использование простых функций и классов, которые известны как валидаторы. Это просто функция, которая принимает значение и ничего не возвращает, если значение верно, иначе вызывает ValidationError. Они могут быть переданы в конструктор поля через аргумент validators или определены в самом классе поля Field с помощью атрибута default_validators.

Простые валидаторы могут использоваться для проверки значений внутри полей. Давайте рассмотрим SlugField:

from django.forms import CharField
from django.core import validators

class SlugField(CharField):
    default_validators = [validators.validate_slug]

Как можно увидеть SlugField — это обычное поле CharField, которое имеет валидатор, проверяющий вводимое значение на допустимые символы. Все это можно указать при определении поля:

эквивалентно:

slug = forms.CharField(validators=[validators.validate_slug])

Обычные проверки, такие как проверка email или по регулярному выражению, можно выполнить используя существующие валидаторы Django. Например, validators.validate_slug экземпляр RegexValidator с первым аргументом равным ^[-a-zA-Z0-9_]+$. Подробности смотрите в разделе о создании валидаторов.

Встроенная проверка поля формы¶

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

from django import forms
from django.core.validators import validate_email

class MultiEmailField(forms.Field):
    def to_python(self, value):
        "Normalize data to a list of strings."

        # Return an empty list if no input was given.
        if not value:
            return []
        return value.split(',')

    def validate(self, value):
        "Check if value consists only of valid emails."

        # Use the parent's handling of required fields, etc.
        super(MultiEmailField, self).validate(value)

        for email in value:
            validate_email(email)

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

Давайте создадим простую форму ContactForm, чтобы показать как можно использовать это поле:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    recipients = MultiEmailField()
    cc_myself = forms.BooleanField(required=False)

Просто используем MultiEmailField как и любое другое поле. При вызове метода формы is_valid() происходит вызов метода MultiEmailField.clean(), который в свою очередь вызовет собственные методы to_python() и validate().

Проверка атрибута определённого поля¶

Продолжая работать над нашим примером, предположим, что на форме ContactForm поле электронной почты recipients всегда должно содержать адрес «fred@example.com». Эта проверка будет особенностью нашей формы, следовательно, нам не надо её помещать в класс MultiEmailField. Вместо этого мы напишем метод, который будет проверять поле recipients:

from django import forms

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

Очистка и проверка полей, которые зависят друг от друга¶

Допустим, что мы добавили ещё одно требование для нашей формы: если поле cc_myself равно True, то поле subject должно содержать слово «help». Раз мы выполняем проверку нескольких полей, то метод формы clean() будет правильным местом для нашего кода. Обратите внимание, мы сейчас говорим о методе clean() формы, а раньше говорили о методе clean() поля. Важно понимать разницу между ними при реализации алгоритма проверки данных. Поля содержат один источник данных, а формы — это коллекции полей.

К моменту вызова метода формы clean() все clean() методы полей уже отработали. Таким образом, свойство формы self.cleaned_data будет заполнено данными, прошедшими проверку. Следовательно, надо принять во внимание возможность того, что данные некоторых полей не прошли начальную поверку.

Существует два способа сообщить об ошибках на этом этапе. Обычно ошибку отображают сверху формы. Для этого достаточно вызвать исключение ValidationError в методе формы clean(). Например:

from django import forms

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:
            # Only do something if both fields are valid so far.
            if "help" not in subject:
                raise forms.ValidationError(
                    "Did not send for 'help' in the subject despite "
                    "CC'ing yourself."
                )

В данном коде, при возникновении ошибки во время проверки данных, форма отобразит сообщение об ошибке сверху (обычное поведение), описывая проблему.

Вызов super(ContactForm, self).clean() обеспечивает проверку данных в родительском классе. Если ваша форма наследуется от класса, который не возвращает словарь cleaned_data из метода clean() (это не обязательно), не записывайте в cleaned_data результат вызова super() и используйте вместо этого self.cleaned_data:

def clean(self):
    super(ContactForm, self).clean()
    cc_myself = self.cleaned_data.get("cc_myself")
    ...

Второй способ подразумевает назначение ошибки одному из полей. В нашем случае, давайте назначим сообщение об ошибке обоим полям («subject» и «cc_myself») при отображении формы. Использовать этот способ надо аккуратно, так как он может запутать пользователя. Мы лишь показываем возможные варианты, оставляя решение конкретной задачи вам и вашим дизайнерам. Наш новый код (заменяющий предыдущий пример) выглядит так:

from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super(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:
            msg = "Must put 'help' in subject when cc'ing yourself."
            self.add_error('cc_myself', msg)
            self.add_error('subject', msg)

Вторым аргументом add_error() может быть просто строка, но лучше объект ValidationError. Подробности смотрите в Вызов ValidationError. Обратите внимание, add_error() автоматически убирает поле из cleaned_data.

In this post we’ll learn to create user-defined functions, displaying validation errors in the template for Django Form Validations.

Table Of Contents

  • Introduction
  • Creating Form
  • Rendering Form
  • Saving Form
  • Form Validation User-Defined Functions
  • Conclusion

Introduction

The forms are a Django Module which deals with all form-related functions from binding POST data to form, Validating form and rendering HTML field in the template.
We’ll be using below models.py file as an example to demonstrate form validations.

from django.db import models
from django.contrib.auth.models import User
from datetime import datetime

class AuthUserProfile(models.Model):
    user_profile_id = models.AutoField(primary_key=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='auth_user_profile')
    dob =  models.DateField(blank=True, null=True)
    is_deleted = models.PositiveSmallIntegerField(default=0)
    created_at = models.DateTimeField(auto_now=datetime.now(), null=True)
    updated_at = models.DateTimeField(auto_now=datetime.now(), null=True)

    class Meta():
        db_table = 'auth_user_profile'
        verbose_name = 'User Profile'
        verbose_name_plural = 'User Profiles'

    def __str__(self):
        return self.user

Create a form which has these fields (first_name, last_name, username, password, email) from User models and field (dob) in AuthUserProfile Model and also will add custom field and non-field level validation.

Creating Form

In forms.py file import forms from Django. Inherit forms.Form to UserForm and add attributes to the field.

from django import forms
from datetime import datetime
from django.contrib.auth.models import User

class UserForm(forms.Form):
    first_name = forms.CharField(label="First Name*",widget=forms.TextInput(attrs={'required':True,'class':"form-control"}))
    last_name = forms.CharField(label="Last Name*",widget=forms.TextInput(attrs={'required':True,'class':"form-control"}))
    username = forms.CharField(label="User Name*",widget=forms.TextInput(attrs={'required':True,'class':"form-control"}))
    email = forms.CharField(label="Email",widget=forms.TextInput(attrs={'type':'email','required':False,'class':"form-control"}))
    date_of_birth = forms.CharField(label="Date of Birth",widget=forms.TextInput(attrs={'type':'date','required':True,'class':"form-control"}))
    password = forms.CharField(label="Password*",widget=forms.TextInput(attrs={'required':True,'class':"form-control", 'type' : "password"}))
    confirm_password = forms.CharField(label="Confirm Password*",widget=forms.TextInput(attrs={'required':True,'class':"form-control", 'type' : "password"}))
    
    def clean(self):
        # user age must be above 18 to register
        if self.cleaned_data.get('date_of_birth'):
            dob = datetime.strptime(self.cleaned_data.get('date_of_birth'),"%Y-%m-%d")
            now = datetime.now()
            diff = now.year-dob.year

            if diff < 18: msg="User must be atleast 18 years old" self.add_error(None, msg) #check if user name is unique username_count = User.objects.filter(username=self.cleaned_data.get('username')).count() if username_count>0:
            msg="Username '{}' has already been used.".format(self.cleaned_data.get('username'))
            self.add_error(None, msg)
        
    def clean_confirm_password(self):
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if confirm_password!=password:
            msg = "Password and Confirm Passwords must match."
            self.add_error('confirm_password', msg)

You may notice clean() and clean_confirm_password() methods in UserForm the form they are validation methods.
The clean() the method is form level validation this can also be used to perform field-level validation.

And the clean_confirm_password() is a field-level validation for confirm_password the field it checks if confirm_password!=password then adds error to a then particular field.

Rendering Form

Rendering of forms is an easy part we must pass the form object as an argument to render function.

In views.py create a function user_profile_create which will display rendered form.

from django.contrib.auth.models import User
from users.models import AuthUserProfile
from forms.forms import UserForm
from django.contrib.auth.hashers import make_password
from django.contrib import messages

def user_profile_create(request):
    form = UserForm()
    template="forms/user_profile_create_form.html"
    return render(request,template,{"form":form})

form = UserForm() creates form object of UserForm and is passed as an argument to the render() function.

In urls.py file add routes to view.

urlpatterns = [
    path('user/profile/create', views.user_profile_create, name='user-profile-create'),
]

Create an HTML file in your apps template folder naming user_profile_create_form.html.

<!DOCTYPE html>
<html lang="en">            
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Django Form Validation</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
        <style>
            .error{
                color:red;
            }
        </style>
    </head>            
    <body>
        <div class="container">
        
            {% if messages %}
                {% for message in messages %}
                    {% if message.level == DEFAULT_MESSAGE_LEVELS.SUCCESS %}
                    <div class="alert alert-success"
                    role="alert">
                        <div id="primary-notification-div">
                            {{ message }}
                        </div>
                    </div>
                    {% endif %}
                {% endfor %}
            {% endif %}
                
            <h1>User Profile</h1>
            <form action="{% url 'forms:user-profile-save' %}" method="post">
                {% csrf_token %}
    
                {% if form.errors %}
                    {% for error in form.non_field_errors %}
                        <div class="alert alert-danger">
                            <strong>{{ error|escape }}</strong>
                        </div>
                    {% endfor %}
    
                {% endif %}
    
    
                <div class="row">
                    <div class="col-md-3">
                        {{form.first_name.label}}
                        {{form.first_name}}
    
                        {% if form.errors.first_name %}
                            <label for="" class="error">{{form.errors.first_name|striptags}}</label>
                        {% endif %}
                    </div>
    
                    <div class="col-md-3">
                        {{form.last_name.label}}
                        {{form.last_name}}
                        {% if form.errors.last_name %}
                            <label for="" class="error">{{form.errors.last_name|striptags}}</label>
                        {% endif %}
                    </div>
    
                    <div class="col-md-3">
                        {{form.username.label}}
                        {{form.username}}
                        {% if form.errors.username %}
                            <label for="" class="error">{{form.errors.username|striptags}}</label>
                        {% endif %}
                    </div>
    
                    <div class="col-md-3">
                        {{form.email.label}}
                        {{form.email}}
                        {% if form.errors.email %}
                            <label for="" class="error">{{form.errors.email|striptags}}</label>
                        {% endif %}
                    </div>
    
                    <div class="col-md-3">
                        {{form.date_of_birth.label}}
                        {{form.date_of_birth}}
                        {% if form.errors.date_of_birth %}
                            <label for="" class="error">{{form.errors.date_of_birth|striptags}}</label>
                        {% endif %}
                    </div>
                </div>
    
                <div class="row" style="margin-top: 25px;">
                    <div class="col-md-3">
                        {{form.password.label}}
                        {{form.password}}
                        {% if form.errors.password %}
                            <label for="" class="error">{{form.errors.password|striptags}}</label>
                        {% endif %}
                    </div>
                </div>
    
                <div class="row" style="margin-top: 25px;">
    
                    <div class="col-md-3">
                        {{form.confirm_password.label}}
                        {{form.confirm_password}}
                        {% if form.errors.confirm_password %}
                        <label for="" class="error">{{form.errors.confirm_password|striptags}}</label>
                        {% endif %}
                    </div>
    
                    <div class="col-md-12" style="margin-top: 25px;">
                        <input type="submit" class="btn btn-sm btn-primary" value="submit">
                    </div>
                </div>
            </form>
        </div>
    </body>                
</html>

This is how our form will look when we go to route user/profile/create.

User Profile Form

  • The message displays success message once messages.add_message(request, messages.SUCCESS, ".....") is called it is just like the flash message.
  • The form.errors is called on validation has failed.
  • The form.non_field_errors display errors on top of form this errors are not associated to a particular field.
  • The form.errors. displays the error of the particular field.

This is how errors are displayed in the form.

User Profile Form Displaying Validation Errors

Saving Form

In urls.py file add routes to save the form.

urlpatterns = [
    path('user/profile/save', views.user_profile_create, name='user-profile-save'),
]

In views.py file add function user_profile_save() to save form data.

def user_profile_save(request):

    form = UserForm(request.POST)

    if form.is_valid():

        query = {
            "first_name" : form.cleaned_data.get('first_name'),
            "last_name" : form.cleaned_data.get('last_name'),
            "username" : form.cleaned_data.get('username'),
            "password" : make_password(form.cleaned_data.get('password')),
            "email" : form.cleaned_data.get('email'),
            "is_superuser" : 0,
            "is_staff" : 1,
            "is_active" : 1,
        }

        user = User.objects.create(**query)
        
        query={
            "user_id" : user.id,
            "dob" : form.cleaned_data.get('dob'),
        }
        
        AuthUserProfile.objects.create(**query)
        
        messages.add_message(request, messages.SUCCESS, "User Profile created successfully.")
        
        return HttpResponseRedirect(reverse('forms:user-profile-create'))
    
    template="forms/user_profile_create_form.html"
    
    return render(request,template,{"form":form})

The request.POST is passed to UserForm(request.POST) this binds the submitted data to Form Class.
The form.is_valid() returns a Boolean value if True then the form is clean and if False then there may be validation error.
To view validation errors after .is_valid() method we can print form.errors to view validation errors.

Calling form.cleaned_data.get('') gives use of the sanitized value to that field. Inside .is_valid() we have called model methods to save form data.

Showing success message on successfully validating form and saving its contents into the database

Form Validation User-Defined functions

To defined a custom validation function in Form Class name function with prefix clean followed by underscore and field name which must be validated.

Example

def clean_first_name(self):
    pass #this validates field first_name

def clean_username(self):
    pass #this validates field username

If the value of the field is not as expected that you can raise validation error or add error by mentioning field name self.add_error('field_name', "Error Message").
If you want to raise non-field error than set the first argument of add_error() method None followed by the message you want to be displayed.

self.add_error(None, msg) #this creates a non-field error

Conclusion

We have come to the end of our post on Django Form Validation.
If you have any doubts or suggestions please mention in the comments section and we’ll reach you soon and we would also love to hear requests and your recommendations for new tutorials/posts.

Related Posts

  • Python Django Forms | Creating, Rendering, Validating and Saving Forms
  • Django – Multiple Files Validation and Uploads

Summary

Review Date

2020-06-15

Reviewed Item

Django Forms | Custom Form Validations

Author Rating

51star1star1star1star1star

Software Name

Django Web Framework

Software Name

Windows Os, Mac Os, Ubuntu Os

Software Category

Web Development

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Django admin ошибка проверки csrf запрос отклонен
  • Dixion h100b ошибка 01 пульсоксиметр