21

Given a website, how would you get the HOST of that in a django template, without passing that var from the view?

http://google.com/hello --> {{ BASE_URL }} ==> 'http://google.com'
David542
  • 104,438
  • 178
  • 489
  • 842

5 Answers5

28

This has been answered extensively in the following post

There are several ways of doing it:

  1. As david542 described **
  2. Using {{ request.get_host }} in your template **
  3. Using the contrib.sites framework

** Please note these can be spoofed

Elwin
  • 810
  • 1
  • 8
  • 15
  • thanks for the comprehensive answer/options. Could you please add a bit on 'how' the first two can be spoofed? – David542 Feb 19 '15 at 21:49
  • The first two depend on the request meta data, which essentially is coming from a browser. This can be fixed with the allowed hosts setting, on which more info can be found here https://docs.djangoproject.com/en/1.7/ref/settings/#allowed-hosts – Elwin Feb 19 '15 at 22:03
  • Without `()` in django templates, i. e. `{{ request.get_host }}`. – Jens-Erik Weber Apr 27 '22 at 22:06
23

None of these other answers take scheme into account. This is what worked for me:

{{ request.scheme }}://{{ request.get_host }}
jdeanwallace
  • 1,146
  • 9
  • 13
4

URL: google.com/hello

In Template:

{{ request.get_full_path() }}
return /hello

OR

{{ request.get_host() }}
return google.com

In view:

from django.contrib.sites.shortcuts import get_current_site

def home(request):
    get_current_site(request)
    # google.com

    # OR
    request.get_host()
    # google.com

    # OR
    request.get_full_path()
    # /hello
1

You can get the request object in your template by adding in the following TEMPLECT_CONTEXT_PROCESSOR middleware in your settings:

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

Here is some documentation on it. Then you can call in your template:

{{ request.META.HTTP_NAME }}

And that will give you the base url.

David542
  • 104,438
  • 178
  • 489
  • 842
1

In your template to get base url

{{ request.get_host() }}