amirhossein delkhosh
amirhossein delkhosh

Reputation: 39

how to loop through a python list of nothing

I am trying to create a online class and want to loop through the list of the classes to see if he/she been registered or not

problem is if the list be empty it will return an error

I am using django and django-restframework

here is my code

@api_view(['POST'])
@permission_classes([IsAuthenticated,])
def createOrderForOnlineClasses(request):
    user = request.user
    data = request.data
    Class = OnlineClass.objects.get(id= data["classId"])

    orderCred = {
        'pin' : 'somepin',
        'amount' : int(Class.totalPrice),
        'callback' : 'http://localhost:3000/verify/',   
    }

    for i in user.userprofile.onlineClass.all():
        if i == Class:
            return Response({"details": "allready registered"}, status=status.HTTP_400_BAD_REQUEST)
        else:
            try:
                response = requests.post("URL_TO_SOMEWHERE", data=orderCred)
                if response.status_code == 200 and not response.text.replace('-',"").isdigit():
                    registeredClass = RegisterStudentForOnlineClass.objects.create(
                        user=user,
                        totalPrice = int(Class.totalPrice),
                        transId = response.text,
                        onlineClassName= Class
                    )
                    serializer = RegisterForClassSerializer(registeredClass , many=False)
                    return Response(serializer.data)
                else:
                    return Response({"details": ""} , status= status.HTTP_400_BAD_REQUEST)
            except Exception as e:
                return Response({"details": e})

here is the returned error

Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`

Thank you :)

Upvotes: 0

Views: 59

Answers (1)

Henty
Henty

Reputation: 603

when you call for i in user.userprofile.onlineClass.all() and it is empty it will simply pass the loop. Your problem is actually that you just need a default response for the scenario that user.userprofile.onlineClass.all() is empty.

Simply put a default expected response after the for loop

Upvotes: 2

Related Questions