Search code examples
djangodjango-viewsdjango-generic-views

Django include the same variables in all views


I want to include the same variables in all the views , to avoid repeating , i've been looking at django docs and found the generic display views and i tried it but it doesnt seems to work. Any idea how to do this ?


Solution

  • Write a template context processor:

    def add_foo(request):
        return {'var': 'foo'}
    

    Save this to a file, lets say custom_context.py, put it inside the same directory as your views.py.

    Then, add it to your TEMPLATE_CONTEXT_PROCESSORS setting - make sure you keep the default ones, otherwise other functions may not work. You need to add the Python path, so add yourapp.custom_context.add_foo,

    Now, whenever you return a RequestContext instance (you can do this by using the render shortcut, and all class based views automatically return a RequestContext instance); the variable var will be available in your templates, as {{ var }}.