问题
I used the built-in login view that django makes but now I don't know how to set sessions when a user logs in. I was thinking of redirecting a user to a new view that would add these session variables but I don't see that as an ideal fix. Another question I have is: Can I use these session variables in my templates? If not, how would I get that data to the templates?
Also I am using Django 1.11 with python 2.7.
回答1:
I figured out what I needed to do. You need to use signals. Essentially you just need to set a signal that once a user logs in, set the sessions.
Here is how it looks in my code:
@receiver(user_logged_in)
def sig_user_logged_in(sender, user, request, **kwargs):
request.session['isLoggedIn'] = True
request.session['isAdmin'] = user.is_superuser
request.session['team'] = user.teams
request.session['email'] = user.email
isLoggedIn = request.session.get('isLoggedIn',False)
isAdmin = request.session.get('isAdmin',False)
team =request.session.get('team','')
email = request.session.get('email','')
return render(
request,
'registration/login.html',
context = {'isLoggedIn':isLoggedIn,'isAdmin':isAdmin,'team':team,'email':email},
)
Make sure to have these imports:
from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in
Also if you were wondering which file I put this in, it was views.py
来源:https://stackoverflow.com/questions/50533727/how-to-add-session-variables-with-built-in-login-view