viz228
viz228

Reputation: 63

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 documentation. Basically i need a way to set the default value of the selectfield using jinja if possible.

I cant set the default value from the routes side or the forms side in python because the fields are made dynamically and the default values need to be different depending on the choices. I can set the default value if i use a stringfield but not a selectfield.

Can anyone help me find a solution for this problem? Could i switch to a different formfield to use instead of selectfield?

2nd question would be can i build and use a manual html field that would still work with the other wtform fields when i submit if i set the id and name to be what it would be when the html page is generated? I might have a way to solve my problem that way if its possible.

code for how it would be done with stringfield that i want translated to selectfield:

{% for d in data %}
{{ form.type.label(class="label") }}
{{ form.type(class="field", value=d.type) }}
{% endfor %}

Thank you

Upvotes: 3

Views: 5033

Answers (2)

Geo_Python
Geo_Python

Reputation: 123

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("/...")
def country(): 
   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="")}}

Upvotes: 8

kellymandem
kellymandem

Reputation: 1769

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>

Upvotes: 0

Related Questions