在基于django rest class的视图中为不同类型的用户提供不同的视图

时间:2017-10-01 14:48:25

标签: django django-rest-framework django-views django-class-based-views

如何使用基于类的视图编写以下视图?

@api_view(['GET', 'POST'])
def hotel_list(request):
    # List all hotel or add new .
    if request.method == 'GET':
        if request.user.is_authenticated:
            # Allow GET request for all authenticated users
            hotels = models.Hotel.objects.all()
            serializer = serializers.HotelSerializer(hotels, many=True)
            return Response(serializer.data)
        return Response({"message": "not authorized"}, status=status.HTTP_401_UNAUTHORIZED)

    elif request.method == 'POST':
        if request.user.is_superuser:
            # Allow POST method for super users only
            serializer = serializers.HotelSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)

            else:
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        return Response({"message": "not authorized"}, status=status.HTTP_401_UNAUTHORIZED)

我想为不同的用户组允许不同的权限。

1 个答案:

答案 0 :(得分:1)

首先创建custom-permissions

permissions.py

class CreateAdminOnly(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.method == 'POST':
            return request.user.is_superuser
        return request.user.is_authenticated

    def has_object_permission(self, request, view, obj):
        if request.method == 'POST':
            return request.user.is_superuser
        return request.user.is_authenticated

在views.py中使用modelviewset

from rest_framework import mixins
from rest_framework.permissions import IsAuthenticated

from .permissions import CreateAdminOnly

class CreateListRetrieveViewSet(mixins.CreateModelMixin,
                                mixins.ListModelMixin,
                                viewsets.GenericViewSet):

    queryset = models.Hotel.objects.all()
    serializer_class = HotelSerializer
    permission_classes = [CreateAdminOnly]