【问题标题】:How to obtain a user instance in django application如何在 django 应用程序中获取用户实例
【发布时间】:2021-09-02 10:18:59
【问题描述】:

我正在尝试在 django 应用程序中获取个人资料页面的用户实例,但我发现实现该功能有些困难。我有以下代码块:

models.py

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE, default="")
    image = models.ImageField(upload_to="images/user_profile_pics/", default="images/default_profile_pics/default.jpg")
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)

    def __str__(self):
        return f'{self.lastname} profile'

序列化器.py

class user_profile_serializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = '__all__'

views.py

class user_profile(generics.GenericAPIView):
    serializer_class = user_profile_serializer
    def get(self, request, *args, **kwargs):
        user = self.get_serializer(request.user).data
        if request.user.is_authenticated:
            return Response(user, status=status.HTTP_200_OK)
        else:
            pass

urls.py

urlpatterns = [
    path('profile/', user_profile.as_view(), name="user-profile"),
]

当我评估个人资料网址时,我收到一条错误消息'AnonymousUser' object has no attribute 'data' 我尝试了几种方法,但都没有奏效。请问,如何从数据库中获取特定用户?

【问题讨论】:

  • 如果用户未登录,您希望在user.data (-> request.user.data) 中出现什么,即。它是AnonymousUser 的实例?也许您应该先检查用户是否已登录(request.user.is_authenticated
  • 我试过了,还是不行,我什至遇到了NoneType错误
  • 定义“不工作”

标签: python django django-rest-framework profile


【解决方案1】:

request.user 在用户未登录时是 AnonymousUser。在这种情况下,该对象没有 data 属性。因此你得到的错误。您可以做的一件事是检查request.user.is_authenticated,如果用户未通过身份验证,则返回一些其他值/或无。并在尝试访问 user.data 值之前尝试登录。

【讨论】:

  • 谢谢@moddayjob。我在上面的问题中更新了views.py。我试图检查用户是否经过身份验证,但得到类似的错误。 Got AttributeError when attempting to get a value for field 'firstname' on serializer 'user_profile_serializer'. The serializer field might be named incorrectly and not match any attribute or key on the 'AnonymousUser' instance. Original exception text was: 'nonymousUser' object has no attribute 'firstname'. 请问我执行的代码还有其他部分错误吗?我已经以管理员身份登录
  • 看,在这一行user = self.get_serializer(request.user).data,您正在尝试序列化用户对象。但是用户在这一行仍然是匿名用户。因为您在下一行检查了if request.user.is_authenticated:。所以你得到那个错误。交换这些行,它可能会起作用。你不会得到错误,但你也不会得到序列化的用户对象,因为你没有登录。
猜你喜欢
  • 1970-01-01
  • 2019-11-08
  • 2018-04-25
  • 2015-02-23
  • 2021-08-08
  • 2021-06-10
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
相关资源
最近更新 更多