Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django context processor doesn't display new context values in template

Tags:

EDIT: Updated now that I've narrowed down the problem to the context processor variable not being available to a template that I'm loading with a custom tag.

I'm using Django 1.11 and this is my first time trying to use a custom context processor.

The problem is that the context variable I'm supposed to be adding from the context processor does not return anything from within a template loaded from a custom tag. I don't receive any errors.

So below {{ testcontext }} should return "IT WORKED!" and does so in my base.html template, but returns nothing in the template loaded with @register.inclusion_tag().

settings.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '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',
                'appname.context_processors.test_context',
            ],
        },
    },
]

context_processors.py:

def test_context(request):
    return {'testcontext': 'TEST WORKED!'}

tags.py

from django import template

from appname.models import Category

register = template.Library()

@register.inclusion_tag('template.html')
def load_category(selected_slug=None):
    return {
        'categories': Category.objects.all(),
        'selected':selected_slug,
    }

views.py:

from django.views.generic import ListView
from appname.models import MyModel

class MyView(ListView):
    model = MyModel

urls.py

from django.conf.urls import url

from appname.views import MyView

urlpatterns = [
    url(r'^$', MyView.as_view(), name="home"),
]

template.html

{{ testcontext }}
like image 739
Will S. Avatar asked Dec 21 '17 08:12

Will S.


1 Answers

So the problem was in my custom tag not carrying over the context when loading template.html. So the below code fixes it and my variable from the context processor is now working as expected.

tags.py

from django import template

from appname.models import Category

register = template.Library()

@register.inclusion_tag('template.html', takes_context=True)
def load_category(context,selected_slug=None):
    return {
        'categories': Category.objects.all(),
        'selected': selected_slug,
        'testcontext': context['testcontext'] 
    }
like image 184
Will S. Avatar answered Sep 22 '22 12:09

Will S.