#Custom raise Http404

6 messages · Page 1 of 1 (latest)

minor jay
#

Hello, I have this view

# Last Audit By Line
class LastAuditByLine(APIView):
    def get_object(self, id):
        try:
            return Line.objects.get(id=id)
        except:
            print ("TEST")
            #raise Http404

    @swagger_auto_schema(
        operation_summary="Get Last Audit By Line",
        operation_description="Get Last Audit By Line",
        responses={
            status.HTTP_200_OK: response_200(AuditSerializer(many=True)),
            status.HTTP_404_NOT_FOUND: response_404(),
        },
    )
    def get(self, request, id, format=None):
        if self.get_object(id):
            audit = Audit.objects.filter(line=id).order_by("-audit_date")[:1]
            serializer = AuditSerializer(audit, many=True)
            return JsonResponse(serializer.data, safe=False)```

I want to raise a message like "This line does not exists" in the exception. If I use print method I have this error:

AssertionError at /fjbe_prod_panel/api/audit/2
Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a `<class 'NoneType'>```

fringe sluice
#

Hey @minor jay , I suspect the problem is your if self.get_object(id). If you don't have one, which is the case I imagine, your condition is not true and you are returning nothing and you need to return a response.

minor jay
#

the function get_object always return something, a object from the return or a exception, in case of exception i want to return some custom message

#
class LastAuditByLine(APIView):
    def get_object(self, id):
        try:
            return Line.objects.get(id=id)
        except:
            raise Http404 ```
i have a default 404 message "not found", but i want something more specific, like "Line not found"
minor jay
#

Solved

#

I create that funcion

# Function to handle error message
def error_response(message, status, error=None):
    response = dict()
    response["message"] = message

    return JsonResponse(response, status=status)```