django.contrib.auth.models.AnonymousUser 给用户

django.contrib.auth.models.AnonymousUser to User

我需要获取用户信息,但我只有 request.user,这给了我一个 django.contrib.auth.models.AnonymousUser。我知道 AnonymousUser 的 id、用户名……是空的。如何获取用户信息?

您不能直接使用 AnonymousUser,这 class 只是成为 Django 请求中的默认用户所必需的。

如果您有用户 ID,请执行以下操作:

from django.core.exceptions import PermissionDenied
from django.contrib.auth.models import User

[... other code there ...]

    try:
        user = User.objects.get(pk=user_id)
    except User.DoesNotExist:
        raise PermissionDenied

[... other code there ...]