djangodjango-modelsviewdjango-context

Django: proper way to get context data from another view


I have a menu that its content is obtained from a view, and that menu is in every view. Is there a proper way to get its context data to all my views without having to code again the same thing in every view?

I was thinking returning that context on a JsonResponse of another view and parse it in every template with JavaScript like an API, but is it a good practice?


Solution

  • You can make use of context processors [Django-doc] to pass values to the context in every view.

    You can define a context processor in any app, for example in an app named app:

    # app/context_processors.py
    
    def menuitems(request):
        return {
            'menuitems': ['item1', 'item2', 'item3']
        }

    Next you can register the context processor in the settings.py:

    # settings.py
    
    # …
    
    TEMPLATES = [
        {
            # …
            'OPTIONS': {
                'context_processors': [
                    # …
                    'app.context_processors.menuitems'
                ]
            }
            # …
        }
    ]

    and then you can use the menuitems variables in all template:

    <!-- all views -->
    <ul>
    {% for menuitem in menuitems %}
        <li>{{ menuitem }}</li>
    {% endfor %}
    </ul>