python - 尝试将图像保存到 django 模型时出错
问题描述
我使用美丽的汤从下面描述的网站成功刮取和提取图像,但是当我查看提取的图像时,它们显示为 Url,如下所示。然后,我在尝试将抓取的图像保存到我的 django 数据库时遇到困难,因为下面显示的特定错误不断出现。收到错误后,我还尝试使用 forloop 创建帖子,因为我想尝试将列表元素保存在单个数据中,但它仍然显示相同,或者我没有提交相同的错误,但是当我删除图像抓取时标题,摘要,内容中的文件中的数据并尝试保存到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'
解决方案
请使用此更改您的 for 循环代码段
for image in images:
Post.objects.create(
title=title,
content_1=paragraphs,
image=image,
sources=lnk,
)
推荐阅读
- javascript - 有没有办法查看与数组中给定字符串最密切相关的内容?
- scrapy - 是否可以使用 intersphinx 链接到 scrapy 文档?
- laravel - 如何在比较之前更改 laravel 数据库值?
- javascript - 离子选择更新模型选择的值
- python-3.x - driver.findelement 值每次都在变化
- php - 如果新行不存在,如何插入新行,如果存在则删除?
- docker - 如何使用标签名称作为正则表达式提取 docker hub 图像
- node.js - 更改 mongodb 嵌入文档的根目录
- java - 更改所有孩子的父母
- ruby-on-rails - 无法在 collection_select Rails 6 中进行 Stimulus JS 数据操作