Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

my model has attributes fields as file and the person who uploaded it ,in my case i would want to show the error no file found on my website front end when there is no data in model but instead it is taking me to this error i have implemented my code like this

@api_view(('GET',))
def template_view(request):
    data = Mymodel.objects.first()
    try:
        if data:
            response = HttpResponse(
                data.file,
                content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, '
                             'application/vnd.ms-excel',

            )
            return response
    except FileNotFoundError:
        raise ValueError('No file found')

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Perhaps instead of re-raising a ValueError, you can return a 400 error
e.g.

@api_view(('GET',))
def template_view(request):
    data = Mymodel.objects.first()
    try:
        response = HttpResponse(
            data.file,
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, '
                             'application/vnd.ms-excel',

        )
        return response
    except (FileNotFoundError, AttributeError):
        return HttpResponse("No File Found", status=400)

I’d also catch the AttributeError rather than put an if statement for the data

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading