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

如何在Django中动态保存图片并传递至HTML模板?

在Django中动态生成并传递图片到HTML模板

1. 先配置Django媒体文件环境

动态生成的文件应该存放在媒体目录而非静态目录,先在settings.py中添加以下配置:

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

# 媒体文件根目录
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# 媒体文件访问URL
MEDIA_URL = '/media/'

接着在项目根路由urls.py中添加媒体文件的访问路由(仅开发环境适用,生产环境需用Nginx等服务器配置):

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # 你的其他路由配置
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

2. 修改视图函数,正确保存并传递图片URL

为避免每次生成的图片被覆盖,建议生成唯一文件名;同时要确保图片保存到媒体目录下,再构造可访问的URL传递给模板:

import os
import uuid
from django.conf import settings
import cv2

def img_upscaler(request):
    # some code 
    upscaled = sr.upsample(image)
    
    # 生成唯一文件名,防止覆盖
    img_filename = f"upscaled_{uuid.uuid4().hex}.png"
    # 拼接媒体目录下的保存路径,可按需创建子目录分类存储
    save_dir = os.path.join(settings.MEDIA_ROOT, 'upscaled_images')
    os.makedirs(save_dir, exist_ok=True)  # 确保目录存在
    img_path = os.path.join(save_dir, img_filename)
    
    # 注意:cv2默认以BGR格式保存,若图片颜色异常,需转成RGB格式再保存
    # upscaled_rgb = cv2.cvtColor(upscaled, cv2.COLOR_BGR2RGB)
    # cv2.imwrite(img_path, upscaled_rgb)
    cv2.imwrite(img_path, upscaled)
    
    # 构造模板可访问的图片URL
    img_url = os.path.join(settings.MEDIA_URL, 'upscaled_images', img_filename)
    
    return render(request, "upsc_main.html", {'form': form, 'upscaled_img': img_url})

3. 在HTML模板中调用图片

在upsc_main.html中通过传递的URL渲染图片:

{% if upscaled_img %}
    <img src="{{ upscaled_img }}" alt="Upscaled Result">
{% endif %}

额外提示

  • 生产环境不要依赖static路由处理媒体文件,需配置Nginx/Apache等Web服务器直接映射媒体目录。
  • 若不需要长期保留生成的图片,可添加定时清理脚本,定期删除媒体目录下的旧文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:15:01