每个文章页面都有一个表单供登录用户添加评论。我希望用户能够评论,即使他们还没有登录。它们应该被重定向到登录页面,然后添加评论。但是,当Flask Login的login_required
重定向回页面时,它不是POST请求,表单数据也不会被保留。有没有办法在登录和重定向后保存POST数据?在
@articles.route('/articles/<article_id>/', methods=['GET', 'POST'])
def article_get(article_id):
form = CommentForm(article_id=article_id)
if request.method == 'POST':
if form.validate_on_submit():
if current_user.is_authenticated():
return _create_comment(form, article_id)
else:
return app.login_manager.unauthorized()
r = requests.get('%s/articles/%s/' % (app.config['BASE'], article_id))
article = r.json()['article']
comments = r.json()['comments']
article['time_created'] = datetime.strptime(article['time_created'], '%a, %d %b %Y %H:%M:%S %Z')
for comment in comments:
comment['time_created'] = datetime.strptime(comment['time_created'], '%a, %d %b %Y %H:%M:%S %Z')
return render_template('articles/article_item.html', article=article, comments=comments, form=form)
def _create_comment(form, article_id):
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
data = {'body': form.body.data, 'article_id': article_id, 'user_id': current_user.id}
r = requests.post('%s/articles/comment/' % app.config['BASE'], data=json.dumps(data), headers=headers)
return redirect(url_for('.article_get', article_id=article_id, _anchor='comment-set'))
由于用户必须登录才能发布,因此如果用户没有登录,则只显示“单击此处登录”链接而不是表单会更有意义。在
如果您真的想这样做,您可以在重定向到登录路由时在会话中存储任何表单数据,然后在返回注释路由后检查存储的数据。同时存储请求的路径,这样只有当您返回到同一页时,数据才会恢复。要存储数据,您需要创建自己的
login_required
装饰器。在^{} 将把
MultiDict
数据转储到列表的dict中。它可以存储在session
。在相关问题 更多 >
编程相关推荐