Holly Johnson
Holly Johnson

Reputation: 509

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.

{% 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.

Upvotes: 2

Views: 3562

Answers (1)

Scratch'N'Purr
Scratch'N'Purr

Reputation: 10437

You could add another variable that handles your form selection type, and then pass it into the render_template function:

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:

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

Upvotes: 5

Related Questions