The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles

--

Chapters
00:00 How To Get The Domain Name Of My Site Within A Django Template?
00:18 Accepted Answer Score 91
00:29 Answer 2 Score 139
01:06 Answer 3 Score 71
01:44 Answer 4 Score 137
01:51 Thank you

--

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

--

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.