lembon
lembon

Reputation: 125

Queryset in an inherited Django Template

I'm new to Django and Web programming in general. Have googled but could not find the answer I need. Here's the case:

I have a site, where every page in which the user is logged has certain navigation Menu. That's why they extend a template called base_logged.html, which is also extending base.html. The problem is that the navigation menu is partly populated by a database Query.

Is there a way of populating this without making tha query in every logged view ? Or some kinda View inheritance?

Sorry for my poor english.

Upvotes: 2

Views: 582

Answers (2)

Brian Neal
Brian Neal

Reputation: 32379

Another option is to create a custom template tag (probably an inclusion tag) and put it in your base template.

So in your base template you could have something like this:

{% navigation_bar user %}

Upvotes: 3

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53971

You can use context processors (Here's a good example). These allow you to make variables (querysets etc.) available in every view throughout your site. For example, make a file in one of your apps:

some_app.context_processors.my_context_processor.py

from some_app.models import Bar
def my_context_processor():
    return {
        'foo' : Bar.objects.all(),
    }

and in your settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'some_app.context_processors.my_context_processor',
    ...
)

and you now have access in all your views/templates:

{{ foo }}

Upvotes: 0

Related Questions