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

如何在Django应用中下载含动态内容的名片?

解决方案:Django实现动态名片生成并下载为图片

首先先修正你现有代码中的两处小错误:

  • 视图函数参数定义为mid,但代码中使用了vid,需统一为vid;
  • 模板文件名拼写错误visitng-card.html改为visiting-card.html
# 修正后的视图
def visitingCard(request, vid):
    user = get_object_or_404(CustomUser, id=vid)
    context = {
        'user': user,
    }
    return render(request, 'visiting-card.html', context)

接下来实现点击按钮生成并下载JPG名片的功能,我们使用WeasyPrint处理HTML转图片,配合Pillow转换为JPG格式:


1. 安装依赖

pip install weasyprint pillow

生产环境需额外安装系统依赖:

  • Ubuntu/Debian:sudo apt-get install libpango-1.0-0 libpangocairo-1.0-0 libcairo2 libgdk-pixbuf2.0-0 libffi-dev shared-mime-info
  • macOS:brew install pango cairo gdk-pixbuf

2. 创建纯名片模板

新建templates/visiting-card-template.html,只保留名片核心内容(避免继承base.html带来的多余页面元素):

{% load static %}
<div style="position: relative; width: 600px; height: 400px;">
    <img src="{% static 'dashboard/img/visiting-card-bg.jpg' %}" style="width: 100%; height: 100%; object-fit: cover;" />
    <div style="position: absolute; top: 90px; left: 85px;">
        <img src="{{ user.profile_pic.url }}" alt="{{ user.full_name }}" style="max-width:130px; border-radius: 50%;">
    </div>
    <div style="position: absolute; top: 100px; left: 230px; color: #fff; font-family: Arial, sans-serif;">
        <p>
            <strong>Name: {{ user.full_name }}</strong><br>
            <strong>Country: {{ user.country.name }}</strong><br>
            <strong>Email: {{ user.email }}</strong><br>
            <strong>Contact: {{ user.contact_number }}</strong><br>
        </p>
    </div>
</div>

3. 添加下载视图

在views.py中新增生成并返回图片的视图:

from django.http import HttpResponse
from weasyprint import HTML
from django.template.loader import render_to_string
from PIL import Image
import io

def download_visiting_card(request, vid):
    user = get_object_or_404(CustomUser, id=vid)
    
    # 渲染模板为HTML字符串
    html_string = render_to_string('visiting-card-template.html', {'user': user})
    
    # 生成PNG图片
    html = HTML(string=html_string, base_url=request.build_absolute_uri())
    png_bytes = html.write_png()
    
    # 转换为JPG格式
    img_io = io.BytesIO(png_bytes)
    img = Image.open(img_io)
    jpg_io = io.BytesIO()
    img.convert('RGB').save(jpg_io, format='JPEG', quality=95)
    jpg_io.seek(0)
    
    # 返回下载响应
    response = HttpResponse(jpg_io, content_type='image/jpeg')
    response['Content-Disposition'] = f'attachment; filename="{user.full_name}_visiting_card.jpg"'
    return response

4. 更新URL配置

在urls.py中添加下载路由:

urlpatterns = [
    path('visiting-card/<int:vid>', views.visitingCard, name='visiting-card'),
    path('visiting-card/download/<int:vid>', views.download_visiting_card, name='download-visiting-card'),
]

5. 修改页面下载按钮链接

更新原HTML中的下载按钮,指向新的下载路由:

<div class="pt-3">
    <a href="{% url 'download-visiting-card' vid=user.id %}" class="btn btn-success">Download Now</a>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:15:24