Select default value for flask wtforms selectfield within jinja for dynamic data

核能气质少年 提交于 2019-12-10 19:18:49

问题


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


回答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("/...")
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="")}}



回答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>


来源:https://stackoverflow.com/questions/54823048/select-default-value-for-flask-wtforms-selectfield-within-jinja-for-dynamic-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!