You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中生成图片宽高并填充至OG标签对应属性?

解决方案

方法一:模型中存储宽高字段(推荐)

这种方法在图片上传时就计算好宽高并保存到数据库,避免每次请求都读取图片文件,性能更优。

  1. 修改模型文件 article/models.py
    先确保已安装Pillow(执行 pip install pillow),然后更新模型:
from django.db import models
from PIL import Image

class Article(models.Model):  # 类名首字母大写,符合Python编码规范
    image1 = models.ImageField(upload_to='images', blank=True)
    image1_width = models.PositiveIntegerField(blank=True, null=True)
    image1_height = models.PositiveIntegerField(blank=True, null=True)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        # 仅当图片存在且宽高未设置时计算尺寸
        if self.image1 and not self.image1_width:
            with Image.open(self.image1.path) as img:
                self.image1_width, self.image1_height = img.size
                # 再次保存宽高字段
                super().save(*args, **kwargs)

修改模型后需执行迁移命令:

python manage.py makemigrations
python manage.py migrate
  1. 更新模板 head.html
    模板中先判断图片是否存在,再填充对应OG标签:
{% if article.image1 %}
<meta property="og:image" content="{{ article.image1.url }}" />
<meta property="og:image:secure_url" content="{{ article.image1.url }}" />
<meta property="og:image:width" content="{{ article.image1_width }}" />
<meta property="og:image:height" content="{{ article.image1_height }}" />
{% endif %}

这里用article.image1.url代替直接输出article.image1,能获取完整的图片访问地址,避免路径错误。

方法二:模板直接访问图片属性(简易版)

如果不想修改模型结构,可直接在模板中访问ImageField的width和height属性,前提是已安装Pillow:

{% if article.image1 %}
<meta property="og:image" content="{{ article.image1.url }}" />
<meta property="og:image:secure_url" content="{{ article.image1.url }}" />
<meta property="og:image:width" content="{{ article.image1.width }}" />
<meta property="og:image:height" content="{{ article.image1.height }}" />
{% endif %}

这种方法每次渲染模板都会读取图片文件获取尺寸,适合小流量站点,大流量场景更推荐方法一。

注意事项

  • 必须安装Pillow库,否则无法读取图片尺寸
  • 务必在模板中判断图片是否存在,避免空值或报错
  • 模型类名建议遵循Python规范首字母大写(Article而非article)

内容的提问来源于stack exchange,提问作者Hiren Hiden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 23:39:07