LoginSignup
1
1

More than 3 years have passed since last update.

flask-wtf で SelectField に対し動的に選択肢を追加した時に注意する点

Posted at

flask-wtf で SelectField に対し動的に選択肢を追加する

hoge_form.py
from flask_wtf import FlaskForm
from wtforms import SelectField

class HogeForm(FlaskForm):
    select = SelectField('選択肢', coerce=int)
view.py
@app.route('/', methods=['GET', 'POST'])
def hoge():
    form = HogeForm()
    if form.validate_on_submit():
        ...
    form.select.choices = [(d.id, d.name) for d in data]  
    return render_template('hoge_post.html', form=form)

そうすると以下のようなエラーがでる

TypeError: 'NoneType' object is not iterable

この原因は validate_on_submit() が choices に対してバリデーションを行なっているため、 validate_on_submit() より後に choices を追加するとエラーになってしまう
なので以下のように validate_on_submit() の前で追加する

new_view.py
@app.route('/', methods=['GET', 'POST'])
def hoge():
    form = HogeForm()
    form.select.choices = [(d.id, d.name) for d in data]
    if form.validate_on_submit():
        ...

    return render_template('hoge_post.html', form=form)
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1