【问题标题】:'tuple' object has no attribute '_committed' error while updating image objects?更新图像对象时,“元组”对象没有属性“_committed”错误?
【发布时间】:2020-10-13 08:24:03
【问题描述】:

在这里,我尝试更新特定产品的每个产品图片。但它不能正常工作。这里只有第一个对象的图像在更新。

有一个模板,我们可以在其中一次更新产品和产品图片。 ProductImageProduct 模型具有 ManyToOne 关系,因此在模板中可以有单个产品的多个图像对象。

更新产品模型工作正常,但在更新 ProductImage 对象时它不起作用。

除了压缩之外,还有其他方法可以一次更新多个图像对象吗?

编辑:如果我解压缩图像列表,则更新无法正常工作。例如,如果我改变一个对象的图像,那么另一个对象的图像就会改变。 但是当我更改所有图像对象图像时,更新工作正常。当我只更改部分对象时,它无法正常工作。

当我压缩然后图像列表时,这就是错误回溯。

Traceback (most recent call last):
  File "venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "\venv\lib\site-packages\django\views\generic\base.py", line 73, in view
    return self.dispatch(request, *args, **kwargs)
  File "\venv\lib\site-packages\django\views\generic\base.py", line 101, in dispatch
    return handler(request, *args, **kwargs)
  File "dashboard\product\views\views.py", line 293, in post
    p.save()
  File "venv\lib\site-packages\django\db\models\base.py", line 751, in save
    force_update=force_update, update_fields=update_fields)
  File "venv\lib\site-packages\django\db\models\base.py", line 789, in save_base
    force_update, using, update_fields,
  File "venv\lib\site-packages\django\db\models\base.py", line 867, in _save_table
    for f in non_pks]
  File "lib\site-packages\django\db\models\base.py", line 867, in <listcomp>
    for f in non_pks]
  File "\venv\lib\site-packages\django\db\models\fields\files.py", line 303, in pre_save
    if file and not file._committed:
AttributeError: 'tuple' object has no attribute '_committed'

型号

class ProductImage(models.Model):
    image = models.ImageField(upload_to='imgs',blank=True, null=True)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)

模板

 <form method="post" enctype="multipart/form-data">
       {% csrf_token %}
       {{product_form}}
    <th>Current Image</th>
    <th>Change</th>
    {% for image in p_images %}
    <tr><td>{{image.pk}}</td>
    <td><img src="{{image.image.url}}" width="50" height="50"></td>
    <td><input type="file" name="image"></td>
    </tr>
    {% endfor %}
   <input type="submit">

观看次数

def post(self, request, *args, **kwargs):
    product = Product.objects.get(pk=kwargs['pk'])
    product_form = ProductForm(request.POST, instance=product)
    images = zip(request.FILES.getlist('image')) 
    p_images = ProductImage.objects.filter(product=product).order_by('pk')
    if product_form.is_valid():
        product_form.save()             
        
       # updating product images 
        for p, img in zip(p_images, images):  # error is here
           p.image = img
           p.save()

           # Tried this way too:

       for img in images:
           ProductImage.objects.filter(product=product).update(image=img)

【问题讨论】:

  • 能否添加一个完整的代码 sn-p 以帮助重现情况?截至目前,您的视图代码 sn-p 不是一个完整的
  • 除此之外,ProductImage只有一个single图像字段,怎么会有人将多个图像存储到那个single 字段?我是不是误会了什么?
  • @ArakkalAbu 抱歉标题不好。我打算在 pnce 更新多个产品图像对象?
  • 你熟悉 PDB(python 调试器,这里提到:docs.python.org/3/library/pdb.html)吗?如果没有,请尝试。这通常是一个很好的方法来浏览你的代码,看看为什么事情没有按预期工作。这也很简单,可能只是解释了为什么您的解决方案没有按预期工作。
  • @Ludo21South 问题出在 forloop 中。压缩图像列表和查询集

标签: python django django-views


【解决方案1】:

首先,更改input name 以便能够识别更新了哪个ProductImage

<!-- <td><input type="file" name="image"></td> -->
     <td><input type="file" name="image-{{image.pk}}"></td>

接下来,在request.FILES 中迭代input_name 并获得ProductImage PK。
然后,查找ProductImagep,更新image字段和save模型。

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

【讨论】:

    【解决方案2】:

    问题

    您不必要地压缩 request.FILES.getlist(“images”) 导致包含元组的数组,每个元组都包含一个图像对象。

    解决方案

    改变

    images = zip(request.FILES.getlist('image'))

    images = request.FILES.getlist('image')

    参考

    Django request.FILES.getlist 用法:https://docs.djangoproject.com/en/3.1/topics/http/file-uploads/#uploading-multiple-files

    【讨论】:

    • 我试过这种方式,上传不正常。例如,如果我改变一个对象的图像,那么另一个对象的图像就会改变。
    • 但是,如果我更改所有图像列表,则更新可以工作,但如果我不更改完整的图像列表,它将无法正常工作
    • @D_P 分配前检查图片是否为空即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    相关资源
    最近更新 更多