Skip to content Skip to sidebar Skip to footer

Select Default Value For Flask Wtforms Selectfield Within Jinja For Dynamic Data

I'm trying to set the default value for a select field that is dynamically generated using a for loop using jinja within the html page and i cant find a solution to do this in the

Solution 1:

About setting the default value of a SelectField using WTForms and Jinja2 with dynamic data, you could use the following example:

Firstly, define the SelectField in your form.

class MyForm(FlaskForm):
    country_id = SelectField("Country", coerce=int) #[('1','USA'),..])

Then query the db to construct a list of the available values.

@app.route("/...")defcountry(): 
   form = MyForm()
   available_countries=db.session.query(Country).all()
   countries_list=[(i.id, i.name) for i in available_countries]
   form.country_id.choices = countries_list

Finally in html, use process_data to define the selected value. Note: z variable is not used.

{% set z = form.country_id.process_data(countryNameVariable) %}
{{ form.country_id(class="")}}

Solution 2:

This is the only way I can think of doing it

You could something like this in your views.py

@app.route('/')
def index():
    data=[{'name':'red'}, {'name':'green'}, {'name':'blue'}]
    return render_template('index.html', data=data)

and in your html template

<select name="colour"class="select-field">
    {% set default_value = 'green' %}
    {% for d in data %}
    <option value="{{ d.name }}" {% if d.name == default_value %}selected="selected"{% endif %}>{{ d.name }}</option>
    {% endfor %}
</select>

Post a Comment for "Select Default Value For Flask Wtforms Selectfield Within Jinja For Dynamic Data"