这就是我所做的。来自文档的参考
为项目创建权限类
项目/permissions.py
from rest_framework import permissions
class IsAuthenticatedOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
# Read permission - always allow for GET request
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions - only if authenticated
return request.user and request.user.is_authenticated()
现在在视图中使用这个 PermissionClass
@permission_classes((IsAuthenticatedOrReadOnly, ))
class ShopViewSet(viewsets.ModelViewSet):
queryset = Shop.objects.all()
serializer_class = ShopSerializer