我创建了一个LoggedInUser
模型,并给了related_name
。当我尝试访问时,它给我一个
RelatedObjectDoesNotExist at /
User has no logged_in_user.
models.py
User = settings.AUTH_USER_MODEL
# Model to store the list of logged in users
class LoggedInUser(models.Model):
user = models.OneToOneField(User, related_name='logged_in_user',on_delete=models.CASCADE)
# Session keys are 32 characters long
session_key = models.CharField(max_length=32, null=True, blank=True)
def __str__(self):
return self.user.username
signals.py
@receiver(user_logged_in)
def on_user_logged_in(sender, request, **kwargs):
LoggedInUser.objects.get_or_create(user=kwargs.get('user'))
@receiver(user_logged_out)
def on_user_logged_out(sender, **kwargs):
LoggedInUser.objects.filter(user=kwargs.get('user')).delete()
在自定义 middleware.py
中stored_session_key = request.user.logged_in_user.session_key # Error in these line.
错误:
django.contrib.auth.models.User.logged_in_user.RelatedObjectDoesNotExist: 用户没有“ login_in_user”。
版本:
django == 2.1.2
python == 3.6.7
我哪里出错了?
答案 0 :(得分:0)
试试看
def on_user_logged_in(sender, request, **kwargs):
u, created = LoggedInUser.objects.get_or_create(user=kwargs.get('user'))
u.save()
user_logged_in.connect(on_user_logged_in)