回到顶部

CONTENTS

django 获取富文本编辑器中的图片地址(缩略图、封面)

# 环境

  1. python: 3.6.8

  2. django==1.11.22

# models.py

from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth import get_user_model

from DjangoUeditor.models import UEditorField
from pyquery import PyQuery as pq  # pip install pyquery,获取到 html 中的 img 图片地址返回
from uuslug import slugify

User = get_user_model()


class Article(models.Model):
    """
    主题表/文章表
    """
    title = models.CharField(max_length=128, unique=True, verbose_name="标题")
    slug = models.SlugField(max_length=128, unique=True, verbose_name="url标识符")
    content = UEditorField(verbose_name="内容", imagePath="blog/images/", width=1000, height=300, toolbars="full", filePath="blog/files/", default='')
    node = models.ForeignKey(Node, verbose_name="所属节点")
    user = models.ForeignKey(User, related_name="user_article", verbose_name="作者")
    source = models.ForeignKey(Source, verbose_name="来源", blank=True, null=True)
    tags = models.ManyToManyField(Tag, verbose_name="标签", related_name="tags_article", blank=True)
    num_views = models.IntegerField(default=0, verbose_name="浏览数量")
    num_favorites = models.IntegerField(default=0, verbose_name="收藏数量")
    last_answerer = models.ForeignKey(User, related_name="last_answerer_article", verbose_name="最后回复者", blank=True,
                                      null=True)
    show_status = models.BooleanField(default=True, verbose_name="显示状态")
    time_create = models.DateTimeField(auto_now_add=True, verbose_name="发表时间")
    time_update = models.DateTimeField(blank=True, null=True, auto_now=True, verbose_name="更新时间")

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Article, self).save(*args, **kwargs)

    # 获取后台文本编辑器图文内容中图片 url 地址
    def get_content_img_url(self):
        temp = Article.objects.filter(pk=str(self.id)).values('content')  # values 获取 Article 数据表中的 content 字段内容
        html = pq(temp[0]['content'])  # pq 方法获取编辑器 html 内容
        # print(html, "\n", "----")
        img_path = pq(html)('img').attr('src')  # 截取 html 内容中的路径
        # print("pic", img_path)
        return img_path  # 返回第一张图片路径

    class Meta:
        verbose_name = "文章"
        verbose_name_plural = "文章列表"

    def __str__(self):
        title_short = self.title if len(self.title) < 15 else self.title[:12] + '...'
        return "%s %s %s" % (self.id, self.user, title_short)

# views.py 返回 articles

from django.views import generic
from django.core.cache import cache
from ipware.ip import get_ip


class IndexView(generic.ListView):
    template_name = 'lw-index-noslider.html'  # 加载该 html 文件
    context_object_name = "articles"  # 是数据库搜索出来的结果存放的变量名字,用于模板循环显示
    paginate_by = paginate_by  # 设置分页中每一页的记录数目
    model = Article  # 定义从哪份 model 中查询
    ip = None

    def get_queryset(self):
        articles = cache.get("articles")
        if not articles:
            articles = Article.objects.filter(show_status=True).order_by('-time_created')
            cache.set("articles", articles, CACHE_TIMEOUT_ARTICLE)
        return articles

# 模板引用图片地址:(article.get_content_img_url)

{% for article in articles %}
    <img src="{{ article.get_contentimg_url }}-400x250q75"                                          
{% endfor %}

 

^_^
请喝咖啡 ×

前一篇: django 修改 app 在 admin 后台显示的名称(verbose_name)
下一篇: 常用的互联网内容检索网站