The Python Oracle

How to get the domain name of my site within a Django template?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC P Beethoven - Piano Sonata No 2 in A

--

Chapters
00:00 Question
00:23 Accepted answer (Score 90)
00:37 Answer 2 (Score 135)
01:24 Answer 3 (Score 122)
01:38 Answer 4 (Score 68)
02:27 Thank you

--

Full question
https://stackoverflow.com/questions/1451...

Answer 1 links:
[contrib.sites framework]: http://docs.djangoproject.com/en/dev/ref...

Answer 2 links:
[{{ request.get_host }}]: https://docs.djangoproject.com/en/dev/re...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #django #djangotemplates #djangotemplatefilters

#avk47



ANSWER 1

Score 139


If you want the actual HTTP Host header, see Daniel Roseman's comment on @Phsiao's answer. The other alternative is if you're using the contrib.sites framework, you can set a canonical domain name for a Site in the database (mapping the request domain to a settings file with the proper SITE_ID is something you have to do yourself via your webserver setup). In that case you're looking for:

from django.contrib.sites.models import Site

current_site = Site.objects.get_current()
current_site.domain

you'd have to put the current_site object into a template context yourself if you want to use it. If you're using it all over the place, you could package that up in a template context processor.




ANSWER 2

Score 137


I've discovered the {{ request.get_host }} method.




ACCEPTED ANSWER

Score 91


I think what you want is to have access to the request context, see RequestContext.




ANSWER 4

Score 71


Complementing Carl Meyer, you can make a context processor like this:

module.context_processors.py

from django.conf import settings

def site(request):
    return {'SITE_URL': settings.SITE_URL}

local settings.py

SITE_URL = 'http://google.com' # this will reduce the Sites framework db call.

settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "module.context_processors.site",
    ....
 )

templates returning context instance the url site is {{ SITE_URL }}

you can write your own rutine if want to handle subdomains or SSL in the context processor.