[Fixed]-Is the current Site accessible from a template?

27👍

The title of your question presumes that “view” and “template” are interchangeable — they’re not. In order to get the current site in a template, it needs to be added to the context that is used to render the template. If you’re using a RequestContext, you can write a context processor to do this automatically.

You can write a context processor to do this like so:

from django.contrib.sites.models import Site

def site_processor(request):
    return { 'site': Site.objects.get_current() }

Then, add it to your TEMPLATE_CONTEXT_PROCESSORS, and use it like so:

<h3>{{ site.name }}</h3>

0👍

Weirdly, using the bradleyayers processor gave Null results, so instead of using the Site framework, I used the parameter inside the request.

So the processor will look like that :

def host_processor(request):
    return { 'host': request.get_host() }

Hope it helped

Leave a comment