我有多个用户模型和一个与用户具有OneToOne关系的客户模型。 我已经为用户模型建立了身份验证,其中用户只能编辑/更新/删除其个人资料。但我希望已认证的用户也可以访问(列出/创建/更新等)客户模型。
我对客户的权限类别:
class UpdateCustomerProfile(permissions.BasePermission):
"""Allow customers to edit their own profile """
def has_permission(self, request, view):
"""Check if user is authenticated and has permisson to access customer model """
if view.action == 'list':
return request.user.is_authenticated and request.user.is_superuser
elif view.action == 'create':
return request.user.is_authenticated
elif view.action in ['retrieve', 'update', 'partial_update', 'destroy']:
return request.user.is_authenticated
else:
return False
我的客户视图集:
class CustomerViewSet(viewsets.ModelViewSet):
"""Handle creating reading and updating Users in system"""
serializer_class = serializers.CustomerSerializer
queryset = models.Customer.objects.filter()
permission_classes = (permissions.UpdateCustomerProfile,)
但是我收到一条错误消息:
“详细信息”:“未提供身份验证凭据。”
即使我在标头的“授权”字段中添加令牌,也是如此。
更新:
如果将authentication_classes = (TokenAuthentication,)
添加到我的CustomerViewSet中,我将收到错误消息:
"detail": "You do not have permission to perform this action."
我很困惑,我想利用用户的当前授权来授权创建客户。即只有经过身份验证的用户才能创建其客户个人资料
我该如何解决?
答案 0 :(得分:1)
您应该在视图中添加authentication_classes属性
from rest_framework.authentication import TokenAuthentication
class CustomerViewSet(viewsets.ModelViewSet):
"""Handle creating reading and updating Users in system"""
serializer_class = serializers.CustomerSerializer
queryset = models.Customer.objects.filter()
permission_classes = (permissions.UpdateCustomerProfile,)
authentication_classes = (TokenAuthentication,)