我有一个写博客的模式。因为我正在为 Blog
使用所见即所得的编辑器的 descritpion
,通过它我可以在 description
中插入图像.
class Blog(models.Model):
title = models.CharField(max_length=150, blank=True)
description = models.TextField()
pubdate = models.DateTimeField(default=timezone.now)
publish = models.BooleanField(default=False)
在管理员中它看起来像这样:
我想要的是在博客描述中获取第一张图片,并将其呈现在模板中,如下所示:
如何获得 img
src
从博客的描述在模板中使用它?非常感谢您的帮助和指导。谢谢。
views.py:
def blog(request):
blogs = Blog.objects.all()
return render(request, 'blogs.html', {
'blogs':blogs
})
模板:
{% for blog in blogs %}
<div class="blog">
<p class="blog_date"> {{blog.pubdate}} </p>
<h2 class="blog_title"> {{blog.title}} </h2>
<img src="{{STATIC_URL}} ###img src to be included" class="blog_image img-responsive img-thumbnail">
<a href="blog_detail.html" class="blog_read_more btn btn-info">Read more</a>
<div class="container">
<p class="divider">***</p>
</div>
</div>
{% endfor %}
最佳答案
这里有一个基本方法,您可以为方便起见进行调整:
将 first_image 字段添加到您的模型:
class Blog(models.Model):
title = models.CharField(max_length=150, blank=True)
description = models.TextField()
pubdate = models.DateTimeField(default=timezone.now)
publish = models.BooleanField(default=False)
first_image = models.CharField(max_length=400, blank=True)
现在您所要做的就是在保存时填充您的 first_image 字段,因此您的模型的保存方法应该如下所示:
def save(self, *args, **kwargs):
# This regex will grab your first img url
# Note that you have to use double quotes for the src attribute
img = re.search('src="([^"]+)"'[4:], self.description)
self.first_image = img.group().strip('"')
super(Blog, self).save(*args, **kwargs)
现在只需在您的模板中引用它。
这不是一个成熟的解决方案,您还应该考虑其他事项,例如区分笑脸或缩略图或代码片段 imr src 和实际的 img src,但这应该供个人使用,您不希望将其他人的选择限制为将他们的第一张图片作为封面图片。
希望这对您有所帮助!
关于django - 从 Django 的帖子中获取第一张图片 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30844322/