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

前端 未结 5 1073
春和景丽
春和景丽 2020-12-29 11:24

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:



        
相关标签:
5条回答
  • 2020-12-29 12:07

    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>
    
    0 讨论(0)
  • 2020-12-29 12:08

    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>
    
    0 讨论(0)
  • 2020-12-29 12:08

    Referring to standard Django example:

    urlpatterns = [
        path('', views.index, name='index'),
    ]
    

    Then template code:

    href="{% url 'index' %}"
    

    will also work.

    0 讨论(0)
  • 2020-12-29 12:13

    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>
    
    0 讨论(0)
  • 2020-12-29 12:19

    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

    0 讨论(0)
提交回复
热议问题