NoReverseMatch位于/ <url> / </url>

时间:2014-06-14 14:26:44

标签: python django

/<url>/

的NoReverseMatch

我正在尝试将我的视图重定向到带有get请求参数的网址我收到了上述错误,

查看:

return HttpResponseRedirect(reverse('corporate_contribution/?event_id=',args=(event_id, )))

URL:

url(r'^corporate_contribution/$','corporate_contribution', name='corporate_contribution'),

我是Django的新手,如果我做错了,请告诉我。

1 个答案:

答案 0 :(得分:1)

查看参数和查询字符串不是一回事。反向函数中的argskwargs是传递给视图函数的参数。查询字符串(即网址中?之后的参数)将被解析为request.GET字典。

一个简单的解决方案是将您的查询字符串附加到网址:

return HttpResponseRedirect('%s?event_id=%s' % (reverse('corporate_contribution'), event_id))

另一种方法,即经常使用的方法,是捕获部分网址并将其用作视图的参数:

urls.py:

url(r^corporate_contribution/(?P<event_id>[\d]+)/$, 'corporate_contribution', name='corporate_contribution')

views.py:

def corporate_contribution(request, event_id):
    ...

def other_view(request, *args, **kwargs):
    ...
    return HttpResponseRedirect(reverse('corporate_contribution',args=(event_id,)))

这将确保您的视图始终通过event_id。请注意,传递给reverse函数的参数是url的名称(由name='...'定义),而不是实际的url本身,因此它绝对不应包含斜杠。这样您就可以在不破坏代码的情况下更改网址,因为网址将随处更改。

相关问题