根据之前项目在models里面添加一个录入人字段:operator=models.ForeignKey("auth.User",on_delete=models.CASCADE)
序列化文件里面也要加入字段operator
operator=serializers.ReadOnlyField(source="operator.username")#重写operator获取用户名
视图函数里面添加权限和自定义权限
from rest_framework import permissions
from app001.permission import IsOwnerOrReadOnly
class PublisherList(generics.ListCreateAPIView):
queryset = models.Pbulisher.objects.all()
serializer_class = serializers.PublisherSerializer
permission_classes = (permissions.IsAuthenticated,IsOwnerOrReadOnly)#权限IsAuthenticated必须登录,后面是自定义权限
def perform_create(self,serializer):
serializer.save(operator=self.request.user) #默认把发请求的用户设置成录入人员
class PublisherDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = models.Pbulisher.objects.all()
serializer_class = serializers.PublisherSerializer
permission_classes = (permissions.IsAuthenticated,IsOwnerOrReadOnly)#权限IsAuthenticated必须登录,后面是自定义权限
自定义权限
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""自定义权限只允许对象的所有者编辑它"""
def has_object_permission(self, request, view, obj):
#读取权限允许任何请求,
#所以我们总是允许GET,HEAD或OPTIONS请求
if request.method in permissions.SAFE_METHODS:
return True
#只有该出版社的录入者才允许写权限
return obj.operator==request.user
在实际项目中是对token进行认证可以查看rest_framework文档中的API-Authentication