Tomasz Brzezina
Tomasz Brzezina

Reputation: 1534

How to create correct path in Django template

I'm trying to create menu in template which leads to some subpages:

<a href="/">HOME</a> <a href="/about/">O NAS</a> <a href="/rules/">REGULAMIN</a> <a href="/faq/">FAQ</a> <a href="/docs/">DOKUMENTY</A> <a href="/contact/">KONTAKT</a>

And it works only when I put it into main folder, so the url is http://example.org/about/.

When I put it into some subfolder it goes wrong:

http://example.org/subfolder/about/ works, but links in menu leads still http://example.org/about/ which is correct behaviour.

relative path is not working, because it adds instead of replacing last part of URL e.g.: http://example.org/subfolder/about/rules/.

If I would know what url it would be placed, I can hardcode it into template, but I'm sure that it will work in two places with different "subfolders", and I want to make it working in any environment.

I'm trying to find solution, but it leads me to TEMPLATE_CONTEXT_PROCESSORS which isn't working for me, and i'm not sure if it is exactly what I'm trying to get, so I don't dive to deep into.

Upvotes: 1

Views: 61

Answers (2)

Tomasz Brzezina
Tomasz Brzezina

Reputation: 1534

The solution was adding

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP

TEMPLATE_CONTEXT_PROCESSORS = TCP + (
    'django.core.context_processors.request',
)

into settings.py

This was found here: https://stackoverflow.com/a/9233283/354420

In template you can use views.about or name if defined.

Upvotes: 0

marcusshep
marcusshep

Reputation: 1964

Name your URL's.

url(r'^about', views.about, name="about")

Then use the URL template tag to generate the appropriate URL for each name.

{% url 'about' %}

Upvotes: 1

Related Questions