简体   繁体   中英

How to use a WTForms FieldList of FormFields?

I'm building a website using Flask in which I use WTForms . In a Form I now want to use a FieldList of FormFields as follows:

class LocationForm(Form):
    location_id = StringField('location_id')
    city = StringField('city')

class CompanyForm(Form):
    company_name = StringField('company_name')
    locations = FieldList(FormField(LocationForm))

so to give people the ability to enter a company with two locations (dynamic adding of locations comes later) I do this on the front side:

<form action="" method="post" role="form">
    {{ companyForm.hidden_tag() }}
    {{ companyForm.company_name() }}
    {{ locationForm.location_id() }}
    {{ locationForm.city() }}
    {{ locationForm.location_id() }}
    {{ locationForm.city() }}
    <input type="submit" value="Submit!" />
</form>

So on submit I print the locations:

print companyForm.locations.data

but I get

[{'location_id': u'', 'city': u''}]

I can print the values of the first location using the locationForm (see below), but I still don't know how to get the data of the second location.

print locationForm.location_id.data
print locationForm.city.data

So the list of locations does have one dict with empty values, but:

  1. Why does the list of locations have only one, and not two dicts?
  2. And why are the values in the location dict empty?

Does anybody know what I'm doing wrong here? All tips are welcome!

For starters, there's an argument for the FieldList called min_entries , that will make space for your data:

class CompanyForm(Form):
    company_name = StringField('company_name')
    locations = FieldList(FormField(LocationForm), min_entries=2)

This will setup the list the way you need. Next you should render the fields directly from the locations property, so names are generated correctly:

<form action="" method="post" role="form">
    {{ companyForm.hidden_tag() }}
    {{ companyForm.company_name() }}
    {{ companyForm.locations() }}
    <input type="submit" value="Submit!" />
</form>

Look at the rendered html, the inputs should have names like locations-0-city , this way WTForms will know which is which.

Alternatively, for custom rendering of elements do

{% for l in companyForms.locations %}
{{ l.form.city }}
{% endfor %}

(in wtforms alone l.city is shorthand for l.form.city . However, that syntax seems to clash with Jinja, and there it is necessary to use the explicit l.form.city in the template.)

Now to ready the submitted data, just create the CompanyForm and iterate over the locations:

for entry in form.locations.entries:
    print entry.data['location_id']
    print entry.data['city']

This is an old question, but still a good one.

I'd like to add a working Flask based example of a toy database (just a list of strings) with focus on the Python part - how to initialize the form with variable number of subforms and how to process the posted data.

This is the example.py file:

import flask
import wtforms
import flask_wtf

app = flask.Flask(__name__)
app.secret_key = 'fixme!'

# not subclassing from flask_wtf.FlaskForm
# in order to avoid CSRF on subforms
class EntryForm(wtforms.Form):
    city = wtforms.fields.StringField('city name:')
    delete = wtforms.fields.BooleanField('delete?')

class MainForm(flask_wtf.FlaskForm):
    entries = wtforms.fields.FieldList(wtforms.fields.FormField(EntryForm))
    submit = wtforms.fields.SubmitField('SUBMIT')

city_db = "Graz Poprad Brno Basel Rosenheim Torino".split() # initial value

@app.route("/", methods=['POST'])
def demo_view_function_post():
    global city_db

    form = MainForm()
    if form.validate_on_submit():
        city_db = [
            entry['city'] for entry in form.entries.data
            if entry['city'] and not entry['delete']]
        return flask.redirect(flask.url_for('demo_view_function_get'))

    # handle the validation error, i.e. flash a warning
    return flask.render_template('demo.html', form=form)

@app.route("/")
def demo_view_function_get():
    form = MainForm()
    entries_data = [{'city': city, 'delete': False} for city in city_db]
    entries_data.append({'city': '', 'delete': False})  # "add new" placeholder
    form.process(data={'entries': entries_data})
    return flask.render_template('demo.html', form=form)

This is the demo.html file:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Demo</title>
</head>
<body>
  <h1>Subform demo</h1>
  <p>Edit names / mark for deletion / add new</p>
  <form method="post">
    {{ form.csrf_token() }}
    {% for entry in form.entries %}
      {% if loop.last %}
        <div>Add new:</div>
      {% endif %}  
      <div>
        {{ entry.city.label }} {{ entry.city() }}
        {{ entry.delete() }} {{ entry.delete.label }}
      </div>
    {% endfor %}
    {{ form.submit() }}
  </form>
</body>

Run with: FLASK_APP=example flask run

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM