Reputation: 465
I'm writing a blog - it has top bar menu which contains Categories
objects. The problem is that Every view in this blog has to return a context
with Categories.objects.all()
. Is there a better way to solve that problem (adding same queryset to context to every view)? My code:
models.py
class Category(models.Model):
name = models.CharField(max_length=60)
slug = models.SlugField(unique=True, blank=True, null=True)
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
{% block menu %}
<div id="menu">
{% for item in categories %}
<a href="{% url 'category_detail' item.slug %}">
<div class="category">{{ item.name }}</div>
</a>
{% endfor %}
</div>
{% endblock %}
{% block content %}
<!-- I want extend only that block in every view -->
{% endblock %}
</body>
</html>
Upvotes: 1
Views: 321
Reputation: 8525
You can send it via context processors. Just add a file in your root project next to settings.py
, name it context_processor.py
and inside, you write a function
with request
as argument, it must return a dict.
from your_app.models import Category
def global_context(request):
cateogries = Category.objects.all()
context = {'categories':categories,}
return context
then you call it from settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
# codes,
'OPTIONS':{
'context_processors':[
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages', 'django.contrib.messages.context_processors.messages',
# Insert your TEMPLATE_CONTEXT_PROCESSORS here
#'project_name.file_name.function_name',
'project_name.context_processors.global_context',
],
}
},
]
Upvotes: 4
Reputation: 6865
Create a mixin class by inheriting ContextMixin
from django.views.generic.base import ContextMixin
class CategoryMixin(ContextMixin):
"""
A mixin class that adds categories to all the views that use it.
"""
def get_context_data(self, **kwargs):
ctx = super(CategoryMixin, self).get_context_data(**kwargs)
ctx['categories'] = Categories.objects.all()
return ctx
Now in every view where you need categories inherit CategoryMixin
class BlogListView(ListView, CategoryMixin):
model = Event
template_name = 'pages/home.html'
def get_context_data(self, **kwargs):
ctx = super(BlogListView, self).get_context_data(**kwargs)
ctx['view_specific'] = 'something'
return ctx
...
Upvotes: 1