How to convey context to a template without actually specifying it in all views?

I have several views, and all of them work well, and all use templates that extend one basic template that displays the main HTML, header, footer, navigation and so on. Happy family.

now, I want to play with sessions on the pages, and since you cannot access the information about the user's session from the template without transferring it from the view (correct me, where I am mistaken) I have two options:

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

  • somehow inherits all existing views from the view, which will always push the context to the templates being processed - so I don’t need to worry about anything else that I can add to my pages in the future - is this possible?

I am very new to django, and there may be another right way to do this - all your suggestions are greatly appreciated.

+4
source share
1 answer

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

You can either write your own or use it: DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST

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

Then you will receive the request in your template and you can go to the session with request.session

If you do, be sure to pass the RequestContext in your template views, 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 change your settings.py to add to the context handler

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

Source: https://habr.com/ru/post/1343490/


All Articles