【问题标题】:Error Trying to save Image to django model尝试将图像保存到 django 模型时出错
【发布时间】:2021-05-14 07:56:04
【问题描述】:

我使用美丽的汤并成功地从下面描述的网站中提取图像,但是当我查看提取的图像时,它们显示为 Url,如下所示。然后,我在尝试将抓取的图像保存到我的 django 数据库时遇到困难,因为下面显示的特定错误不断出现。收到错误后,我还尝试使用 forloop 创建帖子,因为我想尝试将列表元素保存在单个数据中,但它仍然显示相同,或者我得到相同的错误未提交但是当我从标题、摘要、内容中的文件中删除图像 scrape 数据并尝试保存到 django 数据库时,它是成功的。 保存图像是个问题,我需要帮助

下面是我的示例代码

我的抓取图像显示为如下所示的 url 列表

https://people.net/wp-content/uploads/2021/03/ad1-746x375.jpg https://people.net/wp-content/uploads/2020/08/caroon-1-600x375.jpg

这样的东西带来了图像

images = [i['data-src'] for i in soup.find_all('img', {'class','attachment-jnews-750x375 size-jnews-750x375 lazyload wp-post-image'})] 

但我无法像这样保存上面抓取的图像,因为它会带来错误

Post.objects.create(
                title=title,
                content_1=paragraphs,
                image=images,
                sources=lnk,
            )

当我尝试保存到模型时这会带来错误

class Post(models.Model):
               title = models.CharField(max_length=250, blank = True, help_text='Maximum 160 Title characters.')
               image = models.FileField(upload_to='images', blank=True, null=True,  help_text='You must upload original image before continuing.')
if file and not file._committed: AttributeError: 'list' object has no attribute '_committed'

我尝试使用 for 循环,但同样的错误也存在

for image in images: 
             / Post.objects.create(title=title,
                content_1=paragraphs,
                image=images,
                sources=lnk,
)

我也遇到了这个错误

if file and not file._committed: AttributeError: 'list' object has no attribute '_committed'

【问题讨论】:

  • 好像你传递的是图片列表,而不是一张图片。
  • @SergeyPugach 请告诉我一条出路 - 我需要你的帮助,是的,我正在传递一个图像列表,这就是我在代码中使用 forloop 的原因
  • 在 for 循环中,在创建 Post 对象时,您将 images 传递到必须传递 image 的位置,因为 images 是您正在遍历的列表,而 image 是其中的列表对象当前循环状态。此外,您的代码在 for 循环中有缩进问题
  • Dea @Akash 请给我一个很好的例子,先生,我仍然感到困惑,因为图像是列表对象,图像是列表,我使用对象来横向列表 - 你能帮我一个再远一点
  • 仅供参考,它是 scrape 不是废品

标签: python django django-models beautifulsoup django-file-upload


【解决方案1】:

请用这个改变你的for循环代码sn-p

for image in images:
    Post.objects.create(
        title=title,
        content_1=paragraphs,
        image=image,
        sources=lnk,
    )

【讨论】:

  • 非常感谢@Akash,我真的很感激
  • 我希望它解决了您的问题,如果解决了,请点赞。
  • 亲爱的@Akash 好的,我正在运行代码,编写一个方法——先生,我该如何支持它
  • 即使您已成功保存帖子,此图像也未显示此图像根本没有出现在我的帖子中,但仅存在图像 sigb 是因为它未上传还是已上传正在抓取一个链接
  • 图片在哪里没有出现?在模板中?您可以在管理面板中检查以确认图像正在保存吗?
猜你喜欢
  • 2021-10-13
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
  • 1970-01-01
  • 2022-01-08
相关资源
最近更新 更多