Fields are responsible for rendering and data conversion. They delegate to validators for data validation.
Fields are defined as members on a form in a declarative fashion:
class MyForm(Form):
name = TextField(u'Full Name', [validators.required(), validators.length(max=10)])
address = TextAreaField(u'Mailing Address', [validators.optional(), validators.length(max=200)])
When a field is defined on a form, the construction parameters are saved until the form is instantiated. At form instantiation time, a copy of the field is made with all the parameters specified in the definition. Each instance of the field keeps its own field data and errors list.
The label and validators can be passed to the constructor as sequential arguments, while all other arguments should be passed as keyword arguments. Some fields (such as SelectField) can also take additional field-specific keyword arguments. Consult the built-in fields reference for information on those.
Stores and processes data, and generates HTML for a form field.
Field instances contain the data of that instance as well as the functionality to render it within your Form. They also contain a number of properties which can be used within your templates to render the field and label.
Construction
Construct a new field.
Parameters: |
|
---|
If _form and _name isn’t provided, an UnboundField will be returned instead. Call its bind() method with a form instance and a name to construct the field.
Validation
To validate the field, call its validate method, providing a form and any extra validators needed. To extend validation behaviour, override pre_validate or post_validate.
Validates the field and returns True or False. self.errors will contain any errors raised during validation. This is usually only called by Form.validate.
Subfields shouldn’t override this, but rather override either pre_validate, post_validate or both, depending on needs.
Parameters: |
|
---|
Override if you need field-level validation. Runs before any other validators.
Parameter: | form – The form the field belongs to. |
---|
Override if you need to run any field-level validation tasks after normal validation. This shouldn’t be needed in most cases.
Parameters: |
|
---|
Data access and processing
To handle incoming data from python, override process_data. Similarly, to handle incoming data from the outside, override process_formdata.
Process incoming data, calling process_data, process_formdata as needed, and run filters.
If data is not provided, process_data will be called on the field’s default.
Field subclasses usually won’t override this, instead overriding the process_formdata and process_data methods. Only override this for special advanced processing, such as when a field encapsulates many inputs.
Process the Python data applied to this field and store the result.
This will be called during form construction by the form’s kwargs or obj argument.
Parameter: | value – The python object containing the value to process. |
---|
Process data received over the wire from a form.
This will be called during form construction with data supplied through the formdata argument.
Parameter: | valuelist – A list of strings to process. |
---|
Rendering
To render a field, simply call it, providing any values the widget expects as keyword arguments. Usually the keyword arguments are used for extra HTML attributes.
Render this field as HTML, using keyword args as additional attributes.
Any HTML attribute passed to the method will be added to the tag and entity-escaped properly.
If one wants to pass the “class” argument which is a reserved keyword in some python-based templating languages, one can do:
form.field(class_="text_blob")
This will output (for a text field):
<input type="text" name="field_name" value="blah" class="text_blob" id="field_name" />
Note: Simply coercing the field to a string or unicode will render it as if it was called with no arguments.
Properties
The type of this field, as a string. This can be used in your templates to do logic based on the type of field:
{% for field in form %}
<tr>
{% if field.type == "BooleanField" %}
<td></td>
<td>{{ field }} {{ field.label }}</td>
{% else %}
<td>{{ field.label }}</td>
<td>{{ field }}</td>
{% end %}
</tr>
{% endfor %}
An object containing boolean flags set either by the field itself, or by validators on the field. For example, the built-in required() validator sets the required flag. An unset flag will result in False.
{% for field in form %}
<tr>
<th>{{ field.label }} {% if field.flags.required %}*{% endif %}</th>
<td>{{ field }}</td>
</tr>
{% endfor %}
Basic fields generally represent scalar data types with single values, and refer to a single input from the form.
A text field which displays and coerces data of the decimal.Decimal type.
Defining the number_format parameter to the constructor allows you to customize how the number is displayed, using standard python string formatting rules.
Can render a file-upload field. Will take any passed filename value, if any is sent by the browser in the post params. This field will NOT actually handle the file upload portion, as wtforms does not deal with individual frameworks’ file handling capabilities.
Example usage:
class UploadForm(Form):
image = FileField(u'Image File', [validators.regexp(u'^[^/\\]\.jpg$')])
description = TextAreaField(u'Image Description')
def validate_image(form, field):
if field.data:
field.data = re.sub(r'[^a-z0-9_.-]', '_', field.data)
def upload(request):
form = UploadForm(request.POST)
if form.image.data:
image_data = request.FILES[form.image.name].read()
open(os.path.join(UPLOAD_PATH, form.image.data), 'w').write(image_data)
Represents an <input type="hidden">.
HiddenField is useful for providing data from a model or the application to be used on the form handler side for making choices or finding records. Very frequently, CRUD forms will use the hidden field for an object’s id.
Hidden fields are like any other field in that they can take validators and values and be accessed on the form object. You should consider validating your hidden fields just as you’d validate an input field, to prevent from malicious people playing with your data.
Represents an <input type="password">.
Other than the fact that this makes a password input field, this field functions exactly like a text-input field.
Like a SelectField, except displays a list of radio buttons.
Iterating the field will produce subfields (each containing a label as well) in order to allow custom rendering of the individual radio fields.
{% for subfield in form.radio %}
<tr>
<td>{{ subfield }}</td>
<td>{{ subfield.label }}</td>
</tr>
{% endfor %}
Simply outputting the field without iterating its subfields will result in a <ul> list of radio choices.
Select fields keep a choices property which is a sequence of (value, label) pairs. The value portion can be any type in theory, but as form data is sent by the browser as strings, you will need to provide a function which can coerce the string representation back to a comparable object.
Select fields with static choice values:
class PastebinEntry(Form):
language = SelectField(u'Programming Language', choices=[('cpp', 'C++'), ('py', 'Python'), ('text', 'Plain Text')])
Note that the choices keyword is only evaluated once, so if you want to make a dynamic drop-down list, you’ll want to assign the choices list to the field after instantiation.
Select fields with dynamic choice values:
class UserDetails(Form):
group_id = SelectField(u'Group', coerce=int)
def edit_user(request, id):
user = User.query.get(id)
form = UserDetails(request.POST, obj=user)
form.group_id.choices = [(g.id, g.name) for g in Group.query.order_by('name')]
Note we didn’t pass a choices to the SelectField constructor, but rather created the list in the view function. Also, the coerce keyword arg to SelectField says that we use int() to coerce form data. The default coerce is unicode().
No different from a normal select field, except this one can take (and validate) multiple choices. You’ll need to specify the HTML rows attribute to the select field when rendering.
The data on the SelectMultipleField is stored as a list of objects, each of which is checked and coerced from the form input. Any inputted choices which are not in the given choices list will cause validation on the field to fail.
This field is the base for most of the more complicated fields, and represents an <input type="text">.
{{ form.username(size=30, maxlength=50) }}
Field enclosures allow you to have fields which represent a collection of fields, so that a form can be composed of multiple re-usable components or more complex data structures such as lists and nested objects can be represented.
Encapsulate a form as a field in another form.
Parameter: | form_class – A subclass of Form that will be encapsulated. |
---|
FormFields are useful for editing child objects or enclosing multiple related forms on a page which are submitted and validated together. While subclassing forms captures most desired behaviours, sometimes for reusability or purpose of combining with ListField, FormField makes sense.
For example, take the example of a contact form which uses a similar set of three fields to represent telephone numbers:
class TelephoneForm(Form):
country_code = IntegerField('Country Code', [validators.required()])
area_code = IntegerField('Area Code/Exchange', [validators.required()])
number = TextField('Number')
class ContactForm(Form):
first_name = TextField()
last_name = TextField()
mobile_phone = FormField(TelephoneForm)
office_phone = FormField(TelephoneForm)
In the example, we reused the TelephoneForm to encapsulate the common telephone entry instead of writing a custom field to handle the 3 sub-fields. The data property of the mobile_phone field will return the data dict of the enclosed form. Similarly, the errors property encapsulate the forms’ errors.
Encapsulate an ordered list of multiple instances of the same field type, keeping data as a list.
>>> authors = FieldList(TextField('Name', [validators.required()]))
Parameters: |
|
---|
Note: Due to a limitation in how HTML sends values, FieldList cannot enclose BooleanField or SubmitField instances.
FieldList is not limited to enclosing simple fields; and can indeed represent a list of enclosed forms by combining FieldList with FormField:
class IMForm(Form):
protocol = SelectField(choices=[('aim', 'AIM'), ('msn', 'MSN')])
username = TextField()
class ContactForm(Form):
first_name = TextField()
last_name = TextField()
im_accounts = FieldList(FormField(IMForm))
While WTForms provides customization for existing fields using widgets and keyword argument attributes, sometimes it is necessary to design custom fields to handle special data types in your application.
Let’s design a field which represents a comma-separated list of tags:
class TagListField(Field):
widget = TextInput()
def _value(self):
if self.data:
return u', '.join(self.data)
else:
return u''
def process_formdata(self, valuelist):
if valuelist:
self.data = [x.strip() for x in valuelist[0].split(',')]
else:
self.data = []
The _value method is called by the TextInput widget to provide the value that is displayed in the form. Overriding the process_formdata method processes the incoming form data back into a list of tags.
Custom fields can also override the default field constructor if needed to provide additional customization:
class BetterTagListField(TagListField):
def __init__(self, label='', validators=None, remove_duplicates=True, **kwargs):
super(BetterTagListField, self).__init__(label, validators, **kwargs)
self.remove_duplicates = remove_duplicates
def process_formdata(self, valuelist):
super(BetterTagListField, self).process_formdata(valuelist)
if remove_duplicates:
self.data = list(self._remove_duplicates(self.data))
@staticmethod
def _remove_duplicates(seq):
"""Remove duplicates in a case insensitive, but case preserving manner"""
d = {}
for item in seq:
if item.lower() not in d:
d[item.lower()] = True
yield item