我有一个以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
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。