Search code examples
pythondjangodrydjango-class-based-views

Django - context - How to pass context to ALL views


Because I need to cycle through a model table to render the options/nav-links in the navbar, and the navbar is rendered on every page. Hence, I find myself passing in the same context to every class-based view and it's quite repetitive:

class Xxx:
    ...
    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['categories'] = Category.objects.get_categories_with_item()
        return context

Is there a DRYer way to do this? Thanks!!

PS. and also, is *args necessary in get_context_data method? I've seen code with it and code without


Solution

  • You can to write custom context processor

    from django.core.context_processors import request
    
    def custom_processor(request):
        categories = Category.objects.get_categories_with_item() 
        return {"categories": categories}
    

    You need to add this function to TEMPLATES -> "OPTIONS" -> "context_processors"