如何在重定向后从模板内的会话中检索数据。实际上可能吗?
这是我的代码:
查看.py:
if request.POST:
user = request.POST.get('username')
passw = request.POST.get('password')
#password1 = ''
try:
userdata = Employee.objects.get(username = user, password = passw)
user_id = request.session["user_id"] = userdata.id
employee_details = Employee.objects.get(id=user_id)
request.session['emp_details'] = employee_details
return HttpResponseRedirect('/home/')
except Employee.DoesNotExist:
state = "Username or password incorrect !"
return render_to_response('login.html',
{'username' : username1,'state' : state},
context_instance = RequestContext(request))
模板:home.html
<body>
<p>
<ul>
<li><a href="">{{request.session.emp_details.emp_name}}</a></li>
</ul>
</p>
<p><a href="/logout/"><button>logout</button></a></p>
</body>
谢谢
确保您已将 django.core.context_processors.request 添加到您的模板上下文处理器。然后您就可以像在代码中一样访问会话变量。
您可能需要将以下行添加到您的视图中
request.session.modified = True
这取决于您的设置中是否有
SESSION_SAVE_EVERY_REQUEST = True
。查看保存会话的文档。
最后,确保将 RequestContext 对象传递给
render_to_response
视图中的 '/home/'
函数。 RequestContext
在模板上下文中包含 request
对象(使其可以在模板中使用 {{ request }}
进行访问)。
警告
虽然这应该可以帮助您让会话正常运行 - 我必须同意 Daniel 的观点,但您不应该像这样进行用户身份验证。使用django自己的身份验证。
我在 settings.py 中有选项 SESSION_COOKIE_SECURE = True 。 将其注释掉,会话变量将被保存