Question

I want a menu on all my pages in Django 1.6.

In the menu I also want to include some objects from my database. I know I can make extend ListView and get the objects, and I know I can set variables in get_context_data, but how can I make the objects available on ALL my pages. I think it would be stupid to set the context_data in every single view.

The result of my menu should be something like:

Home
Users
    User 1
    User 2
    User 3
Help
Questions
    Question 1
    Question 2
    Question 3
About

What would be a good way to do it? Middlewares? Template tags?

Was it helpful?

Solution

You are looking for a custom template context processor:

You should write a function like this:

#file: my_context_processors.py

def menu_data(request):

    return {
            'menu': calculate_menu( request ),  #<-- menu is appended 
                                                #    to your context
                                                #    for all templates
             }

Where calculate_menu returns an object with menu items and subitems ( dictionary ? ) Remember than you have path, user and other information into request.

Then include your custom processor on app settings template context processors:

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    #"django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.csrf",
    'django.core.context_processors.request',
    'my_app.my_context_processors.menu_data',   #<---- here
    )

At this time, menu object is available on all your templates.

Do not panic about terms, it is not difficult and this is the right way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top