[Django]-Conditional statements in DRF CreateAPIView

1👍

Add this in your PhotoCreateAPIView:

def get_queryset(self):
    if not self.request.user.edu_email:
         return Category.objects.exclude(
            title='University')

2👍

DRF provides the permission_classes to restrict the certain user.

permission.py

from rest_framework.permissions import IsAuthenticated

class PhotoUploadPermissions(IsAuthenticated):
    """ write custom permissions here"""
    def has_permission(self, request, view):
        if not request.user.edu_email:
            queryset = view.get_queryset()
            category_exclude = queryset.exclude(title='University')
            if category_exclude:
                return True
            else:
               return False

viewsets.py

class PhotoCreateAPIView(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    permission_classes = (PhotoUploadPermissions,)
    serializer_class = PhotoCreateSerializer

Leave a comment