【问题标题】:Get the first image src from a post in django从 django 的帖子中获取第一个图像 src
【发布时间】:2015-06-15 11:43:15
【问题描述】:

我有一个写博客的模型。我正在为Blogdescritpion 使用所见即所得的编辑器,通过它我可以在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 %}

【问题讨论】:

  • 你的所见即所得编辑器叫什么名字?

标签: django django-templates django-views


【解决方案1】:

这是一种基本方法,您可以根据自己的方便进行调整:

在模型中添加 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)

现在只需在您的模板中引用它。

这不是一个完全成熟的解决方案,您还应该考虑其他一些事情,例如区分笑脸或缩略图或代码 sn-p imr src 和实际 img src,但这应该供个人使用,您不希望将其他人的选择限制为将他们的第一张图片作为封面图片。

希望这会有所帮助!

【讨论】:

  • 如果你的意思是调用 .update() 方法,那么不,它不会更新字段,因为 .update() 不会调用 save 方法。查看文档以解决此问题docs.djangoproject.com/en/dev/ref/models/querysets/#update
  • 这将在您每次调用 .save() 方法时使用 first_image 更新博客,对于 .update() 看上面。
  • 我试过这样做,但它没有显示图像链接。 first_image 为空白。
  • 它现在应该可以工作了,只需将 URLField 更改为 CharField 以通过 url 验证约束,因为在这种情况下您没有获取完整的 url。
  • 我也这样做了...我想,它没有保存 first_image。
【解决方案2】:

个人而言,我会在收到新博客的帖子时解析 HTML 以获取图像源,并将其存储到数据库(带有特定字段),这样您以后就不需要这样做了。

我猜描述是 HTML 格式的,在这种情况下,您可以从 HTMLParser 派生一个类,并实现 handle_starttag 方法,以便存储您获得的第一张图像的来源(否则为默认图像)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 2013-07-27
    相关资源
    最近更新 更多