为Jinja中的flask wtforms selectfield选择默认值以获取动态数据 [英] Select default value for flask wtforms selectfield within jinja for dynamic data

查看:447
本文介绍了为Jinja中的flask wtforms selectfield选择默认值以获取动态数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为选择字段设置默认值,该字段是使用html页面中的jinja使用for循环动态生成的,而我在文档中找不到解决方案.基本上,我需要一种方法,如果可能的话,使用jinja设置selectfield的默认值.

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.

我无法在python的路由侧或表单侧设置默认值,因为这些字段是动态生成的,并且默认值需要根据选择而有所不同.如果我使用字符串字段而不使用选择字段,则可以设置默认值.

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?

第二个问题是,如果我将ID和名称设置为生成html页面时的样子,我可以提交并使用一个手动的html字段,该字段在我提交时仍可以与其他wtform字段一起使用吗?如果可能的话,我也许可以用这种方式解决我的问题.

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.

我要转换为selectfield的stringfield的代码:

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 %}

谢谢

推荐答案

关于使用WTForms和Jinja2以及动态数据设置SelectField的默认值,可以使用以下示例:

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

首先,在表单中定义SelectField.

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

最后在html中,使用process_data定义所选值. 注意:不使用z变量.

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="")}}

这篇关于为Jinja中的flask wtforms selectfield选择默认值以获取动态数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