表单重新提交数据Django

时间:2018-09-11 07:56:25

标签: django django-forms

我有一个查看功能,当刷新页面时,它会重新提交数据。

def home(request):
    if request.method == 'POST':
        form = ListForm(request.POST or None)

        if form.is_valid():
            form.save()
            all_items = List.objects.all
            messages.success(request,('Item has been added to List'))
            return render(request, 'home.html', {'all_items': all_items})

    else:
        all_items = List.objects.all
    return render(request, 'home.html',{'all_items':all_items})

请提供有关如何防止这种情况的任何想法。现在,我已阅读的内容已弃用了render_to_response。

谢谢

1 个答案:

答案 0 :(得分:1)

防止表单重新提交并不是什么新鲜事物,the canonical solution is the post-redirect-get pattern:成功发布后,您将返回重定向HTTP响应,从而迫使用户的浏览器进行获取。规范的Django“表单处理程序”视图(在函数版本中)为:

def yourview(request):
    if request.method == "POST":
        form = YourForm(request.POST)
        if form.is_valid():
            do_something_with_the_form_data_here()
            return redirect("your_view_name")
        # if the form isn't valid we want to redisplay it with
        # the validation errors, so we just let the execution
        # flow continue...

   else:
       form = YourForm()

   # here `form` will be either an unbound form (if it's a GET
   # request) or a bound form with validation errors.
   return render(request, "yourtemplate.html", {'form': form, ...})