I'm struggling to access my session variable in django.
I have two different apps custom_user and article. in my views.py file of custom_user i have declared a session variable.
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
request.session['email'] = user.email
return render_to_response(request, "loggedin.html", locals(),context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/accounts/invalid')
and in my views.py of article app I'm accessing it like this.
def articles(request):
return render_to_response('articles.html',
{'articles':Article.objects.all().order_by('-id'),'last':Article.objects.earliest('-pub_date'), 'loggedin':request.session.email})
my articles.html file inherits base.html file and there i'm using {{loggedin}} to access the variable. I have used {{request.session.email}} but this also doesn't work
What I ultimately want to do is to show the email address of the user loggedin throughout my site in my navbar which is in base.html file.
I'm only getting the user.email value in loggedin.html file which is rendered in auth_view function. but not in any other html file.
You should be accessing it as:
'loggedin': request.session['email']
...in the same way you've defined it.
Also, to prevent an error in the case that it's not set, you can use:
'loggedin': request.session.get('email')
Read more about using session variables in views in the docs.