简体   繁体   English

条件烧瓶WTF表单字段

[英]Conditional Flask-WTF Forms Fields

I would like to include or excluded form fields depending on the category they selected. 我想根据选择的类别包括或排除表单字段。

One way i was thinking of doing is like this. 我想做的一种方式就是这样。

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)

In the html. 在html中。

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

This does not work because if its not a whole sale form the whole_sale_price errors and the RetailListingForm How would you recommended i include forms while having it all in one template. 这是行不通的,因为如果它不是一个完整的销售表单, whole_sale_price出现whole_sale_price错误和RetailListingForm ,您将如何建议我在一个模板中全部包含表单的同时包含表单。

You could add another variable that handles your form selection type, and then pass it into the render_template function: 您可以添加另一个处理表单选择类型的变量,然后将其传递给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)

Then, in your template, just use evaluate with type : 然后,在您的模板中,只需将评估与type配合使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM