问题
With django I could simply pass the POST data to the form after failed validation and the user would not have to enter everything again:
question_form = QuestionForm(request.POST)
choice_form_set = ChoiceFormSet(request.POST)
How could I implement this on my own in flask?
回答1:
It's pretty similarly possible with Flask as well:
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm(request.form)
if request.method == 'POST' and form.validate():
user = User(form.username.data, form.email.data,
form.password.data)
db_session.add(user)
flash('Thanks for registering')
return redirect(url_for('login'))
return render_template('register.html', form=form)
The if expression performs the validation check. If validation is successful, the user is forwarded to the login page. If it's false, render_template
is called again with the updated form as parameter, so the form is displayed again with the previously entered data (possibly with hints on what needs to be fixed).
Code taken from Flask documentation.
来源:https://stackoverflow.com/questions/44119600/how-to-keep-input-after-failed-form-validation-in-flask