如何使用内置登录视图添加会话变量 [英] How To Add Session Variables with Built-In login view
问题描述
我使用了django内置的登录视图,但是现在我不知道如何在用户登录时设置会话.我正在考虑将用户重定向到将添加这些会话变量的新视图,但是我不认为这是理想的解决方案.我还有一个问题:我可以在模板中使用这些会话变量吗?如果没有,我该如何将这些数据保存到模板中?
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?
我也在python 2.7中使用Django 1.11.
Also I am using Django 1.11 with python 2.7.
推荐答案
我想出了我需要做的事情.您需要使用信号.本质上,您只需要设置一个信号即可在用户登录后设置会话.
这是我的代码中的样子:
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},
)
确保导入以下内容:
from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in
另外,如果您想知道我将其放入哪个文件,那就是views.py
Also if you were wondering which file I put this in, it was views.py
这篇关于如何使用内置登录视图添加会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!