所以这是我的表格类:
exchangeNames=["one","two","three"]
class addExchange_All(Form):
apis={}
secrets={}
for exchangeName in exchangesNames:
apis[exchangeName+"_api"] = TextField(
description=('Enter %s Api Key:', exchangeName))
secrets[exchangeName+'_secret'] = TextField(validators=[RequiredIf(exchangeName+'_api')],
description=('Enter %s Api Key:', exchangeName))
submit = SubmitField('Update Exchange Credentials')
这是我的路线功能:
@account.route('/manage/exchanges', methods=['POST', 'GET'])
def exchanges():
form=addExchange_All()
return render_template('/account/exchanges.html', form=form)
我正在尝试渲染exchanges.html中的所有字段,如下所示:
<div class="two fields">
{%for a in form.apis%}
{{f.render_form_field(a)}}
{%endfor%}
{%for a in form.secrets%}
{{f.render_form_field(a)}}
{%endfor%}
</div>
这里是render_form_field宏:
{# Render a field for the form #}
{% macro render_form_field(field, extra_classes='') %}
{% if field.type == 'Radio Field' %}
{% set extra_classes = extra_classes + ' grouped fields' %}
{% endif %}
<div class="field {% if field.errors %}error{% endif %} {{
extra_classes }}">
{{ render_form_input(field) }}
{% if field.errors %}
<div class="ui red pointing label">
{{ field.errors[0] | safe }}
</div>
{% endif %}
</div>
{% endmacro %}
模板渲染没有错误,但没有渲染文本字段。我尝试了几种不同的解决方案,比如将它们保存到locals()但似乎没有任何效果。帮助
答案 0 :(得分:0)
我不确定这是不是答案,我没有时间检查它,所以如果有人能纠正我并且我会学到一些东西,我很高兴。
无论如何,我构建动态表单的方法是不使用dicts,并以下列方式将每个项目作为一个单独的元素作为类属性:
def create_dynamic_form():
class addExchange_All(Form):
submit = SubmitField('Update Exchange Credentials')
pass
for exchangeName in ["One","Two","Three"]:
setattr(addExchange_All, exchangeName+"_api", TextField(
description=('Enter '+exchangeName+' Api Key:')))
setattr(addExchange_All, exchangeName+'_secret', TextField(
validators=[RequiredIf(exchangeName+'_api')],
description=('Enter '+exchangeName+' Api Key:')))
return addExchange_All()
然后使用:
form=create_dynamic_form() # instead of addExchange_All()