Francois Paulsen
Francois Paulsen

Reputation: 185

Django: How to display context data from one template on multiple templates

I have to use the context update method in every view in order to show data from my sidebar.html template that I include in other templates as part of my navigation. Is there another way in which I can include the data from my sidebar.html other templates as well? I'm going to have to do this for a lot of templates and does not seem like the right way to do it.

blog/views.py

class BlogPostDetailView(DetailView):
    model = BlogPost
    context_object_name = "post"
    template_name = "blog/single.html"

    def get_context_data(self, **kwargs):
        context = super(BlogPostDetailView, self).get_context_data(**kwargs)
        context.update(
            {
                "categories": Category.objects.all().annotate(
                    post_count=Count("categories")
                )
            },
        )

        return context

Core/views.py

class HomeView(ListView):
    model = BlogPost
    context_object_name = "posts"
    template_name = "core/index.html"
    paginate_by = 4
    ordering = ["-date_posted"]

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        context.update(
            {
                "categories": Category.objects.all().annotate(
                    post_count=Count("categories")
                )
            },
        )

        return context

core/includes/sidebar.html

...
<div class="sidebar-box ftco-animate">
    <h3 class="sidebar-heading">Categories</h3>
    <ul class="categories">
        {% for category in categories %}
        <li><a href="#">{{ category.title }}
                <span>({{ category.post_count }})</span></a></li>
        {% endfor %}
    </ul>
</div>
...

Upvotes: 0

Views: 1635

Answers (1)

Kishan Parmar
Kishan Parmar

Reputation: 820

use djangos context processor for that using that you can get that data in all the template base without passing the context in all the template

for example i want site settings it includes settings of site like contactus and emailaddress all of that column so i will make a context processor for that

make new file

context_processor.py

in that

from foo import Configuration

def code_base(request):

    conf = Configuration.objects.all()
    return {'conf':conf}

Note: also add that context processor in the settings.py under templates on the context processor list 

so from now on you dont have to pass 'conf' in all template as context you can directly access the {{ conf }} without passing context in template

Upvotes: 1

Related Questions