Django,表格重新提交刷新页面?

时间:2018-06-07 17:05:06

标签: django forms

我正在开发一个django应用程序,当我提交表单时它的工作正常但当我刷新页面时,表单再次将数据重新提交到数据库我已经尝试了所有我可以但似乎无法让这个工作正常

我的观点

def _article(request, article_id):
  try:
    article = Article.objects.get(pk=article_id)
    related_articles = Article.objects.filter(tags=article.tags).exclude(pk=article.pk)[:4]
    context['article'] = article
    context['related_articles'] = related_articles
    context['comments'] = article.comments_set.all().order_by('-date')[:4]
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.cleaned_data['comment']
            article.comments_set.create(comment=comment)
            return render(request,'blog/article.html',context)
    else:
        form = CommentForm()        
        context['form'] = form      
    return render(request,'blog/article.html', context)
except Exception as e:
    #write error to file
    return render(request,'blog/404.html')

1 个答案:

答案 0 :(得分:0)

我认为您的问题在于_article视图。尝试将代码更改为此

def _article(request, article_id):
  if request.method == "POST":
    form = CommentForm(request.POST)
    if form.is_valid():
      comment = form.cleaned_data['comment']
      article.comments_set.create(comment=comment)
      return HttpResponseRedirect("</your/url>")
  return render(request,'blog/article.html',context))
  ................