[英]Populate form (wtforms) in flask with data from database using psycopg2
[英]How to redirect while keeping form data using Flask and WTForms?
讓我們有一個頁面,上面有一個注冊表單。 它在#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)
您不能通過redirect
響應發送內容,您只能說“轉到此網址” 。 此外,flask 接受一個Response
類,而不是一個實例作為redirect
的參數。
要解決您的問題,您需要使用session
(或簡單地flash
)來跨請求保留狀態。
這是一個原型:
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_page():
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()
提交無效表單后,您將被重定向到/#invalid
並按預期填充表單:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.