Базовые типы


Базовые поля представляют собой скалярные типы данных с одиночными значениями и относятся к одному эелементу ввода формы.

class wtforms.fields.BooleanField(default field argumentsfalse_values=None)

Represents an <input type="checkbox">. Set the checked-status by using the default-option. Any value for default, e.g. default="checked" puts checked into the html-element and sets the data to True

Параметр: false_values – If provided, a sequence of strings each of which is an exact match string of what is considered a “false” value. Defaults to the tuple ('false', '')
class wtforms.fields.DateField(default field argumentsformat='%Y-%m-%d')

Same as DateTimeField, except stores a datetime.date.

class wtforms.fields.DateTimeField(default field argumentsformat='%Y-%m-%d %H:%M:%S')

A text field which stores a datetime.datetime matching a format.

For better date/time fields, see the dateutil extension

class wtforms.fields.DecimalField(default field argumentsplaces=2rounding=Noneuse_locale=Falsenumber_format=None)

A text field which displays and coerces data of the decimal.Decimal type.

Parameters:
  • places – How many decimal places to quantize the value to for display on form. If None, does not quantize value.
  • rounding – How to round the value during quantize, for example decimal.ROUND_UP. If unset, uses the rounding value from the current thread’s context.
  • use_locale – If True, use locale-based number formatting. Locale-based number formatting requires the ‘babel’ package.
  • number_format – Optional number format for locale. If omitted, use the default decimal format for the locale.
class wtforms.fields.FileField(default field arguments)

Renders a file upload field.

By default, the value will be the filename sent in the form data. WTForms does not deal with frameworks’ file handling capabilities. A WTForms extension for a framework may replace the filename value with an object representing the uploaded data.

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)
class wtforms.fields.MultipleFileField(default field arguments)

FileField that allows choosing multiple files.

class wtforms.fields.FloatField(default field arguments)

A text field, except all input is coerced to an float. Erroneous input is ignored and will not be accepted as a value.

For the majority of uses, DecimalField is preferable to FloatField, except for in cases where an IEEE float is absolutely desired over a decimal value.

class wtforms.fields.IntegerField(default field arguments)

A text field, except all input is coerced to an integer. Erroneous input is ignored and will not be accepted as a value.

class wtforms.fields.RadioField(default field argumentschoices=[]coerce=unicode)

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.

class wtforms.fields.SelectField(default field argumentschoices=[]coerce=unicodeoption_widget=None)

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. Any inputted choices which are not in the given choices list will cause validation on the field to fail.

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().

Advanced functionality

SelectField and its descendants are iterable, and iterating it will produce a list of fields each representing an option. The rendering of this can be further controlled by specifying option_widget=.

class wtforms.fields.SelectMultipleField(default field argumentschoices=[]coerce=unicodeoption_widget=None)

No different from a normal select field, except this one can take (and validate) multiple choices. You’ll need to specify the HTML size 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.

class wtforms.fields.SubmitField(default field arguments)

Represents an <input type="submit">. This allows checking if a given submit button has been pressed.

class wtforms.fields.StringField(default field arguments)

This field is the base for most of the more complicated fields, and represents an <input type="text">.

{{ form.username(size=30, maxlength=50) }}