Django NoReverseMatch与get_absolute_url有关

时间:2018-02-22 16:54:47

标签: python django python-3.x

我知道这可能是最常见的Django问题,但我不能为我的生活做出这样的决定。我快点做。

# urls.py
urlpatterns += [
    path('certs/', views.certs, name='certs'),
    path('certs/<int:id>/', views.view_cert, name='view_cert'),
]

-

# views.py
@login_required
def certs(request):
    certs = Certification.objects.filter(user=request.user)
    return render(request, 'certs.html', {'certs': certs})


def view_cert(request, id):
    cert = Certification.objects.get(id=id)
    return render(request, 'view_cert.html', {'cert': cert})

-

# certs.html
{% if certs %}
    <ul class="list-group">
    {% for cert in certs %}
        <li class="list-group-item">{{ cert.name }}</li>
        <!--<a href="{% url cert.get_absolute_url %}" class="list-group-item list-group-item-action">{{ cert.name }}</a>-->
    {% endfor %}
    </ul>
{% endif %}

-

# models.py
class Certification(models.Model):
...
def get_absolute_url(self):
    return reverse('crypto:view_cert', kwargs={'id': self.id})

例如,当我加载/ certs / 1时,代码工作正常。但是,当我尝试加载/证书(应该列出用户证书)时,我得到一个NoReverseMatch。

Reverse for '/certs/1/' not found. '/certs/1/' is not a valid view function or pattern name.

更令人困惑的是,我可以从shell中完全加载它:

>>> from django.urls import reverse
>>> reverse('crypto:view_cert', kwargs={'id': 1})
'/certs/1/'
>>>

有人有什么想法吗?

1 个答案:

答案 0 :(得分:6)

因为get_absolute_url的结果是url字符串,所以在模板中不需要{% url %}来使用它。只需将其替换为:

<a href="{{ cert.get_absolute_url }}" class="list-group-item list-group-item-action">{{ cert.name }}</a>