Reputation: 97
How can i retrieve the data from session within the template after redirecting.Is it possible actually?
Here is my code:
View.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))
template: 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>
Thanks
Upvotes: 0
Views: 2962
Reputation: 13328
Make sure that you've added django.core.context_processors.request to your template context processors. Then you can access session variables just as you do in your code.
You may need to add the following line to your view
request.session.modified = True
This depends on whether you have SESSION_SAVE_EVERY_REQUEST = True
in your settings. Have a looks at the docs for saving sessions.
Lastly, make sure that you're passing a RequestContext object to the render_to_response
function in the view at '/home/'
. The RequestContext
includes the request
object in the template context (making it accessable in the template with {{ request }}
).
WARNING
Whilst this should help you get your sessions working - I have to agree with Daniel, you shouldn't be doing user authentication like this. Use django's own authentication.
Upvotes: 6