Django2:提交表单后,还有一种更好的方法可以“擦除” POST以停止重新提交

时间:2018-08-28 13:38:04

标签: python django httpresponse

我有一个django应用程序,一页上有几种不同型号的表格。我想要一条“成功”消息,只需在表单提交/验证后添加到上下文中即可轻松做到。但是,这留下了重新提交表单的可能性,这只会在返回页面时产生错误,但仍然使我感到烦恼。

网址:

 url_patterns = [
      re_path(r'^manager/$', Manager.as_view(), name='manager'),

      .......more.....
 ]

views.py:

class Manager(LoginRequiredMixin, View):

    template_name = 'results/manager_templates/manager.html'
    form1 = Form1
    form2 = Form2

    login_url = '/'
    redirect_field_name = 'redirect_to'


    def get(self, request, *args, **kwargs):

        form1 = self.form1()
        form2 = self.form2()

        context = {
                'form1': form1,
                'form2': form,}

        return render(request, self.template_name, context)


    def post(self, request, *args, **kwargs):

        submit_clicked = request.POST.get('submit')

        form1 = self.form1()
        form2 = self.form2()

        context = {}

        if submit_clicked == 'Form 1':

            form1 = self.form1(request.POST)

            if form1.is_valid():
                form1.save()

                context['message'] = 'Form 1 successful'

                # reset the form
                form1 = self.form1()

                # return HttpResponseRedirect(
                #            reverse('results:manager',
                #        ))


            else:
                print('NOT VALID')


        elif submit_clicked == 'Form 2':

             ... do same stuff as above ...


        context['form1'] = form1
        context['form2'] = form2

        return render(request, self.template_name, context)

如果我要取消对HttpResponseRedirect的注释,请在验证并添加表单后像这样:

               return HttpResponseRedirect(
                           reverse('results:manager',
                      ))

然后将其返回到我的页面,如果我刷新了该表单,则不会重新提交。但是,如果不通过url,就无法通过此参数:

即我要写:

               return HttpResponseRedirect(
                           reverse('results:manager',
                           kwargs={'success':'success'}
                      ))

我得到了错误:

Reverse for 'manager' with keyword arguments '{'success': 'success'}' not found. 1 pattern(s) tried: ['manager/$']

,如果我将urls.py更改为:

 url_patterns = [
        re_path(r'^manager/$', Manager.as_view(), name='manager'),
        re_path(r'^manager/(?P<success>)$', Manager.as_view(), name='manager'),

 ] 

我得到了错误:

 Reverse for 'manager' with keyword arguments '{'success': 'success'}' not found. 2 pattern(s) tried: ['manager/(?P<success>)$', 'manager/$']

无论如何,是否需要传递不需要添加到url正则表达式的HttpResponseRedirect变量?还是有其他方法可以“重置”我的request.POST,从而无需使用HttpResponseRedirect即可重新提交表单?

1 个答案:

答案 0 :(得分:1)

如您所见,您应该在成功发布后重定向,以防止重复请求。

更改网址时,您没有在success组中添加任何要匹配的字符。

re_path(r'^manager/(?P<success>\w+)$', Manager.as_view(), name='manager'),

另一个选择是将变量存储在查询字符串中,例如/manager/?success=success,然后您可以在重定向后从request.GET检索值。

您还可以在会话中存储数据,或使用messages framework