Each article page has a form for logged in users to add a comment. I want users to be able to comment even if they haven't logged in yet. They should be redirected to the login page, and then the comment should be added. However, when Flask-Login's login_required
redirects back to the page, it is not a POST request, and the form data is not preserved. Is there a way to preserve the POST data after logging in and redirecting?
@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'))