简体   繁体   English

自定义 Django 上下文处理器不返回任何值

[英]Custom Django context processor not returning any value

I have written a custom context processor to return some frequently-used variables.我编写了一个自定义上下文处理器来返回一些常用的变量。 I have followed multiple tutorials and read the official documentation, but nothing is happening: the context processor is either not loading or not returning any value.我遵循了多个教程并阅读了官方文档,但没有发生任何事情:上下文处理器要么没有加载,要么没有返回任何值。 I am not getting any errors.我没有收到任何错误。

app name: auctions应用名称:拍卖

context_processors.py context_processors.py

def test_context_processor(request):
    return {
        'message': 'Hello, world.'
    }

settings.py设置.py

...

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
                'django.template.context_processors.media',
                'auctions.context_processors.test_context_processor'
            ],
        },
    },
]

...

layout.html布局.html

...

<h1>{{ test_context_processor.message }}</h1>

...

When I inspect the H1 element, it is empty - nothing was returned.当我检查 H1 元素时,它是空的 - 没有返回任何内容。 It looks like this:它看起来像这样:

<h1></h1>

I have tried:我努力了:

  • loading the function in shell and trying it out (it works)在 shell 中加载 function 并试用(它有效)
  • Renaming the function重命名 function
  • Restarting server重启服务器
  • {{ test_context_processor['message'] }} (This generates an error) {{ test_context_processor['message'] }} (这会产生错误)
  • Complaining on SO投诉 SO

All I can think of is that every tutorial example is using the context processor to return a list of objects from a database, whereas I'm just returning a plain string value.我能想到的是,每个教程示例都使用上下文处理器从数据库返回对象列表,而我只是返回一个纯字符串值。 But surely that can't matter, right?但这肯定没关系,对吧? Thanks!谢谢!

You were "nearly there" with this, in your template:在您的模板中,您“几乎就在那里”:

{{ test_context_processor['message'] }}

The only problem with this is that context processors just add data directly to the template context - which is essentially a dictionary holding your template variables.唯一的问题是上下文处理器只是将数据直接添加到模板上下文中——它本质上是一个保存模板变量的字典。 They don't scope or namespace it under anything, certainly not a name corresponding to the name of the context processor.他们没有 scope 或命名空间下的任何东西,当然不是与上下文处理器名称相对应的名称。

So you just need to do this:所以你只需要这样做:

{{ message }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM