Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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 }}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading