Access Model Data from Django Base Template
I have a model Category
, and I want its objects to always be displayed in a navigation menu in 开发者_StackOverflow中文版my base.html
template (which all of my other templates extend).
I want to learn best-practices so would like to know what the correct/accepted way of providing this data to the template is.
Use a custom context processor:
In context_processors.py:
def categories(request):
return {
'categories': Categories.objects.all()
}
And add it to your settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
# ... django's default context processors
"your_app.context_processors.categories",
)
You could create a custom tag for the categories and place it in the base template. That way you wont have to send a "category" variable to the context on every view ..
Good Luck
Just a heads up for anyone using later versions of Django (i.e. 1.9): the way that Django defines its context processors has changed. Instead of adding to TEMPLATE_CONTEXT_PROCESSORS
you can just add a line to Django's list of context processors:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
'app.context_processors.your_processor', # CHANGE THIS
],
},
},
]
Hope this helps!
精彩评论