避免多个表单提交的最佳做法是什么,同时在表单提交后显示消息通知?
为避免多个表单提交,我使用重定向而不是渲染
return redirect(post.get_absolute_url())
但是,如果添加消息然后重定向,则不会显示任何消息。以下是整个视图设置:
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
# List of active comments for this post
comments = post.comments.filter(active=True)
if request.method == 'POST':
# A comment was posted
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
messages.success(request, 'Comment successfully added')
return redirect(post.get_absolute_url())
else:
comment_form = CommentForm()
return render(request, 'blog/post/detail.html', {'post': post,
'comments': comments,
'comment_form': comment_form})
在视图文件中,我捕获所有要调试的消息
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
当然,如果我使用渲染而不是重定向,一切正常,但如果我刷新页面,我仍然会遇到“多表单提交”问题。