在 Django 中创建我自己的上下文处理器 [英] creating my own context processor in django

查看:24
本文介绍了在 Django 中创建我自己的上下文处理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经到了需要将某些变量传递给我的所有视图(主要是自定义身份验证类型变量)的地步.

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 processor was the best way to do this, but I am having some issues.

我的设置文件是这样的

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.contrib.messages.context_processors.messages",
    "sandbox.context_processors.say_hello", 
)

如您所见,我有一个名为context_processors"的模块和一个名为say_hello"的函数.

As you can see, I have a module called 'context_processors' and a function within that called 'say_hello'.

看起来像

def say_hello(request):
        return {
            'say_hello':"Hello",
        }

我认为我现在可以在我的观点范围内执行以下操作是否正确?

Am I right to assume I can now do the following within my views?

{{ say_hello }}

现在,这在我的模板中没有任何效果.

Right now, this renders to nothing in my template.

我的观点看起来像

from django.shortcuts import render_to_response

def test(request):
        return render_to_response("test.html")

推荐答案

您编写的上下文处理器应该可以工作.问题在于你.

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

你确定你的视图是用 RequestContext 呈现的吗?

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

例如:

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

上面的视图不会使用 TEMPLATE_CONTEXT_PROCESSORS 中列出的上下文处理器.确保您像这样提供 RequestContext :

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))

这篇关于在 Django 中创建我自己的上下文处理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