在/<url>/处没有反向匹配

0 投票
1 回答
1764 浏览
提问于 2025-04-18 09:47

/<url>/ 这个地方出现了 NoReverseMatch 错误。

我想把我的视图重定向到一个带有 GET 请求参数的 URL,但我遇到了上面的错误。

视图代码:

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

URL 配置:

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

我刚开始学习 Django,如果我做错了什么,请告诉我。

1 个回答

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函数的参数是网址的名称(通过name='...'定义),而不是实际的网址,所以这里面绝对不能有斜杠。这样做的好处是,你可以随时更改网址本身,而不会影响到你的代码,因为网址会在所有地方都被更新。

撰写回答