简体   繁体   中英

How can I add 2 working forms to the same template?

I need to add 2 separate forms to the same web page and I cannot get the second form to output any information.

In my research I saw people suggesting to split the forms onto 2 different def functions but I am having trouble figuring out how to do that an keep both forms usable at the sane time.

from flask import Flask, session, render_template, url_for, redirect
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField


app = Flask(__name__)
app.config['SECRET_KEY'] = 'b317a06ad972917a84be4c6c14c64882'


class PostForm(FlaskForm):
    content = StringField('Content')
    submit = SubmitField('Submit')


class SecondPostForm(FlaskForm):
    content = StringField('Second Content')
    submit = SubmitField('Second Submit')


@app.route("/", methods=['GET', 'POST'])
@app.route("/home", methods=['GET', 'POST'])
def home():
    form = PostForm()
    second_form = SecondPostForm()
    if form.validate_on_submit():
        print(form.content.data)
        session['content'] = form.content.data
        redirect(url_for('submit'))
        return redirect(url_for('submit'))
'''
--------------------------------------------------------------------
is it possible to split the second if statement onto its own def and keep 
them both usable on the same page at the same time?
--------------------------------------------------------------------

'''
    elif second_form.validate_on_submit():
        print(second_form.content.data)
        session['content'] = second_form.content.data
        return redirect(url_for('othersubmit'))
    return render_template('example.html', second_form=second_form, form=form)


@app.route("/submit", methods=['GET', 'POST'])
def submit():
    content = session.get('content', None)
    print(content)
    session.pop('content', None)
    return redirect(url_for('home'))


@app.route("/othersubmit", methods=['GET', 'POST'])
def othersubmit():
    print('othersubmit')
    content = session.get('content', None)
    print(content)
    session.pop('content', None)
    return redirect(url_for('home'))


if __name__ == "__main__":
    app.run(debug=True)





<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="content-section">
    <form method="POST" action="">
        {{ form.hidden_tag() }}
        <fieldset class="form-group">
            <legend class="border-bottom mb-4">{{ legend }}</legend>
            <div class="form-group">
                {{ form.content.label(class="form-control-label") }}
                {% if form.content.errors %}
                    {{ form.content(class="form-control form-control-lg is-invalid") }}
                    <div class="invalid-feedback">
                        {% for error in form.content.errors %}
                            <span>{{ error }}</span>
                        {% endfor %}
                    </div>
                {% else %}
                    {{ form.content(class="form-control form-control-lg") }}
                {% endif %}
            </div>
        </fieldset>
        <div class="form-group">
            {{ form.submit(class="btn btn-outline-info") }}
        </div>
    </form>
    <form method="POST" action="{{ url_for('othersubmit') }}">
        {{ second_form.hidden_tag() }}
        <fieldset class="form-group">
            <legend class="border-bottom mb-4">{{ legend }}</legend>
            <div class="form-group">
                {{ second_form.content.label(class="form-control-label") }}
                {% if second_form.content.errors %}
                    {{ second_form.content(class="form-control form-control-lg is-invalid") }}
                    <div class="invalid-feedback">
                        {% for error in second_form.content.errors %}
                            <span>{{ error }}</span>
                        {% endfor %}
                    </div>
                {% else %}
                    {{ second_form.content(class="form-control form-control-lg") }}
                {% endif %}
            </div>
        </fieldset>
        <div class="form-group">
            {{ second_form.submit(class="btn btn-outline-info") }}
        </div>
    </form>
</div>
</body>
</html>

I have tried with and without action="{{ url_for('othersubmit') }}" neither have the desired result

The goal is to have either form print its own data and also print which form it came from. At the moment the 1st form prints the same data twice and the 2nd form doesn't print anything.

You can do few things: 1) Firstly, if you have 2 forms on one page, you can't have two {{ second_form.hidden_tag() }}, as they will throw error of having same id. As per wtform documentation, I have handled it as {{ form.csrf_token(id='login_csrf') }}. See you can specify your own id, so this will prevent clash.

2) Change the Submit button name in both the forms. So that they are distinct. Then you can do as below. As you can see i have 2 forms on same page form_login and form_reg. I have kept submit buttons name differet. One is login and another is register.

if form_login.login.data:
        if form_login.validate_on_submit():
            #do something here

    elif form_reg.register.data:
        if form_reg.validate_on_submit():
            #do something here

    return render_template('abc.html')

This should work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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