【发布时间】:2017-11-15 22:15:21
【问题描述】:
我正在使用 Django 和 DRF,我想检查是否允许用户(普通用户)在通过身份验证后查看其自己的个人资料,并且仅允许查看其个人资料(不允许其他用户)。
serializers.py
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'url', 'username', 'password', 'email', 'groups', 'is_staff')
def create(self, validated_data):
user = super().create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
Views.py
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = (IsUser,)
permissions.py
class IsUser(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_permission(self, request, view, obj):
# View or Write permissions are only allowed to the owner of the snippet.
return obj.owner == request.user
这显然是行不通的,因为是错误的。但我不知道如何让用户查看:
http://127.0.0.1:8000/api/users/7
仅当它是管理员或执行请求的同一用户时。
并且: http://127.0.0.1:8000/api/users/ 仅当它是管理员时。
谢谢!
【问题讨论】:
标签: django django-rest-framework