由于必须登录后才能发布用户,因此如果用户未登录,则仅显示“单击此处登录”链接而不是表单是更有意义的。
如果确实要执行此操作,则可以在重定向到登录路径时在会话中存储任何表单数据,然后在返回注释路径后检查此存储的数据。同时存储请求的路径,以便仅当您返回同一页面时才可以恢复数据。要存储数据,您需要创建自己的
login_required装饰器。
request.form.to_dict(flat=False)会将
MultiDict数据转储到列表的字典中。这可以存储在中
session。
from functools import wrapsfrom flask import current_app, request, session, redirect, render_templatefrom flask_login import current_userfrom werkzeug.datastructures import MultiDictdef login_required_save_post(f): @wraps(f) def decorated(*args, **kwargs): if current_app.login_manager._login_disabled or current_user.is_authenticated: # auth disabled or already logged in return f(*args, **kwargs) # store data before handling login session['form_data'] = request.form.to_dict(flat=False) session['form_path'] = request.path return current_app.login_manager.unauthorized() return decorated@app.route('/article/<int:id>', methods=['GET', 'POST'])@login_required_save_postdef article_detail(id): article = Article.query.get_or_404(id) if session.pop('form_path', None) == request.path: # create form with stored data form = CommentForm(MultiDict(session.pop('form_data'))) else: # create form normally form = CommentForm() # can't validate_on_submit, since this might be on a redirect # so just validate no matter what if form.validate(): # add comment to article return redirect(request.path) return render_template('article_detail.html', article=article)


