How to use Django Sessions Framework in generic views to send data to another

爱⌒轻易说出口 提交于 2020-08-10 19:18:57

问题


In my Django application, I am trying to use sessions to store a variable in my class view and later use it to send it to a function view.

In the past I have used sessions on function views and now I am trying to use it on a class view.

class someView(CreateView):
    form_class = myForm
    template_name = 'myTemplate.html'
    ...
    ...

    def get_context_data(self, **kwargs):
        request.session['my_var'] = '1234'
        return context

Than I am trying to capture the session variable in another view like this:

def fnView(request):
    data = {}
    new_var = request.session['my_var']
    data = {'key1': new_var}
    return render(request, 'fnVwTemplt.html', data)

And in the template I am trying to display the variable like this:

{{ key1 }}

However I am coming up with the following message in the browser:

KeyError at ...

'my_var'

It is evident that the variable is not getting stored in the session variable.

What I am doing wrong?

PS. Apologies, if my query is not lucid enough.

来源:https://stackoverflow.com/questions/63140183/how-to-use-django-sessions-framework-in-generic-views-to-send-data-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!