简体   繁体   中英

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

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

settings.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

...

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

...

When I inspect the H1 element, it is empty - nothing was returned. It looks like this:

<h1></h1>

I have tried:

  • loading the function in shell and trying it out (it works)
  • Renaming the function
  • Restarting server
  • {{ test_context_processor['message'] }} (This generates an error)
  • Complaining on 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.

So you just need to do this:

{{ message }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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