You want to use template context processors. I couldn't find a very clear description in the Django documentation, but template context processors are basically callables that are called with a request, and return a dictionary of context variables to be made available for all templates (not strictly all templates, but if you use django.shortcuts.render
, you're covered).
Defining your active template context processors is a bit awkward, because you cannot just add your processor to the list of default processors, and you usually want to keep the default ones as well, so you need to dump the entire list of the default processors plus your processor in your settings file:
In your settings:
TEMPLATE_CONTEXT_PROCESSORS = (
# the default processors:
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
# your processor that will populate the context with a list of categories:
"myapp.context_processors.categories",
)
In your myapp/context_processors.py
:
def categories(request):
return {
'categories': Category.objects.all()
}
Modify filenames and category retrieval as needed.