【问题标题】:Duplicate entry in database on refreshing the submitted form in django在 django 中刷新提交的表单时数据库中的重复条目
【发布时间】:2012-12-22 00:24:08
【问题描述】:

在我使用 GET 方法提交表单然后刷新页面后,数据会重新提交 我正在使用 javascript 进行表单验证

我的观点是:

def show(request,post_id):
    try:
        p = post.objects.get(pk=post_id)
        c = comment.objects.filter(blog_id=p)
        if 'cbox' in request.GET:
            c = comment(text=request.GET['cbox'],name=request.GET['cname'],blog=p)
            c.save()
        c_list = comment.objects.filter(blog_id=p)   
    except  post.DoesNotExist:
        raise Http404
    return render_to_response('show.html',{'post':p,'c_list':c_list})

我的表格是:

<form  name="comment" action="" method="get" onsubmit="return validateForm()">
    <input id="carea"  type="text" placeholder="leave a comment" name="cbox" >
    <input id="cb"  type="submit"  value="Post" />
    <input id="cn"  type="text"  placeholder="Name" name="cname">
</form>

我希望当我刷新我的页面时我的数据不应该被重新提交 谢谢

【问题讨论】:

  • 我在这里使用 GET 方法
  • 在 Django 教程 4 docs.djangoproject.com/en/dev/intro/tutorial04 , Using method="post" (as opposed to method="get") is very important, because the act of submitting this form will alter data server-side. Whenever you create a form that alters data server-side, use method="post". This tip isn't specific to Django; it's just good Web development practice.
  • 好的,我一定会记住的,有什么办法可以使用 'GET' 方法解决上述问题吗?
  • 没有。不要使用 GET 向您的数据库添加内容。解决这个问题的正确方法是使用“POST”并在成功时重定向。

标签: django django-forms django-templates django-views


【解决方案1】:

如果你真的坚持使用 GET 提交,这实际上不是一个好方法。您应该使用服务器端的 HttpResponseRedirect 进行请求重定向,这将从 url 中删除查询字符串。这样它就不会恢复表单。

def show(request,post_id):
    try:
        p = post.objects.get(pk=post_id)
        c = comment.objects.filter(blog_id=p)
        if 'cbox' in request.GET:
            c = comment(text=request.GET['cbox'],name=request.GET['cname'],blog=p)
            c.save()
            #Do a redirect here 
            return HttpResponseRedirect("URL of the page you would like to redirect")
        c_list = comment.objects.filter(blog_id=p)   
    except  post.DoesNotExist:
        raise Http404
    return render_to_response('show.html',{'post':p,'c_list':c_list})

【讨论】:

    猜你喜欢
    • 2011-08-14
    • 2011-03-30
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    相关资源
    最近更新 更多