Search code examples
flaskjinja2flask-wtforms

Set Jinja2/FlaskForms radio button default at the template level


Given a FlaskForm:

from flask_wtf import FlaskForm
from wtforms import RadioField, SubmitField

class DialectPreferenceForm(FlaskForm):
       dialect = RadioField('SQL Choice', 
          choices=[('firebird','Firebird'),('mysql','MySQL'),('bothsql','Both')])
       dialect_submit = SubmitField("Set choice")

and a template

 <form method="POST" action="">
  {{ form_sql.hidden_tag() }}
  {{ form_sql.dialect }}<br/>
  {{ form_sql.dialect_submit }}
  </form>

...can the default radio button be set at the template level? I'm looking to do something like this, given a passed parameter param:

 <form method="POST" action="">
  {{ form_sql.hidden_tag() }}

  {% if param == 1 %}
       {{ form_sql.dialect(default='firebird') }}
  {% elif param == 2 %}
       {{ form_sql.dialect(default='mysql') }}
  {% elif param == 3 %}
       {{ form_sql.dialect(default='bothsql') }}
  {% endif %}

  {{ form_sql.dialect_submit }}
  </form>

This question aims for a similar result, but that template uses raw HTML rather than Flask WTF. I don't want to set it in the


Solution

  • I'm not sure if this is what you're looking for, but one option is to set the default value within the endpoint when instantiating the form. For this you can either use the data attribute of the form, or pass a keyword with a value. The key or keyword should correspond to the variable of the form field.
    Typically this is used to pre-populate form fields, but in your case it may help.

    You can find the documentation here.

    dialect = 'mysql' # or one of the other values
    
    form_sql = DialectPreferenceForm(request.form, dialect=dialect)
    # or
    form_sql = DialectPreferenceForm(request.form, data={ 'dialect': dialect })
    

    Another option is to create the form dynamically within a factory function and use the field's default attribute. However, I think it is too complicated and extensive for this purpose.