简体   繁体   中英

How do I pass context to a template without actually specifying it in all views?

I have a few views and they all work good and all use templates that extend one base template that outputs the core HTML, the header, footer, navigation and so on. Happy family.

now, I want to play with sessions on the pages and since you can't get access to user's session information from the template without actually passing it from the view (correct me where I'm wrong) I have two options:

  1. add session data to the rest of the bits I pass as context to HTML templates in views (not sure if this is a good way to go)

  2. somehow inherit all existing views from a view that will be always pushing context to templates being processed - this way I don't have to worry about anything else I may want to add to my pages in the future - is this possible?

I'm very new to django and there may be other proper way of doing this - all your suggestions are much appreciated.

I think adding in a context processor is a very easy way to do this.

You could either write your own or use this one: DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST

http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request

Then you will have the request in your template, and could get to the session with request.session

If you do that though, make sure that you pass the RequestContext along in your views to the templates, something like this:

from django.template import RequestContext
def some_view(request):
    # ...
    return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Also modify your settings.py to add in the context processor

TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
    "django.core.context_processors.request",
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM