首页 > 解决方案 > 尝试将图像保存到 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'

标签: pythondjangodjango-modelsbeautifulsoupdjango-file-upload

解决方案


请使用此更改您的 for 循环代码段

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

推荐阅读