Django Python - Add table values inside common header

Viewed 30

Maybe trying to do something not possible but basically, I created a file header.html that I include all other my html pages e.g. {% include "project/header.html" %} This works fine the challenge is that on header.html I want to put a dropdown menu with values coming from a model. it works fine if I invoke directly header.html but not when inside other page.

header.html

...
<ul>
{% for club in clubs.all %}
<li> <a href="#">{{ club.name }}</a></li>
{% endfor %}
...

views.py

from django.http import HttpResponse
from django.shortcuts import render

from .models import Club
def index(request):
    clubs = Club.objects
    return render(request, 'project/index.html',{'clubs':clubs})

Is this even possible? Thanks in advance

1 Answers

You can write a context processor [Django-doc] for this. This is a method that is each time added to the request.

In an app (any app that you use) you can define a context processor:

# app/context_processors.py

def all_clubs(request):
    from app.models import Club
    return {
        'clubs': Club.objects.all()
    }

then you register this context processor in the settings.py file, such that it will be added to the context in each render(…) call:

# settings.py

# …

TEMPLATES = [
    {
        # …
        'OPTIONS': {
            'context_processors': [
                # …
                'app.context_processors.all_clubs'
            ]
        }
        # …
    }
]

Now you do no longer need to pass clubs in each render call. It will automatically be added. Since QuerySets are lazy, it will not hit the database if your template does not use clubs.

Related