如何在使用Flask和WTForms保留表单数据的同时进行重定向?

时间:2019-07-05 14:15:46

标签: python redirect flask

让我们在上面有一个注册表格的页面。在#registration节中。如果用户提交了无效数据,则页面应将其返回到#registration部分,并显示向其提交了无效值的字段。

我试图渲染模板并做出响应并重定向到它,但是我得到了TypeError

  File ".../app/routes.py", line 28, in index
    return redirect(url_for('.index', form=form, _anchor='registration'), 302, response)
  File ".../python3.7/site-packages/werkzeug/utils.py", line 507, in redirect
    mimetype="text/html",
TypeError: __call__() got an unexpected keyword argument 'mimetype'

函数如下:

@app.route('/', methods=['GET', 'POST'])
def index():
    form = RegisterForm()
    if form.validate_on_submit():
        # everithing OK
        return redirect(url_for('.index', _anchor='registration'))

    # If form was submitted but contained invalid information
    if form.is_submitted():
        response = make_response(render_template('index.html', form=form))
        return redirect(url_for('.index', _anchor='registration'), 302, response)

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

1 个答案:

答案 0 :(得分:1)

您不能发送带有redirect响应的内容,只能说“转到该网址” 。而且flask接受Response类,而不是实例作为redirect的参数。

要解决您的问题,您需要使用session(或简单地flash ing)来保留请求中的状态。

这是一个原型:

from flask import Flask, render_template_string, request, session, redirect
from werkzeug import MultiDict

from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField
from wtforms.validators import AnyOf

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

class MyForm(FlaskForm):
    name = StringField('name', validators=[AnyOf(['secretname'])])

@app.route('/', methods=['POST', 'GET'])
def form():
    form = MyForm()
    html = '''
    {% for error in form.name.errors %} <span>{{ error }}</span> {% endfor %}
    <form method="POST" action="/">
        {{ form.csrf_token }}
        {{ form.name.label }} {{ form.name(size=20) }}
        <input type="submit" value="Go">
    </form>
    '''

    if request.method == 'GET':
        formdata = session.get('formdata', None)
        if formdata:
            form = MyForm(MultiDict(formdata))
            form.validate()
            session.pop('formdata')
        return render_template_string(html, form=form)

    if form.validate_on_submit():
        # use the form somehow
        # ...
        return redirect('/#registered')

    if form.is_submitted() and not form.validate():
        session['formdata'] = request.form
        return redirect('/#invalid')

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

运行服务器时,您得到:
enter image description here

提交无效的表单后,您将重定向到/#invalid,并按预期填充表单:

invalid submission