Django 权限:如何使扩展用户仅更新和查看配置文件?

Django Permissions: How to make extended User only to update and view profile?

我正在尝试为我创建的扩展用户编写自定义权限,以便只允许它查看(检索)用户个人资料并更新它。但是,使用我当前的代码,它不允许用户查看它的配置文件。我刚开始使用 Django,无法提出解决方案,所以请告知哪里出了问题?下面是我的代码:

Permissions.py

from rest_framework import permissions


class UserPermissions(permissions.BasePermission):

    def has_permission(self, request, view):
        return request.user and request.user.is_authenticated()

    def has_object_permission(self, request, view, obj):
        return obj == request.user

views.py

from rest_framework.permissions import IsAuthenticated, IsAdminUser
from .permissions import UserPermissions


class UserList(generics.ListCreateAPIView):

    queryset = UserProfile.objects.all()
    model = UserProfile
    serializer_class = UserSerializer
    paginate_by = 10
    permission_classes = (IsAuthenticated, IsAdminUser,)

    def get_queryset(self):

        queryset = UserProfile.objects.all()
        search_query = self.request.query_params.get('user', None)

        if search_query is not None:
            queryset = queryset.filter(username__istartswith=search_query)
        queryset = queryset.order_by('username')
        return queryset


class UserDetail(generics.RetrieveUpdateAPIView):

    queryset = UserProfile.objects.all()
    model = UserProfile
    serializer_class = UserSerializer
    permission_classes = (IsAuthenticated, UserPermissions,)


class UserDelete(generics.DestroyAPIView):

    queryset = UserProfile.objects.all()
    model = UserProfile
    serializer_class = UserSerializer
    permission_classes = (IsAuthenticated, IsAdminUser,)

Serializers.py

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserProfile

    def create(self, validated_data):

        user = super(UserSerializer, self).create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user

models.py

from django.contrib.auth.models import User

class UserProfile(User):

    class Meta:

        ordering = ["username"]
        db_table = 'user'

    createdby = models.CharField(max_length=100, blank=True, default="")
    updatedon = models.DateTimeField(blank=True, auto_now=True)
    is_admin = models.BooleanField(default=False)

因为UserProfile != User, :

class UserPermissions(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):
        # obj is UserProfile instance not User instance.
        # so, this method will always return False
        return obj == request.user

其他代码包含 UserProfile 也是错误的。 关于 extend User 你可以按照文档: https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-user https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#auth-custom-user