[Django]-How to get getting base_url in django template

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

24👍

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

{{ request.scheme }}://{{ request.get_host }}

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.

1👍

In your template to get base url

{{ request.get_host() }}

Leave a comment