I have a class based APIVIEW and I want to prevent a normal user (isstaff=false, is_superuser=false) from creating a customer.

class CustomerPageView(APIView):
    # permission_required = 'api.view_customer'
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    def get(self, request):
        customer = Customer.objects.all()

        # Check if there is a customer
        if not customer.exists():
            return JsonResponse([], safe=False)
        customer_serializer = CustomerSerializer(customer, many=True)
        return JsonResponse(customer_serializer.data, safe=False)
    
    def post(self, request):
        data = json.loads(request.body.decode('utf-8'))
        company_name, contact_person, contact_number, company_address = data.values()
        company_name = company_name.strip()

        # Check if item exists
        chk_company_name = Customer.objects.filter(company_name__iexact=company_name)
        if chk_company_name:
            return JsonResponse({'label':'company_name', 'message':'Customer Already Exists'}, status=500)
        
        if len(company_name) == 0:
            return JsonResponse({'label':'company_name', 'message':'Invalid Entry'}, status=500)
        
        createCustomerInstance = Customer.objects.create(
            company_name=company_name,
            contact_person=contact_person,
            contact_number=contact_number,
            company_address=company_address,
        )

        return JsonResponse({'message': f"Successfully added {company_name}", 'variant': 'success'})

enter image description here this user currently don't have any permissions. However when I logged in as normal user I can still create a customer.

0

There are 0 best solutions below