DJANGO NoReverseMatch at/“未找到反向”

2024-10-03 13:18:27 发布

您现在位置:Python中文网/ 问答频道 /正文

第一次和django在一起,需要帮助。。。在

错误:

Reverse for 'anuncio' with arguments '(u'Restaurante Avenida',)' and keyword arguments '{}' not found.

获取方法 Django版本:1.5.2 异常类型:NoReverseMatch 异常值:

找不到参数为“(u'Restaurante Avenida',)”和关键字参数“{}”的“anuncio”的反向操作。在

异常位置:/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py在render中,第424行 Python可执行文件:/usr/bin/Python Python版本:2.7.3

网址:

^{pr2}$

模板:

<a href="{% url 'anuncio' user.userprofile.anuncio %}"> {{user.userprofile.anuncio}} </a>

视图:

def anuncio(request, titulo):

Anuncio = Anuncio.objects.get(titulo = titulo)

variables = RequestContext(request, {'anuncio': Anuncio})

return render_to_response('anuncio.html', variables)

Tags: django版本参数requestusrvariablesrenderarguments
1条回答
网友
1楼 · 发布于 2024-10-03 13:18:27

你的问题是:

url(r'^anuncio/(?P<titulo>\d+)$', anuncio),

\d+匹配数字。在

你需要的是匹配字母和空格。在

试试看

^{pr2}$

还有,这里

Anuncio = Anuncio.objects.get(titulo = titulo)

请使用其他变量名。不要重写模型名。在

anuncio = Anuncio.objects.get(titulo = titulo)

还有一件事,.get()如果没有匹配项,将抛出一个错误。所以,你可以考虑

anuncio = get_object_or_404(Anuncio, titulo = titulo)

阅读更多关于get_object_or_404

最后一件事:这里

<a href="{% url 'anuncio' user.userprofile.anuncio %}"> {{user.userprofile.anuncio}} </a>

我建议使用id而不是anuncio字段。类似user.userprofile.id并将regex保持为\d+-在模型对象中避免空格(并且是唯一的)

相关问题 更多 >