Harton Harton - 1 year ago 102
HTML Question

Managing django urls

I am making a personal site. I have a blog page(site.com/blog), where I have a list of my blog posts. If I want to check a blog post simple enough I can click it and the code:

<a href="/blog/{{ obj.id }}"><h1>{{ obj.topic_title }}</h1></a>

will get me there. Also if I want to go to my contacts page (site.com/contacts). Easy enough I click nav contacs button and I go there

<a href="/contacts">Contacts</a>

but if I enter a blog post (site.com/blog/1), I am using the same template and if I want to go to my contacts page I have to yet again click the

<a href="/contacts">Contacts</a>

link, but that will port me to a 404 page site.com/blog/contacts . How do I deal with this problem without harcoding every single page

Answer Source

Use the built-in Django url template tag, which takes the view name and returns an absolute path to it.

Returns an absolute path reference (a URL without the domain name) matching a given view and optional parameters.

You can give it a view name and any of its view parameters as well. This is much better than how you link to the blog page:

{% url 'blog-view-name' obj.id %}

This ensures that if you ever change the structure of your views, it will still not break your links.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download