简体   繁体   中英

Problem with linking forms using Flask and WTForms

I'm trying to set up a web app that runs methods based on user input. The first page takes the image and amount of images and runs a method with them, the user is then sent to the next form which is a conformation button that confirms they have completed a task outside of the application. However when the confirmation button is pressed the user is redirected the first page where it is shown that they are required to input information into the form even though it has been previously filled out

@app.route("/", methods=['GET', 'POST'])
def Home():
    form = SelectImageForm()
    if form.validate_on_submit():
        Label_Required = form.ImageLabel.data
        Amount_Required = form.Amount.data
        Cloud_Transfer(form.ImageLabel.data, form.Amount.data)
        flash(f'Searching Labels for {form.ImageLabel.data}!', 'success')
        form = SelectXMLConversion()
        return Stage2()
    return render_template('home.html', title = 'Label Selection', form=form )

@app.route('/stage2', methods=['GET','POST'])
def Stage2():
    form =  SelectXMLConversion()
    if form.validate_on_submit():
        return render_template('stage2.html', title ='Label Selection', form=form)


if __name__ == '__main__':
    app.run(debug='true')

At the moment its expected just to reload the stage 2 page however it is sending them back to the first page prompting them to fill in the required fields

Don't return Stage2() instead:

from flask import redirect, url_for

def home():
form = SelectImageForm()
if form.validate_on_submit():
    Label_Required = form.ImageLabel.data
    Amount_Required = form.Amount.data
    Cloud_Transfer(form.ImageLabel.data, form.Amount.data)
    flash(f'Searching Labels for {form.ImageLabel.data}!', 'success')
    form = SelectXMLConversion()
    return redirect(url_for('stage2'))
return render_template('home.html', title = 'Label Selection', form=form )

Also, route definitions should be functions, which should be lower case like def home() and def stage2() . I believe label_required and amount_required are also meant to be variables, which should be lower case as well. You may want to check out the conventions for naming in Python .

Finally, as is, the stage2() route will fail. You don't return a template unless the form is validated. Presumably, you want people to fill out the form on this route first, in which case you must have a return outside of that if form.validate_on_submit(): condition.

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