The Forms API | Django documentation (original) (raw)

Bound and unbound forms

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

class Form[source]

To create an unbound Form instance, simply instantiate the class:

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

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

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

Form. is_bound

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

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

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

f = ContactForm({}) f.is_bound True

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

Using forms to validate data

Form. clean()

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

Form. is_valid()

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

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

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

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

Form. errors

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

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

In this dictionary, the keys are the field names, and the values are lists of Unicode 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 callis_valid() first. The form’s data will be validated the first time either you call is_valid() or access errors.

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

Form.errors. as_data()

Returns a dict that maps fields to their original ValidationErrorinstances.

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

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

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

Form.errors. as_json(escape_html=False)

Returns the errors serialized as JSON.

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

By default, as_json() does not escape its output. If you are using it for something like AJAX requests to a form view where the client interprets the response and inserts errors into the page, you’ll want to be sure to escape the results on the client-side to avoid the possibility of a cross-site scripting attack. It’s trivial to do so using a JavaScript library like jQuery - simply use $(el).text(errorText) rather than .html().

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. add_error(field, error)

This method allows adding errors to specific fields from within theForm.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 simple string, or preferably an instance ofValidationError. See Raising ValidationError for best practices when defining form errors.

Note that Form.add_error() automatically removes the relevant field fromcleaned_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 Trueif the field contains any errors at all.

To check for non-field errors useNON_FIELD_ERRORS as the field parameter.

Form. non_field_errors()

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

Behavior of unbound forms

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

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

Dynamic initial values

Form. initial

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

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

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

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

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

from django import forms class CommentForm(forms.Form): ... name = forms.CharField(initial='class') ... url = forms.URLField() ... comment = forms.CharField() f = CommentForm(initial={'name': 'instance'}, auto_id=False) print(f)

Name: Url: Comment:

Checking which form data has changed

Form. has_changed()

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

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

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

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

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

Form. changed_data

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

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

Accessing the fields from the form

Form. fields

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

for row in f.fields.values(): print(row) ... <django.forms.fields.CharField object at 0x7ffaac632510> <django.forms.fields.URLField object at 0x7ffaac632f90> <django.forms.fields.CharField object at 0x7ffaac3aa050> f.fields['name'] <django.forms.fields.CharField object at 0x7ffaac6324d0>

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

f.as_table().split('\n')[0] 'Name:' f.fields['name'].label = "Username" f.as_table().split('\n')[0] 'Username:'

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

f.base_fields['name'].label = "Username" another_f = CommentForm(auto_id=False) another_f.as_table().split('\n')[0] 'Username:'

Accessing “clean” data

Form. cleaned_data

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

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

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

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

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

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

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

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

data = {'subject': 'hello', ... 'message': 'Hi there', ... 'sender': 'foo@example.com', ... 'cc_myself': True, ... 'extra_field_1': 'foo', ... 'extra_field_2': 'bar', ... 'extra_field_3': 'baz'} f = ContactForm(data) f.is_valid() True f.cleaned_data # Doesn't contain extra_field_1, etc. {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}

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

from django import forms class OptionalPersonForm(forms.Form): ... first_name = forms.CharField() ... last_name = forms.CharField() ... nick_name = forms.CharField(required=False) data = {'first_name': 'John', 'last_name': 'Lennon'} f = OptionalPersonForm(data) f.is_valid() True f.cleaned_data {'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'}

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

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

Outputting forms as HTML

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

f = ContactForm() print(f)

Subject: Message: Sender: Cc myself:

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="checked" if appropriate:

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

Subject: Message: Sender: Cc myself:

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

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 Unicode object.

as_p()

Form. as_p()

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

f = ContactForm() f.as_p() '

Subject:

\n

Message:

\n

Sender:

\n

Cc myself:

' print(f.as_p())

Subject:

Message:

Sender:

Cc myself:

as_ul()

Form. as_ul()

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

