4

Flask-WTF フォームを使用しており、次のコードがあります。

forms.py で

class DealForm( Form ):
    country  = SelectField( 'Country' )

main.py で

if not form.validate_on_submit():
    form = DealForm()
    form.country.choices = [('us','USA'),('gb','Great Britain'),('ru','Russia')]
    return render_template( 'index.html', user = current_user, form = form )
else:
    return render_template( 'index.html', form = form )

country.choices が None であるため、POST から戻るとエラーが発生します。何が間違っていますか?

4

1 に答える 1

11

を呼び出す前に選択肢を設定する必要がありますvalidate_on_submit()

これらは静的であるため、 Form クラスを作成するときに実行します。

class DealForm(Form):
    country = SelectField('Country', choices=[
        ('us','USA'),('gb','Great Britain'),('ru','Russia')])

フォーム インスタンスの作成後にそれらを設定したい場合 (たとえば、利用可能な選択肢がハードコードされていないか、他の要因によって異なるなどの理由で)、クラスのインスタンスを作成した後に次のように行います。

form.country.choices = [('us','USA'),('gb','Great Britain'),('ru','Russia')]

つまり、以前と同じように。

于 2012-06-06T20:13:44.103 に答える