Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to get the root path of a site in template?

Tags:

python

django

I want to design a go back home button for my site and how can I get the root path of my site in the template so I can do something like this:

<a href="{{ root_url }}">Go back home</a>

Or I should first figure out the path in my views and then pass it to the template to render by some context. Thanks.

like image 364
Bob Fang Avatar asked Apr 15 '13 07:04

Bob Fang


People also ask

How can I get full path URL in Django?

Use handy request. build_absolute_uri() method on request, pass it the relative url and it'll give you full one. By default, the absolute URL for request. get_full_path() is returned, but you can pass it a relative URL as the first argument to convert it to an absolute URL.

Where is the template directory in Django?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.


4 Answers

I think the proper way here is use the {% url %} tag and I'm assuming that you have a root url in your url conf.

urls.py

url(r'^mah_root/$', 'someapp.views.mah_view', name='mah_view'),

Then in your template:

<a href="{% url mah_view %}">Go back home</a>
like image 65
Henrik Andersson Avatar answered Nov 04 '22 12:11

Henrik Andersson


You should be able to access the get_host() method of the request:

<a href="http://{{ request.get_host() }}">Go back home</a>

Though you could probably also do:

<a href="/">Go back home</a>
like image 32
Nathan Villaescusa Avatar answered Nov 04 '22 12:11

Nathan Villaescusa


I found a trick, Use this tag:

{{ HTTP_HOST }}

you could do:

<a href="{{ HTTP_HOST }}"> back home <a>

or

<a href="{{ HTTP_HOST }}/what_you_want"> back home <a>
like image 24
Charlie Lutaud Avatar answered Nov 04 '22 12:11

Charlie Lutaud


this is what i did:

in urls.py:

from django.contrib import admin
from django.urls import include, path
from django.views.generic import TemplateView

urlpatterns = [
    path('blog/', include('blog.urls')),
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name='landing.html'), name='landing')
]

then, in whatever view:

<a href="{% url 'landing' %}">Site Title</a>

this will resolve to localhost:8000/ or site.domain.com/ whichever you are using, when you click the link

like image 25
p4ndepravity Avatar answered Nov 04 '22 14:11

p4ndepravity