How to rewrite this Flask view function to follow the post/redirect/get pattern?

前端 未结 2 1369
你的背包
你的背包 2021-01-06 01:01

I have a small log browser. It retrieves and displays a list of previously logged records depending on user\'s input. It does not update anything.

The code is very s

2条回答
  •  不要未来只要你来
    2021-01-06 01:34

    The common way to do P/R/G in Flask is this:

    @app.route('/log', methods=('GET', 'POST'))
    def log():
        form = LogForm()
        if form.validate_on_submit():
            # process the form data
            # you can flash() a message here or add something to the session
            return redirect(url_for('log'))
        # this code is reached when the form was not submitted or failed to validate
        # if you add something to the session in case of successful submission, try
        # popping it here and pass it to the template
        return render_template('log.html', form=form)
    

    By staying on the POSTed page in case the form failed to validate WTForms prefills the fields with the data entered by the user and you can show the errors of each field during form rendering (usually people write some Jinja macros to render a WTForm easily)

提交回复
热议问题