[Answered ]-Django ValueError: The view didn't return an HttpResponse object. It returned None instead

1👍

It is important to return a HttpResponse object. Here’s how to correct it –

  1. When you catch the exception, you still have to return an HTTPResponse object. In the absence of a return statement, it will error out with the message you are currently receiving.
  2. To resolve #1, I have added another redirect statement in the exception block. Please add a target that works in your case.
  3. There is a typo when you are creating an Image. It should be Images.objects.create. The typo is currently on the word object. Because it was erroring out, the flow was hitting the exception block and subsequently breaking your flow.
class AddProductImages(TemplateView):
    template_name = "addimages.html"

    def post(self, *args, **kwargs):
        try:
            images = self.request.FILES.getlist('images')
            product = Product.objects.get(id = self.kwargs['pk'])

            for image in images:
                product_images = Images.objects.create(
                        product = product,
                        images = image

                    )
            return redirect('index')
        except Exception as e:
            return redirect('some_other_target')

0👍

It likely excepted since thats the only place you aren’t returning anything.

I can also see why it’s excepting.

product_images = Images.objcts.create(
                        product = product,
                        images = image

                    )

should be:

product_images = Images.objects.create(
                        product = product,
                        images = image

                    )

Hey, at least now you found out why a blanket except statement like this, is not good. Try to be more specific with exceptions. You could even do:

try:
    code...
except ValueError as e:
    print(e)
except Product.DoesNotExist as e:
    print(e)

This way you can tailor your code to the exceptions raised, and a simple SyntaxError won’t catch you off-guard like this.

Leave a comment