這就是我所做的。從documentation
創建權限類參考該項目
項目/ 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