Skip to main content
 首页 » 编程设计

python之DJANGO NoReverseMatch 位于/"reverse not found"

2024年11月01日28pander-it

第一次使用django,需要一些帮助...

错误:

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

请求方式:GET Django 版本:1.5.2 异常类型:NoReverseMatch 异常值:

使用参数“(u'Restaurante Avenida',)”和关键字参数“{}”找不到“anuncio”。

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

网址:

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

模板:

<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) 

请您参考如下方法:

你的问题在这里:

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

\d+ 匹配数字。

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

尝试

url(r'^anuncio/(?P<titulo>[\w ]+)$', anuncio, name = 'anuncio'), 

还有,这里

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+ - 模型对象中避免空格(并且是唯一的)