条件Flask-WTF表单字段

时间:2016-11-26 23:33:25

标签: python flask flask-wtforms

我想根据所选的类别添加或排除表单字段。

我想做的一种方式就是这样。

if form.category.data == "retail":
    # return "Retail Form"
    form = RetailListingForm()
    return render_template('seller/seller_new_listing.html', form=form)
if form.category.data == "wholesale":
    # Return Wholesale
    form = WholeSaleListingForm()
    return render_template('seller/seller_new_listing.html', form=form)

if form.category.data == "wholesale-and-retail":
    # Return Both forms by inheritance
    return render_template('seller/seller_new_listing.html', form=form)

在html中。

{% if form == WholeSaleListingForm  %}
    {{render_field(form.whole_sale_price)}}
{% endif  %}

这不起作用,因为如果它不是整个销售形成whole_sale_price错误和RetailListingForm你怎么建议我在一个模板中包含表格时包含表格。

1 个答案:

答案 0 :(得分:2)

您可以添加另一个处理表单选择类型的变量,然后将其传递给render_template函数:

if form.category.data == "retail":
    # return "Retail Form"
    type = 'retail'
    form = RetailListingForm()
    return render_template('seller/seller_new_listing.html', form=form, type=type)
elif form.category.data == "wholesale":
    # Return Wholesale
    type = 'wholesale'
    form = WholeSaleListingForm()
    return render_template('seller/seller_new_listing.html', form=form, type=type)
elif form.category.data == "wholesale-and-retail":
    # Return Both forms by inheritance
    return render_template('seller/seller_new_listing.html', form=form, type=None)

然后,在您的模板中,只需使用type评估

{% if type == 'wholesale' %}
    {{ render_field(form.whole_sale_price) }}
{% endif %}