Django {{site}} template context not working?
Asked Answered
D

2

8

This should be a super simple one. I'm pretty sure that I've used this context successfully in the past in my templates for linking purposes. My belief was that this was built into the RequestContext instance somehow or other.

the SITE_ID record in my settings file is correct. I've included a RequestContext instance for all my views and i have included the contrib.auth app, which may be relevant in this case.

Is the {{site}} context somehow built in or should I query the Sites object for the instance?

thanks all, Brendan

Dipietro answered 23/2, 2011 at 17:33 Comment(0)
M
24

Django strives to be explicit, so it is unlikely that it would set any context by it self. There has to be context processor which sets {{site}} in settings.CONTEXT_PROCESSORS. I've checked django.core.context_processors and django.contrib.sites and there is no such processor which sets site. So you probably had a third-party context processor which does that.

It is very easy to write context processor:

myproject/context_processors.py:

    from django.contrib.sites.models import Site

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

myproject/settings.py:

    CONTEXT_PROCESSORS += ['myproject.context_processors.site']
Malady answered 23/2, 2011 at 18:29 Comment(1)
thank Skimantas, that definitely answers my question. I didn't use any third party context processors, so the previous ability to use site is still a mystery. I'm going to look into that. Great answer to my overall question, though.Dipietro
N
2

It wont hurt to create a custom context processor

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

Note that get_current() uses SITE_ID, which is a global setting in the project (defined in settings.py). If you are going to support multi-sites, you need the SITE_ID variable to change its value depending on the current site being accessed.

Here is a nice snippet that will make it work.

Noami answered 23/2, 2011 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.