Django使用参数反向URL到类视图

9 投票
1 回答
4883 浏览
提问于 2025-04-17 08:46

我刚开始学习Python和Django,有个问题想问一下。
我被要求把函数视图转换成基于类的视图。但是我的链接现在无法正常工作。

这些是来自urls.py的内容:

url(r'^$', ContactIndex.as_view()),
url(r'^add$', ContactAdd.as_view()),
url(r'^([0-9]+)/update$', ContactUpdate.as_view()),
url(r'^([0-9]+)/view$', ContactView.as_view()),

这是我的链接:

{% url rtr_contact.views.ContactView contact.id %}

但是这个链接不管用,显示的是:

Caught NoReverseMatch while rendering: Reverse for 'rtr_contact.views.ContactView' with arguments '(20L,)' and keyword arguments '{}' not found.

1 个回答

18

为了让网址反向解析变得简单,我建议你总是给你的网址模式起个名字。

url(r'^$', ContactIndex.as_view(), name="contact_index"),
url(r'^add$', ContactAdd.as_view(), name="contact_add"),
url(r'^([0-9]+)/update$', ContactUpdate.as_view(), name="contact_update"),
url(r'^([0-9]+)/view$', ContactView.as_view(), name="contact_view"),

然后在模板中:

{% url contact_view contact.id %}

撰写回答