creating my own context processor in django

后端 未结 4 1963
青春惊慌失措
青春惊慌失措 2020-11-29 00:01

I have come to a point where I need to pass certain variables to all of my views (mostly custom authentication type variables).

I was told writing my own context pro

相关标签:
4条回答
  • 2020-11-29 00:34

    The context processor you have written should work. The problem is in your view.

    Are you positive that your view is being rendered with RequestContext?

    For example:

    def test_view(request):
        return render_to_response('template.html')
    

    The view above will not use the context processors listed in TEMPLATE_CONTEXT_PROCESSORS. Make sure you are supplying a RequestContext like so:

    def test_view(request):
        return render_to_response('template.html', context_instance=RequestContext(request))
    
    0 讨论(0)
  • 2020-11-29 00:34

    According to the django docs you can use render as a shortcut instead of render_to_response with the context_instance argument:

    Alternatively, use the render() shortcut which is the same as a call to render_to_response() with a context_instance argument that forces the use of a RequestContext.

    0 讨论(0)
  • 2020-11-29 00:45

    Since Django 1.8 you register your custom context processors like this:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [
                'templates'
            ],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                    'www.context_processors.instance',
                ],
            },
        },
    ]
    

    assuming your context processor is in app www in context_processors.py

    0 讨论(0)
  • 2020-11-29 00:51

    If you’re using Django’s render_to_response() shortcut to populate a template with the contents of a dictionary, your template will be passed a Context instance by default (not a RequestContext). To use a RequestContext in your template rendering, use the render() shortcut which is the same as a call to render_to_response() with a context_instance argument that forces the use of a RequestContext.

    0 讨论(0)
提交回复
热议问题