3

I'm working on a web page. There will be contact in the footer like email or telephone. This footer should be everywhere so it is in the base.html which is being extended by each template/html.

I've created a table called ContactAdmin, to provide simple and straightforward interface for admin to change his contact info. And here is the problem.

The base.html has no view (it is just for extending) so I don't know how to put there variable - email, telephone from table ContactAdmin. I thought about putting it into every view which is a huge overkill in my opinion.

So how to make Django to read this variables from database and put them into base.html?

The ContactAdmin table should have just one row

Milano
  • 18,048
  • 37
  • 153
  • 353

2 Answers2

4

You dont need to edit all views. Exactly for this scenario, django has template context processors. The advantage here is, since the base template is still part of the templating language, and it has access to the Context, you just need to set these variables in your custom context processor, and everything should work as is.

Some examples on how to write your custom context processors:

Community
  • 1
  • 1
karthikr
  • 97,368
  • 26
  • 197
  • 188
2

You can use context processors for this purpose. For instance:

yourapp/context_processors.py

def contact(request):
    from yourapp.models import ContactAdmin
    contacts = ContactAdmin.objects.all()

    return {
        'contacts': contact,  # Add 'contacts' to the context
    }

yourproject/settings.py

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'yourapp.context_processors.contact',
            ]
        }
    }
]

I guess these contact settings are not going to change very often. So you may be interested in caching the result of the query as well.

Antoine Pinsard
  • 33,148
  • 8
  • 67
  • 87