Menor
Menor

Reputation: 300

Applying a list of items to every view in views.py

Is there a way to apply a list of items to every view without having to do it manually for every view? I have got a list of items in my navbar and I have to add this to every view to have it displayed in every page:

category_list = Category.objects.all()
context = {
    'category_list': category_list
    }

Upvotes: 1

Views: 59

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477598

This is done through context processors [Django-doc]. These are functions that add items to the context each time a template is rendered. You can for example write such processor in a file named app/context_processors.py (with app the name of your app):

# app/context_processors.py

def category_list(request):
    return {
        'category_list': Category.objects.all()
    }

In the settings.py file, you then register the context processor:

# settings.py

# …

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

Upvotes: 1

Related Questions