[Django]-How to put variable from database into base.html template?

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.

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:

Leave a comment