我正在像Django project这样的博客中构建评论系统。每篇文章的末尾都有一个表格(效果很好)。我要这样做,以便在提交表单时刷新页面并显示评论。
(在我刚刚链接到博客的首页之前,评论已保存并显示)
我尝试下面的代码,但是该页面停留在“正在加载”中,然后显示无法访问{{ip_adress}},但是仍然写入了DB。这是我的views.py
def view_article(request, id):
try:
article =get_object_or_404(Article, id=id)
comments = CommentArticle.objects.filter(article_id=id)
form = CommentForm(request.POST or None, initial={'article_id': id})
url = "submit_comment/" + str(id)
if form.is_valid():
message = form.cleaned_data['message']
poster_name = form.cleaned_data['poster_name']
article_id = id
return HttpResponseRedirect(reverse('refresh_article'))
except Article.DoesNotExist:
raise Http404
return render( request, 'blog/view_article.html', locals())
def refresh_article(request, id):
url = 'view_article' + str(id)
return HttpResponseRedirect(reverse(url))
有人有任何线索吗?谢谢!
答案 0 :(得分:0)
您正在进入无限循环。您只需要验证帖子上的表单即可。
def view_article(request, id):
try:
article =get_object_or_404(Article, id=id)
comments = CommentArticle.objects.filter(article_id=id)
form = CommentForm(request.POST or None, initial={'article_id': id})
url = "submit_comment/" + str(id)
if request.method == "POST" and form.is_valid():
message = form.cleaned_data['message']
poster_name = form.cleaned_data['poster_name']
article_id = id
return HttpResponseRedirect(reverse('view_article', kwargs={'id': id}))
except Article.DoesNotExist:
raise Http404
return render( request, 'blog/view_article.html', locals())
此外,您无需重定向到另一个视图,也无需重定向回当前视图。您只需将其重定向回同一视图即可。