python - 根据 django Rest Framework 中的身份验证方法使用不同的序列化器

标签 python django django-views django-rest-framework django-rest-viewsets

我正在尝试在 django Rest 框架中实现用户配置文件。

用户应该能够请求其他用户的个人资料;但是,由于配置文件包含敏感信息,因此我想限制在非所有者和未经身份验证的用户请求配置文件时返回给他们的信息。

我正在寻找一个可以在 View 方法中运行的测试,该测试将确定该请求使用哪个序列化程序。

我该怎么做?

# models.py
class Profile(models.Model):

    user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile')
    bio = models.CharField(max_length=100)
    # dob is sensitive and should be protected...
    dob = models.DateTimeField(blank=True, null=True)

我的序列化器看起来像这样:

# serializers.py
# Only for the owner...
class ProfileOwnerSerializer(serializers.HyperlinkedModelSerializer):
    user = serializers.ReadOnlyField(source='user.id')
    first_name = serializers.ReadOnlyField(source='user.first_name')
    last_name = serializers.ReadOnlyField(source='user.last_name')

    class Meta:
        model = Profile
        fields = (
            'url',
            'id',
            'dob',     #sensitive
            'user',
            'first_name',
            'last_name',   #sensitive
        )

#For logged in users...
class ProfileSerializer(serializers.HyperlinkedModelSerializer):
    user = serializers.ReadOnlyField(source='user.id')
    first_name = serializers.ReadOnlyField(source='user.first_name')

    class Meta:
        model = Profile
        fields = (
            'url',
            'id',
            'bio',
            'user',
            'first_name',
        )

#For everyone else...
class NonAuthProfileSerializer:
    ...

我会尝试在这里区分它们......

# views.py
class ProfileDetail(APIView):
    """
    Retrieve a profile instance.
    """

    # Can't user permission_classes bc I want to cater to different classes...

    def get_object(self, pk):
        try:
            return Profile.objects.get(pk=pk)
        except Profile.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        profile = self.get_object(pk)
        # is_owner = ???
        # is_authenticated = ???

        # Define the serializer to be ProfileSerializer, ProfileOwnerSerializer, etc.
        serializer = CorrectSerializer(
            profile,
            context={"request": request},
        )
        return Response(serializer.data)

我认为检查请求是否由所有者发送并不困难,因为我可以交叉引用个人资料 ID。

但是,如何检查用户是否登录呢?我尝试在 View 方法中查看 request.user.auth ,但无论请求是否登录,这似乎都是 None

最佳答案

我认为您应该检查request.user.is_authenticated()。填空:

is_owner = profile.user == request.user
is_authenticated = request.user.is_authenticated()

关于python - 根据 django Rest Framework 中的身份验证方法使用不同的序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44686443/

相关文章:

python - 递归遍历多维字典,维数未知

Django Rest Framework - 可浏览的 API 表单总是返回 400 错误请求

django - 无法使用 django-pipeline 缩小 html 文件

python - Nuke自己的python版本,如何安装、添加或包装新模块?

python - Discord 导入 python 问题

python - 正则表达式捕获最多 2 位数字和逗号(如果后跟另一个单词和数字)

python - 在 ListView 中使用 `get_context_data` 过滤结果

django - 从结果中排除整个QuerySet

python - Django 中的反向重定向

python - 如何在 django Updateview 或创建 View 表单中添加 css