django重定向不重定向

Atm*_*tma 0 django redirect django-urls django-forms

我在视图中有以下形式逻辑:

if request.method == 'POST':
        form = MyForm(request.POST, request.FILES)
        if form.is_valid():

            my_form = form.save()                                          )
            print 'before redirect'
            redirect('customer:department-edit')
            print 'after redirect'
Run Code Online (Sandbox Code Playgroud)

我的网址条目如下所示:

url(r'^departments/$', views.departments_view, name='department-edit'),
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

before redirect
after redirect
Run Code Online (Sandbox Code Playgroud)

为什么在提交表单后不会发生重定向?

ach*_*zot 5

你似乎忘了return在之前添加一个声明redirect().

为什么需要一个return?因为该redirect方法只是a的快捷方式HttpResponseRedirect,所以它的行为与任何其他操作类似:它必须返回响应.

所以你的代码应该是这样的:

...
print 'before redirect'
return redirect('customer:department-edit')
print 'after redirect'
...
Run Code Online (Sandbox Code Playgroud)

请参阅Django文档示例 :)