Cleaned data django что это
Перейти к содержимому

Cleaned data 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:

Don’t coerce variables into the message; use placeholders and the params argument of the constructor:

Use mapping keys instead of positional formatting. This enables putting the variables in any order or omitting them altogether when rewriting the message:

Wrap the message with gettext to enable translation:

Putting it all together:

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:

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

Raising multiple errors¶

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

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

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 :

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:

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:

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:

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:

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:

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:

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:

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 .

What is the use of cleaned_data in Django

Django says if form.is_valid() is True . form.cleaned_data is where all validated fields are stored. But I am confused about using the cleaned_data function.

form.cleaned_data[‘f1’] — cleaned data request.POST.get(‘f1’) — un-validated data

I have a model form in Django.

Does this save cleaned_data to the model or does it save unvalidated data.

Does form2 contain form1’s cleaned_data or unvalidated data.

Apart from converting any date to python datetime object, is there a good example of benefit of using cleaned_data vs unvalidated data. Thanks

2 Answers 2

form.cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects.

form.data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).

Example by code

In my forms.py I have two fields:

and in my views.py :

The above code prints the following output:

If instead views.py contains:

The above code prints the following:

There 2 situations: using basic Form (forms.Form) and ModelForm (forms.ModelForm).

If you are using a ModelForm then there is no any need of playing with a cleaned_data dictionary because when you do form.save() it is already be matched and the clean data is saved. But you are using basic Form then you have to manually match each cleaned_data to its database place and then save the instance to the database not the form.

For example basic Form:

For example ModelForm:

NOTE: If the form pass from is_valid() stage then there is no any unvalidated data.

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

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

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

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

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

to_python() Метод на Field первый шаг в каждой проверке. Он приводит значение к правильному типу данных и повышает, ValidationError если это невозможно. Этот метод принимает исходное значение из виджета и возвращает преобразованное значение. Например, a 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 потому что общий clean() метод поля , описанный выше, уже очистил данные один раз).

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

Возвращаемое значение этого метода заменяет существующее значение в cleaned_data , поэтому оно должно быть значением поля из 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 . Для любого поля, если Field.clean() метод вызывает a ValidationError , никакой метод очистки для конкретного поля не вызывается. Однако методы очистки для всех остальных полей по-прежнему выполняются.

Повышение ValidationError ¶

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

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

Не вводите переменные в сообщение; используйте заполнители и params аргумент конструктора:

Используйте ключи сопоставления вместо позиционного форматирования. Это позволяет размещать переменные в любом порядке или вообще их опускать при перезаписи сообщения:

Оберните сообщение, gettext чтобы включить перевод:

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

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

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

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

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

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

Как и выше, рекомендуется передавать список ValidationError экземпляров с помощью code s, params но список строк также будет работать:

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

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

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

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

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

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

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

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

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

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

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

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

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

Продолжая предыдущий пример, предположим, что в нашем ContactForm мы хотим убедиться, что recipients поле всегда содержит адрес «[email protected]» . Это проверка, специфичная для нашей формы, поэтому мы не хотим помещать ее в общий MultiEmailField класс. Вместо этого мы пишем метод очистки, который работает с recipients полем, например:

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

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

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

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

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

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

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

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

The Forms API¶

This document covers the gritty details of Django’s forms API. You should read the introduction to working with forms first.

Bound and unbound forms¶

A Form instance is either bound to a set of data, or unbound.

  • If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
  • If it’s unbound, it cannot do validation (because there’s no data to validate!), but it can still render the blank form as HTML.

To create an unbound Form instance, instantiate the class:

To bind data to a form, pass the data as a dictionary as the first parameter to your Form class constructor:

In this dictionary, the keys are the field names, which correspond to the attributes in your Form class. The values are the data you’re trying to validate. These will usually be strings, but there’s no requirement that they be strings; the type of data you pass depends on the Field , as we’ll see in a moment.

If you need to distinguish between bound and unbound form instances at runtime, check the value of the form’s is_bound attribute:

Note that passing an empty dictionary creates a bound form with empty data:

If you have a bound Form instance and want to change the data somehow, or if you want to bind an unbound Form instance to some data, create another Form instance. There is no way to change data in a Form instance. Once a Form instance has been created, you should consider its data immutable, whether it has data or not.

Using forms to validate data¶

Implement a clean() method on your Form when you must add custom validation for fields that are interdependent. See Cleaning and validating fields that depend on each other for example usage.

