문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

Not sure what gave you that impression. The request context processor does exactly what it says on the tin: adds the request to the context processor. There's nothing that says it will do anything with the SITE_NAME setting - especially as that isn't even a standard setting.

If you want that to be added by a context processor, then you can write your own - it'll only be two lines of code.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top