N C
N C

Reputation: 62

Django - generically linking to a specific URL

Is there a generic way to link within Django to a specific URL?

For example I'll use the writing your first Django app if my urls.py looks like the example in the tutorial:

from django.conf.urls import url

from . import views

urlpatterns = [
    # ex: /polls/
    url(r'^$', views.index, name='index'),
    # ex: /polls/5/
    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
    # ex: /polls/5/results/
    url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
    # ex: /polls/5/vote/
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

I want to have a link to the 5th poll I could write the html

<a href='/polls/5/'>link</a>

But I'd rather write something like the below so I can maintain the specific URL from a single place:

<a href='{% url poll5 %}'>link</a>

I assume Django can do this but I'm not sure of the syntax or where to record the url

Upvotes: 0

Views: 62

Answers (2)

Angel Cruijff
Angel Cruijff

Reputation: 158

You can use namespaces in urls, in your project urls.py:

url(r'^polls/', include('polls.urls', namespace="polls")),

And then, in your template:

<a href='{% url 'polls:detail' 5 %}'>link</a>

The 5 can be poll.id or some of your variables.

Upvotes: 2

doniyor
doniyor

Reputation: 37894

you can write <a href='/polls/5/'>link</a> as

<a href='{% url 'details' question.id %}'>link</a>

or

<a href='{% url 'polls:details' question.id %}'>link</a>

if you namespace the polls url

Upvotes: 1

Related Questions