python - 条件 Flask-WTF 表单字段

标签 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 您建议我如何将表单包含在一个模板中。

最佳答案

您可以添加另一个处理表单选择类型的变量,然后将其传递到 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)

然后,在您的模板中,只需使用评估与类型:

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

关于python - 条件 Flask-WTF 表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40824257/

相关文章:

python - 如何为项目在 PYPI 上设置 "front page"文档?

Python 求解模式并用数字和英文单词返回答案

python - 无法导入 'pymongo'

Python Flask 提交按钮问题

python - 无法使用 PySpark pickle listreverseiterator 对象

python - 对具有可变帧率的视频的每一帧应用自定义函数

python - 在 flask sqlalchemy 中使用外键引用值

python - 奇怪的 `UnicodeEncodeError` 使用 `os.path.exists`

flask - 可以使用 wtforms 来验证 GET 参数吗?

python - WTForms 在 Heroku 上引发 "TypeError: ' unicode' 没有缓冲区接口(interface)