[Django]-Passing an object in every Django page

7👍

write a template context processor:

#my_context_processors.py

def include_groups(request):
    #perform your logic to create your list of groups
    groups = []
    return {'groups':groups}

then add it in your settings file:

#settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
     "django.core.context_processors.auth",
     "django.core.context_processors.debug",
     "django.core.context_processors.i18n",
     "django.core.context_processors.media",
     "path.to.my_context_processors.include_groups",
)

now a variable groups will be available to you in all your templates

1👍

If you need data added to more than one template contexts you should look into achieving that via your own template context processor.

1👍

You need to create template context processor to pass an object to each request. Here is some example

0👍

#tu_context_processor.py

from setting.models import Business


def include_business(request):
    business = Business.objects.all().last()
    return {'business': business}

in your settings file:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        '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',
                'core.tu_context_processor.include_business',
            ],
        },
    },
]

now a variable business will be available to you in all your templates
tested in Django 4

Leave a comment