Display tasks count in base.html

Viewed 75

I have a Task model and in my base template I want to display the number of tasks and a list of the tasks.

How can I do this without having to import the Task model manually through my context dictionary in every view?

Right now I have this:

base.html

<span class="notification">{{tasks.count}}</span>

views.py

def dashboard_view(request):
    context = {
        "tasks": Task.objects.all(),
    }
    return render(request=request, template_name='main/index.html', context=context)

As one might imagine, having this in every view night not be practical.

1 Answers

You can make a context processor [Django-doc]. For example in a certain app you can write:

# app/context_processors.py

def task_count(request):
    from app.models import Task
    return {
        'tasks': Task.objects.all()
    }

then you can register this context processor in the settings.py:

# settings.py

# …

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

For every template you render, it will thus make a variable tasks available, that will contain a QuerySet with all tasks. Since QuerySets are lazy, it will not execute the query if you do not need it.

Related