Home > OS >  Django response Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from
Django response Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from

Time:02-13

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')

CodePudding user response:

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

  • Related