3

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?

infrared
  • 3,566
  • 2
  • 25
  • 37
praks5432
  • 7,246
  • 32
  • 91
  • 156

4 Answers4

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

MattoTodd
  • 14,467
  • 16
  • 59
  • 76
1

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

Bernhard Vallant
  • 49,468
  • 20
  • 120
  • 148
1

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

Community
  • 1
  • 1
Nicolae Dascalu
  • 3,425
  • 2
  • 19
  • 17
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