The primary task of a Form object is to validate data. With a bound Form instance, call the is_valid() method to run validation and return a boolean designating whether the data was valid:

Let’s try with some invalid data. In this case, subject is blank (an error, because all fields are required by default) and sender is not a valid email address:

Access the errors attribute to get a dictionary of error messages:

In this dictionary, the keys are the field names, and the values are lists of strings representing the error messages. The error messages are stored in lists because a field can have multiple error messages.

You can access errors without having to call is_valid() first. The form’s data will be validated the first time either you call is_valid() or access errors .

The validation routines will only get called once, regardless of how many times you access errors or call is_valid() . This means that if validation has side effects, those side effects will only be triggered once.

Returns a dict that maps fields to their original ValidationError instances.

Use this method anytime you need to identify an error by its code . This enables things like rewriting the error’s message or writing custom logic in a view when a given error is present. It can also be used to serialize the errors in a custom format (e.g. XML); for instance, as_json() relies on as_data() .

The need for the as_data() method is due to backwards compatibility. Previously ValidationError instances were lost as soon as their rendered error messages were added to the Form.errors dictionary. Ideally Form.errors would have stored ValidationError instances and methods with an as_ prefix could render them, but it had to be done the other way around in order not to break code that expects rendered error messages in Form.errors .

Form.errors. as_json ( escape_html = False

Returns the errors serialized as JSON.

By default, as_json() does not escape its output. If you are using it for something like AJAX requests to a form view where the client interprets the response and inserts errors into the page, you’ll want to be sure to escape the results on the client-side to avoid the possibility of a cross-site scripting attack. You can do this in JavaScript with element.textContent = errorText or with jQuery’s $(el).text(errorText) (rather than its .html() function).

If for some reason you don’t want to use client-side escaping, you can also set escape_html=True and error messages will be escaped so you can use them directly in HTML.

Form.errors. get_json_data ( escape_html = False

Returns the errors as a dictionary suitable for serializing to JSON. Form.errors.as_json() returns serialized JSON, while this returns the error data before it’s serialized.

The escape_html parameter behaves as described in Form.errors.as_json() .

Form. add_error ( field , error

This method allows adding errors to specific fields from within the Form.clean() method, or from outside the form altogether; for instance from a view.

The field argument is the name of the field to which the errors should be added. If its value is None the error will be treated as a non-field error as returned by Form.non_field_errors() .

The error argument can be a string, or preferably an instance of ValidationError . See Raising ValidationError for best practices when defining form errors.

Note that Form.add_error() automatically removes the relevant field from cleaned_data .

Form. has_error ( field , code = None

This method returns a boolean designating whether a field has an error with a specific error code . If code is None , it will return True if the field contains any errors at all.

To check for non-field errors use NON_FIELD_ERRORS as the field parameter.

This method returns the list of errors from Form.errors that aren’t associated with a particular field. This includes ValidationError s that are raised in Form.clean() and errors added using Form.add_error(None, ". ") .

Behavior of unbound forms¶

It’s meaningless to validate a form with no data, but, for the record, here’s what happens with unbound forms:

Initial form values¶

Use initial to declare the initial value of form fields at runtime. For example, you might want to fill in a username field with the username of the current session.

To accomplish this, use the initial argument to a Form . This argument, if given, should be a dictionary mapping field names to initial values. Only include the fields for which you’re specifying an initial value; it’s not necessary to include every field in your form. For example:

These values are only displayed for unbound forms, and they’re not used as fallback values if a particular value isn’t provided.

If a Field defines initial and you include initial when instantiating the Form , then the latter initial will have precedence. In this example, initial is provided both at the field level and at the form instance level, and the latter gets precedence:

Returns the initial data for a form field. It retrieves the data from Form.initial if present, otherwise trying Field.initial . Callable values are evaluated.

It is recommended to use BoundField.initial over get_initial_for_field() because BoundField.initial has a simpler interface. Also, unlike get_initial_for_field() , BoundField.initial caches its values. This is useful especially when dealing with callables whose return values can change (e.g. datetime.now or uuid.uuid4 ):

Checking which form data has changed¶

Use the has_changed() method on your Form when you need to check if the form data has been changed from the initial data.

When the form is submitted, we reconstruct it and provide the original data so that the comparison can be done:

has_changed() will be True if the data from request.POST differs from what was provided in initial or False otherwise. The result is computed by calling Field.has_changed() for each field in the form.

The changed_data attribute returns a list of the names of the fields whose values in the form’s bound data (usually request.POST ) differ from what was provided in initial . It returns an empty list if no data differs.

Accessing the fields from the form¶

You can access the fields of Form instance from its fields attribute:

You can alter the field and BoundField of Form instance to change the way it is presented in the form:

Beware not to alter the base_fields attribute because this modification will influence all subsequent ContactForm instances within the same Python process:

Accessing “clean” data¶

Each field in a Form class is responsible not only for validating data, but also for “cleaning” it – normalizing it to a consistent format. This is a nice feature, because it allows data for a particular field to be input in a variety of ways, always resulting in consistent output.

For example, DateField normalizes input into a Python datetime.date object. Regardless of whether you pass it a string in the format ‘1994-07-15’ , a datetime.date object, or a number of other formats, DateField will always normalize it to a datetime.date object as long as it’s valid.

Once you’ve created a Form instance with a set of data and validated it, you can access the clean data via its cleaned_data attribute:

Note that any text-based field – such as CharField or EmailField – always cleans the input into a string. We’ll cover the encoding implications later in this document.

If your data does not validate, the cleaned_data dictionary contains only the valid fields:

cleaned_data will always only contain a key for fields defined in the Form , even if you pass extra data when you define the Form . In this example, we pass a bunch of extra fields to the ContactForm constructor, but cleaned_data contains only the form’s fields:

When the Form is valid, cleaned_data will include a key and value for all its fields, even if the data didn’t include a value for some optional fields. In this example, the data dictionary doesn’t include a value for the nick_name field, but cleaned_data includes it, with an empty value:

In this above example, the cleaned_data value for nick_name is set to an empty string, because nick_name is CharField , and CharField s treat empty values as an empty string. Each field type knows what its “blank” value is – e.g., for DateField , it’s None instead of the empty string. For full details on each field’s behavior in this case, see the “Empty value” note for each field in the “Built-in Field classes” section below.

You can write code to perform validation for particular form fields (based on their name) or for the form as a whole (considering combinations of various fields). More information about this is in Form and field validation .

Outputting forms as HTML¶

The second task of a Form object is to render itself as HTML. To do so, print it:

If the form is bound to data, the HTML output will include that data appropriately. For example, if a field is represented by an <input type="text"> , the data will be in the value attribute. If a field is represented by an <input type="checkbox"> , then that HTML will include checked if appropriate:

This default output is a two-column HTML table, with a <tr> for each field. Notice the following:

  • For flexibility, the output does not include the <table> and </table> tags, nor does it include the <form> and </form> tags or an <input type="submit"> tag. It’s your job to do that.
  • Each field type has a default HTML representation. CharField is represented by an <input type="text"> and EmailField by an <input type="email"> . BooleanField(null=False) is represented by an <input type="checkbox"> . Note these are merely sensible defaults; you can specify which HTML to use for a given field by using widgets, which we’ll explain shortly.
  • The HTML name for each tag is taken directly from its attribute name in the ContactForm class.
  • The text label for each field – e.g. ‘Subject:’ , ‘Message:’ and ‘Cc myself:’ is generated from the field name by converting all underscores to spaces and upper-casing the first letter. Again, note these are merely sensible defaults; you can also specify labels manually.
  • Each text label is surrounded in an HTML <label> tag, which points to the appropriate form field via its id . Its id , in turn, is generated by prepending ‘id_’ to the field name. The id attributes and <label> tags are included in the output by default, to follow best practices, but you can change that behavior.
  • The output uses HTML5 syntax, targeting <!DOCTYPE html> . For example, it uses boolean attributes such as checked rather than the XHTML style of checked=’checked’ .

Although <table> output is the default output style when you print a form, other output styles are available. Each style is available as a method on a form object, and each rendering method returns a string.

Default rendering¶

The default rendering when you print a form uses the following methods and attributes.

template_name ¶

The name of the template rendered if the form is cast into a string, e.g. via print(form) or in a template via << form >> .

By default, a property returning the value of the renderer’s form_template_name . You may set it as a string template name in order to override that for a particular form class.

In older versions template_name defaulted to the string value ‘django/forms/default.html’ .

render() ¶

The render method is called by __str__ as well as the Form.as_table() , Form.as_p() , and Form.as_ul() methods. All arguments are optional and default to:

  • template_name : Form.template_name
  • context : Value returned by Form.get_context()
  • renderer : Value returned by Form.default_renderer

By passing template_name you can customize the template used for just a single call.

get_context() ¶

Return the template context for rendering the form.

The available context is:

  • form : The bound form.
  • fields : All bound fields, except the hidden fields.
  • hidden_fields : All hidden bound fields.
  • errors : All non field related or hidden field related form errors.
template_name_label ¶

The template used to render a field’s <label> , used when calling BoundField.label_tag() / legend_tag() . Can be changed per form by overriding this attribute or more generally by overriding the default template, see also Overriding built-in form templates .

Output styles¶

As well as rendering the form directly, such as in a template with << form >> , the following helper functions serve as a proxy to Form.render() passing a particular template_name value.

These helpers are most useful in a template, where you need to override the form renderer or form provided value but cannot pass the additional parameter to render() . For example, you can render a form as an unordered list using << form.as_ul >> .

Each helper pairs a form method with an attribute giving the appropriate template name.

as_div() ¶

The template used by as_div() . Default: ‘django/forms/div.html’ .

as_div() renders the form as a series of <div> elements, with each <div> containing one field, such as:

… gives HTML like:

Of the framework provided templates and output styles, as_div() is recommended over the as_p() , as_table() , and as_ul() versions as the template implements <fieldset> and <legend> to group related inputs and is easier for screen reader users to navigate.

The template used by as_p() . Default: ‘django/forms/p.html’ .

as_p() renders the form as a series of <p> tags, with each <p> containing one field:

as_ul() ¶

The template used by as_ul() . Default: ‘django/forms/ul.html’ .

as_ul() renders the form as a series of <li> tags, with each <li> containing one field. It does not include the <ul> or </ul> , so that you can specify any HTML attributes on the <ul> for flexibility:

as_table() ¶

The template used by as_table() . Default: ‘django/forms/table.html’ .

as_table() renders the form as an HTML <table> :

Styling required or erroneous form rows¶

It’s pretty common to style form rows and fields that are required or have errors. For example, you might want to present required form rows in bold and highlight errors in red.

The Form class has a couple of hooks you can use to add class attributes to required rows or to rows with errors: set the Form.error_css_class and/or Form.required_css_class attributes:

Once you’ve done that, rows will be given "error" and/or "required" classes, as needed. The HTML will look something like:

Configuring form elements’ HTML id attributes and <label> tags¶

By default, the form rendering methods include:

  • HTML id attributes on the form elements.
  • The corresponding <label> tags around the labels. An HTML <label> tag designates which label text is associated with which form element. This small enhancement makes forms more usable and more accessible to assistive devices. It’s always a good idea to use <label> tags.

The id attribute values are generated by prepending id_ to the form field names. This behavior is configurable, though, if you want to change the id convention or remove HTML id attributes and <label> tags entirely.

Use the auto_id argument to the Form constructor to control the id and label behavior. This argument must be True , False or a string.

If auto_id is False , then the form output will not include <label> tags nor id attributes:

If auto_id is set to True , then the form output will include <label> tags and will use the field name as its id for each form field:

If auto_id is set to a string containing the format character ‘%s’ , then the form output will include <label> tags, and will generate id attributes based on the format string. For example, for a format string ‘field_%s’ , a field named subject will get the id value ‘field_subject’ . Continuing our example:

If auto_id is set to any other true value – such as a string that doesn’t include %s – then the library will act as if auto_id is True .

By default, auto_id is set to the string ‘id_%s’ .

A translatable string (defaults to a colon ( : ) in English) that will be appended after any label name when a form is rendered.

It’s possible to customize that character, or omit it entirely, using the label_suffix parameter:

Note that the label suffix is added only if the last character of the label isn’t a punctuation character (in English, those are . , ! , ? or : ).

Fields can also define their own label_suffix . This will take precedence over Form.label_suffix . The suffix can also be overridden at runtime using the label_suffix parameter to label_tag() / legend_tag() .

When set to True (the default), required form fields will have the required HTML attribute.

Formsets instantiate forms with use_required_attribute=False to avoid incorrect browser validation when adding and deleting forms from a formset.

Configuring the rendering of a form’s widgets¶

Specifies the renderer to use for the form. Defaults to None which means to use the default renderer specified by the FORM_RENDERER setting.

You can set this as a class attribute when declaring your form or use the renderer argument to Form.__init__() . For example:

Notes on field ordering¶

In the as_p() , as_ul() and as_table() shortcuts, the fields are displayed in the order in which you define them in your form class. For example, in the ContactForm example, the fields are defined in the order subject , message , sender , cc_myself . To reorder the HTML output, change the order in which those fields are listed in the class.

There are several other ways to customize the order:

By default Form.field_order=None , which retains the order in which you define the fields in your form class. If field_order is a list of field names, the fields are ordered as specified by the list and remaining fields are appended according to the default order. Unknown field names in the list are ignored. This makes it possible to disable a field in a subclass by setting it to None without having to redefine ordering.

You can also use the Form.field_order argument to a Form to override the field order. If a Form defines field_order and you include field_order when instantiating the Form , then the latter field_order will have precedence.

Form. order_fields ( field_order

You may rearrange the fields any time using order_fields() with a list of field names as in field_order .

How errors are displayed¶

If you render a bound Form object, the act of rendering will automatically run the form’s validation if it hasn’t already happened, and the HTML output will include the validation errors as a <ul class="errorlist"> near the field. The particular positioning of the error messages depends on the output method you’re using:

Customizing the error list format¶

By default, forms use django.forms.utils.ErrorList to format validation errors. ErrorList is a list like object where initlist is the list of errors. In addition this class has the following attributes and methods.

The CSS classes to be used when rendering the error list. Any provided classes are added to the default errorlist class.

Specifies the renderer to use for ErrorList . Defaults to None which means to use the default renderer specified by the FORM_RENDERER setting.

The name of the template used when calling __str__ or render() . By default this is ‘django/forms/errors/list/default.html’ which is a proxy for the ‘ul.html’ template.

The name of the template used when calling as_text() . By default this is ‘django/forms/errors/list/text.html’ . This template renders the errors as a list of bullet points.

The name of the template used when calling as_ul() . By default this is ‘django/forms/errors/list/ul.html’ . This template renders the errors in <li> tags with a wrapping <ul> with the CSS classes as defined by error_class .

Return context for rendering of errors in a template.

The available context is:

  • errors : A list of the errors.
  • error_class : A string of CSS classes.

The render method is called by __str__ as well as by the as_ul() method.

All arguments are optional and will default to:

  • template_name : Value returned by template_name
  • context : Value returned by get_context()
  • renderer : Value returned by renderer

Renders the error list using the template defined by template_name_text .

Renders the error list using the template defined by template_name_ul .

If you’d like to customize the rendering of errors this can be achieved by overriding the template_name attribute or more generally by overriding the default template, see also Overriding built-in form templates .

Rendering of ErrorList was moved to the template engine.

Deprecated since version 4.0: The ability to return a str when calling the __str__ method is deprecated. Use the template engine instead which returns a SafeString .

More granular output¶

The as_p() , as_ul() , and as_table() methods are shortcuts – they’re not the only way a form object can be displayed.

Used to display HTML or access attributes for a single field of a Form instance.

The __str__() method of this object displays the HTML for this field.

To retrieve a single BoundField , use dictionary lookup syntax on your form using the field’s name as the key:

To retrieve all BoundField objects, iterate the form:

The field-specific output honors the form object’s auto_id setting:

Attributes of BoundField ¶

The HTML ID attribute for this BoundField . Returns an empty string if Form.auto_id is False .

This property returns the data for this BoundField extracted by the widget’s value_from_datadict() method, or None if it wasn’t given:

A list-like object that is displayed as an HTML <ul class="errorlist"> when printed:

The form Field instance from the form class that this BoundField wraps.

The Form instance this BoundField is bound to.

The help_text of the field.

The name that will be used in the widget’s HTML name attribute. It takes the form prefix into account.

Use this property to render the ID of this field. For example, if you are manually constructing a <label> in your template (despite the fact that label_tag() / legend_tag() will do this for you):

By default, this will be the field’s name prefixed by id_ (” id_my_field ” for the example above). You may modify the ID by setting attrs on the field’s widget. For example, declaring a field like this:

and using the template above, would render something like:

Use BoundField.initial to retrieve initial data for a form field. It retrieves the data from Form.initial if present, otherwise trying Field.initial . Callable values are evaluated. See Initial form values for more examples.

BoundField.initial caches its return value, which is useful especially when dealing with callables whose return values can change (e.g. datetime.now or uuid.uuid4 ):

Returns True if this BoundField ’s widget is hidden.

The label of the field. This is used in label_tag() / legend_tag() .

The name of this field in the form:

Returns the value of this BoundField widget’s use_fieldset attribute.

Returns the lowercased class name of the wrapped field’s widget, with any trailing input or widget removed. This may be used when building forms where the layout is dependent upon the widget type. For example:

Methods of BoundField ¶

Returns a string of HTML for representing this as an <input type="hidden"> .

**kwargs are passed to as_widget() .

This method is primarily used internally. You should use a widget instead.

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

Renders the field by rendering the passed widget, adding any HTML attributes passed as attrs . If no widget is specified, then the field’s default widget will be used.

only_initial is used by Django internals and should not be set explicitly.

BoundField. css_classes ( extra_classes = None

When you use Django’s rendering shortcuts, CSS classes are used to indicate required form fields or fields that contain errors. If you’re manually rendering a form, you can access these CSS classes using the css_classes method:

If you want to provide some additional classes in addition to the error and required classes that may be required, you can provide those classes as an argument:

Renders a label tag for the form field using the template specified by Form.template_name_label .

The available context is:

  • field : This instance of the BoundField .
  • contents : By default a concatenated string of BoundField.label and Form.label_suffix (or Field.label_suffix , if set). This can be overridden by the contents and label_suffix arguments.
  • attrs : A dict containing for , Form.required_css_class , and id . id is generated by the field’s widget attrs or BoundField.auto_id . Additional attributes can be provided by the attrs argument.
  • use_tag : A boolean which is True if the label has an id . If False the default template omits the tag .
  • tag : An optional string to customize the tag, defaults to label .

In your template field is the instance of the BoundField . Therefore field.field accesses BoundField.field being the field you declare, e.g. forms.CharField .

To separately render the label tag of a form field, you can call its label_tag() method:

If you’d like to customize the rendering this can be achieved by overriding the Form.template_name_label attribute or more generally by overriding the default template, see also Overriding built-in form templates .

The label is now rendered using the template engine.

The tag argument was added.

Calls label_tag() with tag=’legend’ to render the label with <legend> tags. This is useful when rendering radio and multiple checkbox widgets where <legend> may be more appropriate than a <label> .

Use this method to render the raw value of this field as it would be rendered by a Widget :

Customizing BoundField ¶

If you need to access some additional information about a form field in a template and using a subclass of Field isn’t sufficient, consider also customizing BoundField .

A custom form field can override get_bound_field() :

Field. get_bound_field ( form , field_name

Takes an instance of Form and the name of the field. The return value will be used when accessing the field in a template. Most likely it will be an instance of a subclass of BoundField .

If you have a GPSCoordinatesField , for example, and want to be able to access additional information about the coordinates in a template, this could be implemented as follows:

Now you can access the country in a template with << form.coordinates.country >> .

Binding uploaded files to a form¶

Dealing with forms that have FileField and ImageField fields is a little more complicated than a normal form.

Firstly, in order to upload files, you’ll need to make sure that your <form> element correctly defines the enctype as "multipart/form-data" :

Secondly, when you use the form, you need to bind the file data. File data is handled separately to normal form data, so when your form contains a FileField and ImageField , you will need to specify a second argument when you bind your form. So if we extend our ContactForm to include an ImageField called mugshot , we need to bind the file data containing the mugshot image:

In practice, you will usually specify request.FILES as the source of file data (just like you use request.POST as the source of form data):

Constructing an unbound form is the same as always – omit both form data and file data:

Testing for multipart forms¶

If you’re writing reusable views or templates, you may not know ahead of time whether your form is a multipart form or not. The is_multipart() method tells you whether the form requires multipart encoding for submission:

Here’s an example of how you might use this in a template:

Subclassing forms¶

If you have multiple Form classes that share fields, you can use subclassing to remove redundancy.

When you subclass a custom Form class, the resulting subclass will include all fields of the parent class(es), followed by the fields you define in the subclass.

In this example, ContactFormWithPriority contains all the fields from ContactForm , plus an additional field, priority . The ContactForm fields are ordered first:

It’s possible to subclass multiple forms, treating forms as mixins. In this example, BeatleForm subclasses both PersonForm and InstrumentForm (in that order), and its field list includes the fields from the parent classes:

It’s possible to declaratively remove a Field inherited from a parent class by setting the name of the field to None on the subclass. For example:

Prefixes for forms¶

You can put several Django forms inside one <form> tag. To give each Form its own namespace, use the prefix keyword argument:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *