Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

python - Determine which WTForms button was pressed in a Flask view

I have a page with multiple links to redirect the user to different pages. I thought using a form would be nicer, so I defined a WTForms Form with multiple SubmitFields. How do I determine which button was clicked and redirect based on that?

class MainForm(Form):
    user_stats = SubmitField('User Stats')
    room_stats = SubmitField('Room Stats')

@main.route('/')
@login_required
def index():
    form = MainForm()    
    return render_template('index.html', form=form)
<form action="#" method="post">
    {{ wtf.quick_form(form) }}
</form>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You added two buttons to the form, so check which of the fields' data is True.

from flask import Flask, render_template, redirect, url_for
from flask_wtf import Form
from wtforms import SubmitField

app = Flask(__name__)
app.secret_key = 'davidism'

class StatsForm(Form):
    user_stats = SubmitField()
    room_stats = SubmitField()

@app.route('/stats', methods=['GET', 'POST'])
def stats():
    form = StatsForm()

    if form.validate_on_submit():
        if form.user_stats.data:
            return redirect(url_for('user_stats'))
        elif form.room_stats.data:
            return redirect(url_for('room_stats'))

    return render_template('stats.html', form=form)

app.run(debug=True)
<form method="post">
    {{ form.hidden_tag() }}
    {{ form.user_stats }}
    {{ form.room_stats }}
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...