Search code examples
pythondjangorender-to-response

Scope of dictionary passed in render_to_response


def func(user):
    templatename="login.html"
    return render_to_response(templatename,{'user':user},context_instance=RequestContext(request)

What is the scope of the dictionary passed in the render_to_response function in django ? Means could we only use that dictionary in the login.html template or else any template of our app.


Solution

  • The scope of your dict is within login.html only.

    If you want to use access to the user in your template, use something like this:

    {{user}}
    

    If you want to have a dict with a scope in any template, use context processors

    add this in your Settings.py

    import django.conf.global_settings as DEFAULT_SETTINGS
    
    TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
        'utils.custom_context_processors.my_context_processor',
    )
    

    create a folder in your project root dir, lets name it "utils", inside the folder create init.py file and custom_context_processors.py

       +apps
       ....other folders.
       +utils
          ---__init__.py
          ---custom_context_processors.py
    

    custom_context_processors.py

    def my_context_processor(request):
          your_custom_dict = {...}
          return your_custom_dict
    

    With that, your_custom_dict will be available in any template.

    Note: If you only want to access to the user in any place, just do {{request.user}}