# Hande Error Http404 in view

**URL:** <https://forum.djangoproject.com/t/hande-error-http404-in-view/16543>\
**Category:** Forms & APIs\
**Created:** [October 19, 2022, 8:24am UTC](https://forum.djangoproject.com/t/hande-error-http404-in-view/16543 "2022-10-19T08:24:50Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Inferi92](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/inferi92/32/8546_2.png) [@Inferi92](https://forum.djangoproject.com/u/Inferi92)\
**Post date:** [October 19, 2022, 8:24am UTC](https://forum.djangoproject.com/t/hande-error-http404-in-view/16543/1 "2022-10-19T08:24:50Z")

</div>

Hi have this view:

```auto
# Last Audit By Line
class LastAuditByLine(APIView):
    def get_object(self, id):
        try:
            return Line.objects.get(id=id)
        except Line.DoesNotExist:
            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)

```

On the funcion get\_object I want to handle the error and add some custom message like “That Line Does Not Exists”.  
If I add a print instead of Http404 I have this error:

```auto
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'>

```

---

<div class="post-metadata">

**Author:** ![leandrodesouzadev](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/leandrodesouzadev/32/8981_2.png) [@leandrodesouzadev](https://forum.djangoproject.com/u/leandrodesouzadev)\
**Post date:** [October 19, 2022, 10:56am UTC](https://forum.djangoproject.com/t/hande-error-http404-in-view/16543/2 "2022-10-19T10:56:01Z")

</div>

Hey there!

And what if instead of doing:

> [@Inferi92](#):
>
> ```auto
> raise Http404
> 
> ```

You did:

```auto
raise Http404("That Line Does Not Exists”)

```

---

<div class="post-metadata">

**Author:** ![leandrodesouzadev](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/leandrodesouzadev/32/8981_2.png) [@leandrodesouzadev](https://forum.djangoproject.com/u/leandrodesouzadev)\
**Post date:** [October 19, 2022, 11:02am UTC](https://forum.djangoproject.com/t/hande-error-http404-in-view/16543/3 "2022-10-19T11:02:24Z")

</div>

Just a clean code tip here:

You don’t need this `if` statement here:

> [@Inferi92](#):
>
> ```auto
> def get(self, request, id, format=None):
> if self.get_object(id):
> 
> ```

Your `get_object` function will always return an object, or will raise a exception (and if is raised, then the function won’t return to the caller, and that’s your `get` function).  
So you can:

```auto
def get(self, request, id, format=None):
    line = self.get_object(id)
    audits = Audit.objects.filter(line=line).order_by("-audit_date")[:1]
    # or even use the forward relation manager, if you didn't set the `related_name` on the line field of the Audit model
   # line.audit_set.order_by("-audit_date")[:1]
    ...

```

---

<div class="post-metadata">

**Author:** ![Inferi92](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/inferi92/32/8546_2.png) [@Inferi92](https://forum.djangoproject.com/u/Inferi92)\
**Post date:** [October 19, 2022, 1:29pm UTC](https://forum.djangoproject.com/t/hande-error-http404-in-view/16543/4 "2022-10-19T13:29:37Z")

</div>

Hi @leandrodesouzadev thanks for your help.  
I have done some tests and I get the result I was waiting for.  
Create this function:

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

    return JsonResponse(response, status=status)

```

and inside the view I made some changes

```auto
def get_object(self, id):
        try:
            Line.objects.get(id=id)
        except Line.DoesNotExist:
            return 1

    @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) == 1:
            message = "This Line Does Not Exist"
            return error_response(
                message=message,
                status=status.HTTP_404_NOT_FOUND,
            )
        else:
            audit = Audit.objects.filter(line=id).order_by("-audit_date")[:1]
            serializer = AuditSerializer(audit, many=True)
            return JsonResponse(serializer.data, safe=False)

```

This solutions works perfectly
