2 回答
TA贡献1829条经验 获得超9个赞
您收到该错误是因为数据库中不再有要更新的会话,您已经删除了其上方 2 行的所有活动会话。要解决这个问题,只需在清理它们时省略当前活动的会话:
@receiver(user_logged_in)
def remove_other_sessions(sender, user, request, **kwargs):
# remove other sessions
old_sessions = Session.objects.filter(usersession__user=user)
if request.session.session_key:
old_sessions = old_sessions.exclude(session_key=request.session.session_key)
old_sessions.delete()
# save current session
request.session.save()
# create a link from the user to the current session (for later removal)
UserSession.objects.get_or_create(
user=user,
session=Session.objects.get(pk=request.session.session_key)
)
TA贡献1744条经验 获得超4个赞
@GwynBleidD 的回答很好!但这里有一个小错误:
if request.session.session_key:
old_sessions = old_sessions.exclude(session_key=request.session.session_key)
应该写成:
if request.session.session_key:
old_sessions = old_sessions.exclude(session_key=request.session.session_key).delete()
else:
old_sessions.delete()
否则当您第二次尝试在同一台计算机上登录时会出现错误。
添加回答
举报