开发者社区> 问答> 正文

Django -在文章的HTML中创建相关的图像

我有一个以html为文本的文章模型和一个带有字段Article = ForeignKey(Article)的图像模型。如果有图像添加到文章的html中,应该提取并作为对象添加到图像模型中。我编写了函数create_images_from_tags来使用Beautifulsoup搜索img标记并保存它们。 不幸的是,这不起作用,我得到这个错误:

ValueError: save() prohibited to prevent data loss due to unsaved related object 'Article'.

这是我的文章模型的保存功能:

def save(self, *args, **kwargs):
    self.html = self.create_images_from_tags(self.html)

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

将这个函数放在super.save()之后将会导致一个无限循环,因为我必须在它之后再次保存模型。 编辑 我create_images_from_tags功能:

def create_images_from_tags(self, html: str) -> str:
    """
        Creates Image objects from the HTML. Searches using Beautifulsoup for img (HTML element).
        First checks if the image already exists (using 'data-image-id' attribute on the img-tag)
            If not, an Image object will be created and the id will be saved on the tag using the `data-image-id`
            attribute.
            The img-tag 'loading' attribute will be changed to 'lazy'.

            The following attributes of the img-tags will be extracted and saved on the Image object:
                alt -> description
                data-name -> name
                src -> path (will be created to an absolute path using the BASE_DIR from the settings)
            The following static values will be saved on the Image object:
                Article -> self (the current article)
                reduced_information -> True
                from_article -> True

    :param html: Old HTML of the article
    :return: New HTML
    """
    soup = BeautifulSoup(html, "html.parser")

    for element in soup.find_all("img"):
        image_id = element.get("data-image-id", None)

        try:
            Image.objects.get(id=image_id)
        except ObjectDoesNotExist:
            src = element["src"]
            description = element.get("alt", " ")
            name = str(element.get(
                "data-name",
                escape(f"Ein Bild vom Artikel \"{self.short_title}\"")
            ))
            # If src is relative, make full path
            if src.startswith("/"):
                path = os.path.join(settings.BASE_DIR, src[1:]).replace("\\", "/")
            else:
                path = src

            image = Image.objects.create(
                description=description,
                name=name,

                _original=path,
                Article=self,

                reduced_information=True,
                from_article=True,
            )

            element["data-image-id"] = image.id
            element["loading"] = "lazy"
    return str(soup)

问题来源StackOverflow 地址:/questions/59467031/django-create-images-related-on-articles-html

展开
收起
kun坤 2019-12-25 09:34:04 473 0
0 条回答
写回答
取消 提交回答
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
《零基础HTML入门教程》 立即下载
天猫 HTML5 互动技术实践 立即下载
天猫HTML5互动技术实践 立即下载