praks5432
praks5432

Reputation: 7792

Passing an object in every Django page

I have an object called Groups that is used in every single page on my website. However, Django only passes in Python objects to html through render_to_response and I can't render to response everytime something happens to the groups object.

How do I maintain this object(as in make it respond to adding and deletion) and produce it in every Django template that I have without calling render_to_response?

Upvotes: 3

Views: 641

Answers (4)

Md Moksedul Alam
Md Moksedul Alam

Reputation: 81

#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

Upvotes: 0

MattoTodd
MattoTodd

Reputation: 15209

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

Upvotes: 7

Nicolae Dascalu
Nicolae Dascalu

Reputation: 3535

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

Upvotes: 1

Bernhard Vallant
Bernhard Vallant

Reputation: 50786

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

Upvotes: 1

Related Questions