1👍
It is important to return a HttpResponse object. Here’s how to correct it –
- 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.
- To resolve #1, I have added another redirect statement in the exception block. Please add a target that works in your case.
- There is a typo when you are creating an
Image
. It should beImages.objects.create
. The typo is currently on the wordobject
. 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.
- [Answered ]-Django-registration module dont send email
- [Answered ]-ImportError: cannot import name 'urlpatterns' from 'django'
- [Answered ]-Django Rest Framework – main url HTTP/1.1" 404 Not Found
- [Answered ]-How do I debug a production server not finding settings and logging files not working?
- [Answered ]-Python sleep if a function runs for 20 times
Source:stackexchange.com