My problem is that in the templates and in the CMD I become a None return instead the images.
The views:
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.objcts.create(
product = product,
images = image
)
return redirect('index')
except Exception as e:
print(e)
The urls:
path('addimages/<int:pk>/', AddProductImages.as_view(), name="addimages"),
The templates:
<div >
<br />
<h1>ADD IMAGE</h1>
<br />
<hr />
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="images" id="" multiple>
<br>
<button type="submit" >Submit</button>
</form>
</div>
The results:
""" The result is so: what's the problem please?
ValueError: The view photo.views.AddProductImages didn't return an HttpResponse object. It returned None instead.
[31/Aug/2022 22:08:11] "POST /addimages/1/ HTTP/1.1" 500 65400
"""
So, could someone check this please? Thanks!
CodePudding user response:
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.
CodePudding user response:
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')