Django reverse url with parameters to a class base

2020-04-02 11:19发布

问题:

I just started learning python and django and I have a question. I got the assignment to turn function views into class based views. But my links wont work now.

these are from 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()),

This is my link :

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

but this doesnt work it says:

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

回答1:

To make url reversing easy, I recommend that you always name your url patterns.

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

Then in the template:

{% url contact_view contact.id %}