在 django 中创建我自己的上下文处理器

发布于 2024-09-02 20:23:05 字数 910 浏览 6 评论 0原文

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

有人告诉我编写自己的上下文处理器是执行此操作的最佳方法,但我遇到了一些问题。

我的设置文件如下所示

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”的函数。

看起来

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

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

{{ say_hello }}

现在,这在我的模板中没有呈现任何内容。

我的观点看起来像

from django.shortcuts import render_to_response

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

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.

My settings file looks like this

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

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

Which looks like

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.

My view looks like

from django.shortcuts import render_to_response

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

套路撩心 2024-09-09 20:23:05

您编写的上下文处理器应该可以工作。问题出在你的看法上。

您确定您的视图是通过 RequestContext 渲染的吗?

例如:

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

上面的视图不会使用TEMPLATE_CONTEXT_PROCESSORS中列出的上下文处理器。确保您提供一个 RequestContext ,如下所示:

def test_view(request):
    return render_to_response('template.html', context_instance=RequestContext(request))

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))
路弥 2024-09-09 20:23:05

根据 django 文档 您可以使用render 作为快捷方式,而不是带有 context_instance 参数的 render_to_response:

或者,使用 render() 快捷方式,该快捷方式与使用 context_instance 参数调用 render_to_response() 相同,强制使用 RequestContext。

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.

晚雾 2024-09-09 20:23:05

假设您有这样的文件结构:

YourDjangoProject
├───project
│   ├───__init__.py
│   ├───asgi.py
│   ├───settings.py
│   ├───urls.py
│   └───wsgi.py
├───.env
├───manage.py
└───db.sqlite3

1) 在任何位置创建一个 context_processors.py 文件

我将在项目文件夹中创建一个(使用 settings.py):

YourDjangoProject
└───project
    ├───...
    └───context_processors.py

2) 创建一个context_processors.py 中接受 HttpRequest 对象作为参数并返回字典的函数

上下文处理器只是一个接受 HttpRequest 对象作为参数并返回字典的函数。

像这样:

# project/context_processors.py

def site_email(request):
    return {'site_email': '[email protected]'}

3) 将其添加到 settings.py 中的 context_processors 设置(出于安全原因位于底部)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'config' / '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',
                'project.context_processors.site_email',  # <- New context processor here
            ],
        },
    },
]

现在,您将能够访问整个网站上每个 django 模板上的“site_email”模板变量。

祝您编码愉快!

Let's say you have a file structure like this:

YourDjangoProject
├───project
│   ├───__init__.py
│   ├───asgi.py
│   ├───settings.py
│   ├───urls.py
│   └───wsgi.py
├───.env
├───manage.py
└───db.sqlite3

1) Anywhere, create a context_processors.py file

I'll create one in the project folder (with settings.py):

YourDjangoProject
└───project
    ├───...
    └───context_processors.py

2) Create a function in context_processors.py that accepts a HttpRequest object as an argument and returns a dictionary

A context processor is just a function that accepts an HttpRequest object as an argument and returns a dictionary.

Like this:

# project/context_processors.py

def site_email(request):
    return {'site_email': '[email protected]'}

3) Add this to your context_processors setting in settings.py (at the bottom for security reasons)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'config' / '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',
                'project.context_processors.site_email',  # <- New context processor here
            ],
        },
    },
]

Now you'll be able to access the 'site_email' template variable on every single django template across your whole site.

Happy coding!

睡美人的小仙女 2024-09-09 20:23:05

从 Django 1.8 开始,您可以像这样注册自定义上下文处理器:

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',
            ],
        },
    },
]

假设您的上下文处理器位于应用程序 wwwcontext_processors.py

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

中二柚 2024-09-09 20:23:05

如果您使用 Django 的 render_to_response() 快捷方式用字典的内容填充模板,则默认情况下将向您的模板传递一个 Context 实例(而不是 RequestContext) 。要在模板渲染中使用 RequestContext,请使用 render() 快捷方式,该快捷方式与使用 render_to_response() 进行调用相同code>context_instance 参数强制使用 RequestContext

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文