Joe Mornin
Joe Mornin

Reputation: 9134

How to avoid repeating URL structures in Django

The Django tutorial explains how to create a basic poll app. The templates in the tutorial frequently use hard-coded URL structures—for instance:

<form action="/polls/{{ poll.id }}/vote/" method="post">

And:

<a href="/polls/{{ poll.id }}/">Vote again?</a>

What would be the best way to refactor this code to avoid repeating /polls/ throughout the templates?

Upvotes: 1

Views: 479

Answers (2)

super9
super9

Reputation: 30111

Alternatively, name your urls.

See: https://docs.djangoproject.com/en/dev/topics/http/urls/#naming-url-patterns

In the template, the url would look like:

<a href="{% url poll_url poll.id %}">Vote again?</a>

In the view, the url can be retrieved using the reverse method like:

reverse('poll_url', args=[poll.id])

Upvotes: 0

Mark Lavin
Mark Lavin

Reputation: 25164

Use the url template tag https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#url

Upvotes: 3

Related Questions