'tuple' object has no attribute '_committed' error while updating image objects?
First, change input
name
to be able to identify which ProductImage
was updated.
<!-- <td><input type="file" name="image"></td> -->
<td><input type="file" name="image-{{image.pk}}"></td>
Next, iterate the input_name
in request.FILES
and get the ProductImage
PK.
Then, lookup the ProductImage
p
, update the image
field and save
the model.
def post(self, request, *args, **kwargs):
product = Product.objects.get(pk=kwargs['pk'])
product_form = ProductForm(request.POST, instance=product)
if product_form.is_valid():
product_form.save()
# Updating product images
if request.FILES:
p_images = ProductImage.objects.filter(product=product).order_by('pk')
p_images_lookup = {p_image.pk: p_image for p_image in p_images}
for input_name in request.FILES:
p = p_images_lookup[int(input_name[len('image-'):])]
p.image = request.FILES[input_name]
p.save()
Problem
You’re unnecessarily zipping request.FILES.getlist(“images”)
leading to an array containing tuples, each containing an image object.
Solution
Change
images = zip(request.FILES.getlist('image'))
To
images = request.FILES.getlist('image')
Reference
Django request.FILES.getlist usage: https://docs.djangoproject.com/en/3.1/topics/http/file-uploads/#uploading-multiple-files