nos nos - 2 months ago 34
Python Question

flask-bootstrap with two forms in one page

I plan to put two forms in one page in my flask app, one to edit general user information and the other to reset password. The template looks like this

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block page_content %}
<div class="page-header">
<h1>Edit Profile</h1>
</div>

{{ wtf.quick_form(form_profile, form_type='horizontal') }}

<hr>

{{ wtf.quick_form(form_reset, form_type='horizontal') }}

<hr>
{% endblock %}


Each form has a submit button.

In the route function, I tried to separate the two form like this

form_profile = ProfileForm()
form_reset = ResetForm()

if form_profile.validate_on_submit() and form_profile.submit.data:
....
if form_reset.validate_on_submit() and form_reset.submit.data:
.....


But it didn't work. When I click on the button in the ResetForm, the ProfileForm validation logic is executed.

I suspect the problem is that
wtf.quick_form()
creates two identical submit buttons, but not sure.

What should I do in this case? Can
bootstrap/wtf.html
template deal with this situation?

Answer

Define this two SubmitField with different names, like this:

class Form1(Form):
    name = StringField('name')
    submit1 = SubmitField('submit')

class Form2(Form):
    name = StringField('name')
    submit2 = SubmitField('submit')

Then in the view:

....
form1 = Form1()
form2 = Form2()

if form1.validate_on_submit() and form1.submit1.data:
....
if form2.validate_on_submit() and form2.submit2.data:
....