Django redirect()快捷方式不再工作了?

时间:2017-01-17 11:12:43

标签: python django

如果要在视图中重定向,请执行以下操作:

@secure_required
def school_index(request, school_id):

    school = get_object_or_404(School, pk = school_id)    
    redirect('schools:school_events', kwargs= {'school_id': school.id} )

然后我得到错误:

 Request Method:    GET Request URL:    http://127.0.0.1:8008/schools/20/
 Django Version:    1.9.6 Exception Type:   NoReverseMatch Exception
 Value: 
 Reverse for 'school_events' with arguments '()' and keyword arguments '{'kwargs': {'school_id': 20}}' not found. 
1 pattern(s) tried:['schools/(?P<school_id>\\d+)/events/$']

的url:

urlpatterns = [

    url(r'^(?P<school_id>\d+)/$', views.school_index, name='school_index'),
    url(r'^(?P<school_id>\d+)/events/$', views.school_events, name='school_events'),
]

正如我所说,redirect()只是一个快捷方式,它应该返回给定对象,url或视图的HttpResponseRedirect。我提供了正确的视图名称,关键字参数但Django无法匹配url。什么可能是错的?

P.S。如果使用HttpResponseRedirect:

,一切正常
@secure_required
def school_index(request, school_id):

    school = get_object_or_404(School, pk = school_id)
    url = reverse('schools:school_events', kwargs= {'school_id': school.id})
    return HttpResponseRedirect(url)

0 个答案:

没有答案