Sorry for posting a naive question!
I saw that I can pass data from a view to a template in 2 ways, one is using a “context” like this:
context={'my_data_label' : my_data_value}
template=loader.get_template('my_template.html')
return HttpResponse(template.render(context,request))
and the second way is just
request.session['my_data_label']=my_data_value
What is the difference? Possibly just that the 2nd way exposes the data to the browsing person
and the first doesn’t? Thank you!
Well, technically yes.
But these approaches have distinct use cases.
While the view is responsible for creating a context to be used to render a template (and more other things) on a single request, the request.session
is used to store data across multiple requests and is not normally used to render variables on a template.
You can read more about sessions on the docs.
Is important to notice that values stored in the session will be persisted, either on your database, cache, file, depending on your configuration.
It’s better to save yourself from shotting on your foot to use the proper way of passing data to templates: the view.
The first way makes the actual object available in the template, allowing you to reference related objects or methods from within a template tag.
The second way would provide a serialized form of the data and not a reference to an actual object. Also, that data is only available to the template if you have the request
context processor active.
Using the standard session backend, neither directly exposes data to the browser.
Thank you for your opinion; I am going with the ‘context’ options,
also because the “session way” was too persistent and somehow
showed up when closing/reopening my page, and confusing me and others.
(unless this was my fault for some reason)
Thank you!