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.
I've discovered the {{ request.get_host }}
method.
I think what you want is to have access to the request context, see RequestContext.
Complementing Carl Meyer, you can make a context processor like this:
from django.conf import settings
def site(request):
return {'SITE_URL': settings.SITE_URL}
SITE_URL = 'http://google.com' # this will reduce the Sites framework db call.
TEMPLATE_CONTEXT_PROCESSORS = (
...
"module.context_processors.site",
....
)
you can write your own rutine if want to handle subdomains or SSL in the context processor.
I know this question is old, but I stumbled upon it looking for a pythonic way to get current domain.
def myview(request):
domain = request.build_absolute_uri('/')[:-1]
# that will build the complete domain: http://foobar.com
The variation of the context processor I use is:
from django.contrib.sites.shortcuts import get_current_site
from django.utils.functional import SimpleLazyObject
def site(request):
return {
'site': SimpleLazyObject(lambda: get_current_site(request)),
}
The SimpleLazyObject
wrapper makes sure the DB call only happens when the template actually uses the site
object. This removes the query from the admin pages. It also caches the result.
and include it in the settings:
TEMPLATE_CONTEXT_PROCESSORS = (
...
"module.context_processors.site",
....
)
In the template, you can use {{ site.domain }}
to get the current domain name.
edit: to support protocol switching too, use:
def site(request):
site = SimpleLazyObject(lambda: get_current_site(request))
protocol = 'https' if request.is_secure() else 'http'
return {
'site': site,
'site_root': SimpleLazyObject(lambda: "{0}://{1}".format(protocol, site.domain)),
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With