'Django include template tag include multiple context object
I`m building a blog template page, which will include the Post list context object and the Category list context object.
I`m using class-based view in the views.py:
class CatListView(ListView):
model = Category
context_object_name = 'categories'
template_name = 'blog/category.html'
class PostListView(ListView):
model = Post
context_object_name = 'post_list'
template_name = 'blog/blog.html'
urls.py:
urlpatterns = [
path('', views.PostListView.as_view(), name='blog'),
...
]
using the include tag to include the category template in blog.html:
{% extends 'base.html'%}
{% block content %}
<main class="main-content">
<div class="container mt-8">
<div class="row">
<div class="col-lg-8">
<h2>Post list</h2>
{% for post in post_list %}
{{ post.title }}
{% endfor %}
</div>
<div class="col-lg-4">
{% include "blog/category.html"%}
</div>
</div>
</div>
</main>
{% endblock %}
category.html:
<ul class="mt-8">
{% for cat in categories %}
<li>{{ cat.title }}</li>
{% endfor %}
</ul>
I just cant pass the category context in the post.html template. maybe Im can do it with the function-based view, but is it possible to pass multiple contexts into one template using only a class-based view?
Solution 1:[1]
To return more than one context variables you can always override get_context_data method like this:
class PostListView(ListView):
# rest of the code
queryset = Post.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['extra_variable'] = # get extra context
return context
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
