2

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.

lembon
  • 125
  • 7

2 Answers2

3

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 %}
mustafa.0x
  • 1,476
  • 2
  • 17
  • 30
Brian Neal
  • 31,821
  • 7
  • 55
  • 59
0

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 }}
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
  • That sounds nice. I will try it and then post my experience. Doesn't matter that not every page will make sense with the query? Because the query is based in the user... – lembon Mar 23 '12 at 00:10
  • `... def my_context_processor(request): ...` – Ryan Allen Sep 30 '13 at 18:02