f = ContactForm() f.as_ul() '

  • Subject:
  • \n
  • Message:
  • \n
  • Sender:
  • \n
  • Cc myself:
  • ' print(f.as_ul())

  • Subject:
  • Message:
  • Sender:
  • Cc myself:
  • as_table()

    Form. as_table()

    Finally, as_table() outputs the form as an HTML <table>. This is exactly the same as print. In fact, when you print a form object, it calls its as_table() method behind the scenes:

    f = ContactForm() f.as_table() 'Subject:\nMessage:\nSender:\nCc myself:' print(f)

    Subject: Message: Sender: Cc myself:

    Styling required or erroneous form rows

    Form. error_css_class

    Form. required_css_class

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

    The Form class has a couple of hooks you can use to add classattributes to required rows or to rows with errors: simply set theForm.error_css_class and/or Form.required_css_classattributes:

    from django import forms

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

    # ... and the rest of your fields here

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

    f = ContactForm(data) print(f.as_table())

    Subject: ... Message: ... Sender: ... Cc myself: ... >>> f['subject'].label_tag() Subject: >>> f['subject'].label_tag(attrs={'class': 'foo'}) Subject:

    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 ordersubject, message, sender, cc_myself. To reorder the HTML output, just change the order in which those fields are listed in the class.

    There are several other ways to customize the order:

    Form. field_order

    New in Django 1.9.

    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 definesfield_order and you include field_order when instantiating the Form, then the latter field_order will have precedence.

    Form. order_fields(field_order)

    New in Django 1.9.

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

    How errors are displayed

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

    data = {'subject': '', ... 'message': 'Hi there', ... 'sender': 'invalid email address', ... 'cc_myself': True} f = ContactForm(data, auto_id=False) print(f.as_table())

    Subject: Message: Sender: Cc myself: >>> print(f.as_ul())
  • Subject:
  • Message:
  • Sender:
  • Cc myself:
  • >>> print(f.as_p())

    Subject:

    Message:

    Sender:

    Cc myself:

    Customizing the error list format

    By default, forms use django.forms.utils.ErrorList to format validation errors. If you’d like to use an alternate class for displaying errors, you can pass that in at construction time (replace __str__ by __unicode__ on Python 2):

    from django.forms.utils import ErrorList class DivErrorList(ErrorList): ... def str(self): # unicode on Python 2 ... return self.as_divs() ... def as_divs(self): ... if not self: return '' ... return '

    %s
    ' % ''.join(['
    %s
    ' % e for e in self]) f = ContactForm(data, auto_id=False, error_class=DivErrorList) f.as_p()

    This field is required.

    Subject:

    Message:

    Enter a valid email address.

    Sender:

    Cc myself:

    More granular output

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

    class BoundField[source]

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

    The __str__() (__unicode__ on Python 2) method of this object displays the HTML for this field.

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

    form = ContactForm() print(form['subject'])

    To retrieve all BoundField objects, iterate the form:

    form = ContactForm() for boundfield in form: print(boundfield)

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

    f = ContactForm(auto_id=False) print(f['message']) f = ContactForm(auto_id='id_%s') print(f['message'])

    Attributes of BoundField

    BoundField. auto_id

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

    BoundField. data

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

    unbound_form = ContactForm() print(unbound_form['subject'].data) None bound_form = ContactForm(data={'subject': 'My Subject'}) print(bound_form['subject'].data) My Subject

    BoundField. errors

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

    data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''} f = ContactForm(data, auto_id=False) print(f['message']) f['message'].errors ['This field is required.'] print(f['message'].errors)

    >>> f['subject'].errors [] >>> print(f['subject'].errors)

    str(f['subject'].errors) ''

    BoundField. field

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

    BoundField. form

    The Form instance this BoundFieldis bound to.

    BoundField. help_text

    The help_text of the field.

    BoundField. html_name

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

    BoundField. id_for_label

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

    ...{{ my_field }}

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

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

    and using the template above, would render something like:

    ...

    BoundField. is_hidden

    Returns True if this BoundField’s widget is hidden.

    BoundField. label

    The label of the field. This is used inlabel_tag().

    BoundField. name

    The name of this field in the form:

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

    Methods of BoundField

    BoundField. as_hidden(attrs=None, **kwargs)[source]

    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)[source]

    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()[source]

    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 thecss_classes method:

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

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

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

    BoundField. label_tag(contents=None, attrs=None, label_suffix=None)[source]

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

    f = ContactForm(data={'message': ''}) print(f['message'].label_tag()) Message:

    You can provide the contents parameter which will replace the auto-generated label tag. An attrs dictionary may contain additional attributes for the <label> tag.

    The HTML that’s generated includes the form’slabel_suffix (a colon, by default) or, if set, the current field’s label_suffix. The optionallabel_suffix parameter allows you to override any previously set suffix. For example, you can use an empty string to hide the label on selected fields. If you need to do this in a template, you could write a custom filter to allow passing parameters to label_tag.

    BoundField. value()[source]

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

    initial = {'subject': 'welcome'} unbound_form = ContactForm(initial=initial) bound_form = ContactForm(data={'subject': 'hi'}, initial=initial) print(unbound_form['subject'].value()) welcome print(bound_form['subject'].value()) hi

    Customizing BoundField

    New in Django 1.9.

    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)[source]

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

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

    class GPSCoordinatesBoundField(BoundField): @property def country(self): """ Return the country the coordinates lie in or None if it can't be determined. """ value = self.value() if value: return get_country_from_coordinates(value) else: return None

    class GPSCoordinatesField(Field): def get_bound_field(self, form, field_name): return GPSCoordinatesBoundField(form, self, field_name)

    Now you can access the country in a template with{{ form.coordinates.country }}.

    Binding uploaded files to a form

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

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

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

    Bound form with an image field

    from django.core.files.uploadedfile import SimpleUploadedFile data = {'subject': 'hello', ... 'message': 'Hi there', ... 'sender': 'foo@example.com', ... 'cc_myself': True} file_data = {'mugshot': SimpleUploadedFile('face.jpg', )} f = ContactFormWithMugshot(data, file_data)

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

    Bound form with an image field, data from the request

    f = ContactFormWithMugshot(request.POST, request.FILES)

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

    Unbound form with an image field

    f = ContactFormWithMugshot()

    Testing for multipart forms

    Form. is_multipart()

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

    f = ContactFormWithMugshot() f.is_multipart() True

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

    {% if form.is_multipart %}

    {% else %} {% endif %} {{ form }}

    Subclassing forms

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

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

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

    class ContactFormWithPriority(ContactForm): ... priority = forms.CharField() f = ContactFormWithPriority(auto_id=False) print(f.as_ul())

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

    from django import forms class PersonForm(forms.Form): ... first_name = forms.CharField() ... last_name = forms.CharField() class InstrumentForm(forms.Form): ... instrument = forms.CharField() class BeatleForm(InstrumentForm, PersonForm): ... haircut_type = forms.CharField() b = BeatleForm(auto_id=False) print(b.as_ul())

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

    from django import forms

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

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

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

    Prefixes for forms

    Form. prefix

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

    mother = PersonForm(prefix="mother") father = PersonForm(prefix="father") print(mother.as_ul())

  • First name:
  • Last name:
  • >>> print(father.as_ul())
  • First name:
  • Last name:
  • The prefix can also be specified on the form class:

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

    New in Django 1.9:

    The ability to specify prefix on the form class was added.