[Answered ]-Django context processors available globally to templates in ALL apps

1👍

I was able to finally get an answer in the Unofficial Django Discord Forum, so I thought I would post the solution here in case others run into the same problem.

It turns out that by setting the context_processors in just one app, anything used by it becomes available globally. So based on my above example:

(1) In the project’s settings.py, I add in the context_processors section:

'home.context_processors.site_settings'

(2) I add toward the end of settings.py:

COMPANY_NAME = ‘My Company Name’

(3) Considering my first app in the project is called home, I add a folder in that app’s directory called contenxt_processors.py, and add the following into the file:

from django.conf import settings

def site_settings(request):
    return {
        'company_name': settings.COMPANY_NAME,
    }

(4) Now I have the constant available to me in all templates, in all of my apps, without having to repeat the process in other apps. It seems counter-intuitive, but it works like a charm. So in any template that I add {{ company_name }}, it will display My Company Name, as I set it in the settings.py file.

(5) Now if I want to add other constants, I simply add them to the settings.py file under COMPANY_NAME = ‘My Company Name’. For example, I may now add

COMPANY_URL = 'www.mydomain.com'

and then I also add it to the context_processors.py file in my primary app folder. Such that it now looks like this:

from django.conf import settings

def site_settings(request):
    return {
        'company_name': settings.COMPANY_NAME,
        'company_url': settings.COMPANY_URL,
    }

That was it, and now I have {{ company_name }} and {{ company_url }} available in all of my templates

👤mck

Leave a comment