案例
vip权限认证
数据准备
User表创建两条数据 Group表创建一条数据,name叫vip 操作User和Group的关系表,让1号用户属于1号vip组
permissions.py
from rest_framework.permissions import BasePermission
from django.contrib.auth.models import Group
class IsVipUser(BasePermission):
def has_permission(self, request, view):
if request.user and request.user.is_authenticated: # 必须是合法用户
try:
vip_group = Group.objects.get(name='vip')
if vip_group in request.user.groups.all(): # 用户可能不属于任何分组
return True # 必须是vip分组用户
except:
pass
return False
views.py
from .permissions import IsVipUser
class CarViewSet(ModelViewSet):
permission_classes = [IsVipUser]
queryset = models.Car.objects.all()
serializer_class = serializers.CarSerializer
|