url name to generic class-based views with parameters?

259 views
Skip to first unread message

Mark Stahler

unread,
Jan 18, 2012, 10:46:36 AM1/18/12
to Django users
Can someone explain how to link using url names to class-based views
that include parameters?

Example:

url(r'^video/(?P<pk>\d+)/$', VideoView.as_view()),

works but all my links have to manually have "/video/{{ video.id }}/"
or similar. I cannot get {% url videos %}{{ video.id }} to work with
the following route for some reason.

url(r'^video/(?P<pk>\d+)/$', VideoView.as_view(), name='videos'),

I cant find anything in the documentation about this. Can anyone
explain?

J. Cliff Dyer

unread,
Jan 18, 2012, 10:51:32 AM1/18/12
to django...@googlegroups.com
You need to use {% url videos video.id %} or {% url videos pk=video.id
%}

Tom Evans

unread,
Jan 18, 2012, 10:52:21 AM1/18/12
to django...@googlegroups.com

Your URL takes a parameter, but you are not giving it one. Try:

{% url videos video.id %}

See:

https://docs.djangoproject.com/en/1.3/topics/http/urls/#reverse

and:

https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#url

Cheers

Tom

Andre Terra

unread,
Jan 18, 2012, 10:58:10 AM1/18/12
to django...@googlegroups.com
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#url

# template.html
{% load url from future %}

<p>{% url videos pk=video.pk %}</p>


# ----------------------------

While we're at it, consider defining a more verbose name to the url, such as 'video-detail'. I personally like to map url names to an 'app-model-view' syntax, so you can do something like 'myapp-video-detail' and rename your 'VideoView' to 'VideoDetail'. Then later have 'myapp-video-list' routing to VideoList and so forth. This is also consistent with the generic class based views offered by Django and helps keeping your urls.py organized.



Cheers,
AT



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.


Mark Stahler

unread,
Jan 18, 2012, 11:15:08 AM1/18/12
to Django users
Aha, thanks guys. Very simple now that it was pointed out.
Reply all
Reply to author
Forward
0 new messages