AttributeError:“元组”对象没有属性“ _committed”

时间:2019-12-15 02:11:45

标签: python django

完整追溯:

Traceback (most recent call last):
  File "crawl_ebaumsworld.py", line 92, in <module>
    crawl(first_url)
  File "crawl_ebaumsworld.py", line 66, in crawl
    creator=mike
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 422, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/michael/projects/deepsteg/engine/models.py", line 62, in save
    return super(AttackImage, self).save(*args, **kwargs)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 779, in save_base
    force_update, using, update_fields,
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 870, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert
    using=using, raw=raw)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1334, in execute_sql
    for sql, params in self.as_sql():
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1278, in as_sql
    for obj in self.query.objs
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1278, in <listcomp>
    for obj in self.query.objs
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1277, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1228, in pre_save_val
    return field.pre_save(obj, add=True)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/fields/files.py", line 286, in pre_save
    if file and not file._committed:
AttributeError: 'tuple' object has no attribute '_committed'

models.py

class AttackImage(models.Model):
    title = models.CharField(max_length=255)
    image = models.ImageField(upload_to='attack_images', blank=True, null=True)
    source_url = models.URLField(blank=True,null=True)
    domain = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True)
    creator = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True)
    slug = models.SlugField(blank=True,null=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)[:50]

        if self.source_url and not self.image:
            result = urllib.request.urlretrieve(self.source_url)
            self.image = os.path.basename(self.source_url), File(open(result[0], 'rb'))

        if self.source_url:
            if '//' in self.source_url:
                d = self.source_url.split('//')[1].split('/')[0]
            else:
                d = self.source_url.split('/')[0]

            try:
                domain = Domain.objects.get(domain_url=d)
            except Exception as e:
                print(e)
                domain_object = Domain.objects.create(domain_url=d)
                domain = domain_object
            self.domain = domain

        return super(AttackImage, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse("attack_image_detail", kwargs={
            'pk': str(self.id),
            'slug': str(self.slug)})

我相信这是由于行self.image = os.path.basename(self.source_url), File(open(result[0], 'rb'))

有人可以帮忙吗?提前致谢。堆栈是python / django。我的基本问题是,如果我是对的,并且上面的行是引起问题的原因,那么如何正确地将图像分配给ImageField(不保存图像)?

1 个答案:

答案 0 :(得分:1)

使用substring_of = [given_string[i:j] for i, j in combinations(range(len(given_string) + 1), r=2) if given_string[i:j] != ""] ImageField时,您实际上是在FieldFile的实例上进行操作

在这种情况下,错误是为FileField指定了错误的类型-它期望使用FieldFile或至少为File类型。


简要回答在代码中可以代替ImageField使用的内容:

self.image = ....

检查this StackOverflow answer保存文件。我添加了一个小的更改- from django.core.files import File ... with open(result[0], "rb") as downloaded_file: self.image.save(os.path.basename(self.source_url), File(downloaded_file), save=False) ... -在保存图像时-在这一步中,我们仅保存下载的文件=从临时路径复制文件,并由urllib将其下载到{ {1}},但不保存模型实例

save=False-读取文件并将其保存在MEDIA路径下的self.image.save(name, file)中,名称为MEDIA,并且模型实例被保存(默认保存为True)。

upload_to-相同,但是更改文件后不会保存模型实例,这可能是您稍后保存模型实例name时所希望的。


代码中正在执行什么步骤:

  • 使用urllib下载文件(到临时路径)
  • 保存/复制到正确的媒体/ upload_to路径并将ImageField设置为其值
  • 设置其他模型实例字段
  • 保存模型