pythondjangodjango-class-based-viewsrequestcontext

Accessing variables in setting.py from templates with Django 1.4


I'd like to load the site name in a template using:

{{ SITE_NAME }}

In setting.py I have:

SITE_NAME = "MySite"

and

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP

TEMPLATE_CONTEXT_PROCESSORS = TCP + (
    'django.core.context_processors.request',
)

I'm also using Class Based Views to load my view (views.py):

from django.views.generic import TemplateView

class MenuNavMixin(object):
    def get_context_data(self, **kwargs):
        context = super(MenuNavMixin, self).get_context_data(**kwargs)
        return context


class AboutView(MenuNavMixin, TemplateView):
    template_name = "home/about.html"

urls.py:

url(r'^about/$', AboutView.as_view(), name='about'),

I can't access SITE_NAME in home/about.html unless I specifically add it to the context variables with:

import mywebsite.settings

class MenuNavMixin(object):
    def get_context_data(self, **kwargs):
        context = super(MenuNavMixin, self).get_context_data(**kwargs)
        context['SITE_NAME'] = mywebsite.settings.SITE_NAME
        return context

I thought that this wasn't the case if I used:

TEMPLATE_CONTEXT_PROCESSORS = TCP + (
    'django.core.context_processors.request',
)

Can anyone point me in the right direction?


Solution

  • django.core.context_processors.request only adds the request to the context, see the docs.

    Write your won context processor, something like:

    from django.conf import settings    
    
    def add_site_setting(request):
      return {'site_name': settings.SITE_NAME}
    

    Then add that function to TEMPLATE_CONTEXT_PROCESSORS in your settings.py

    Also, I suggest a good habit to get into is using from django.conf import settings rather than explicitly importing your settings file.