【问题标题】:Path to image in Django Template for emails not work电子邮件的 Django 模板中的图像路径不起作用
【发布时间】:2019-12-11 00:40:35
【问题描述】:

我想将图像添加到电子邮件的 html 模板中。在我的项目设置中,我有

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

和

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
...
                'django.template.context_processors.media',
            ],
        },
    },
]

在我的网址里有

urlpatterns = [


] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

我的项目结构

我的电子邮件方法

message = render_to_string('recovery_password.html', {
            "code": code,
            "MEDIA_URL": settings.MEDIA_URL
        })
        mail_subject = 'Recovery password'

        email = EmailMessage(mail_subject,
                             message,
                             to=[to_email],
                             )
        email.content_subtype = "html"
        email.send()

在 recovery_password.html 中我有图片上的链接

<a><img src="{{MEDIA_URL}}image1.png/></a>

但我在电子邮件中的图像不起作用。它不显示在模板中

UPD:我的所有项目结构

【问题讨论】:

  • 当你像这样模糊你的目录结构时,有点难以分辨。我只能看到您已将目录配置为“模板”并将其命名为“媒体”。但那里也有一个子目录。约定将您的模板存储为 /
  • @urbanespaceman 感谢您的评论。我有一个带有模板的单独文件夹和带有图像的单独文件夹。请查看我的 UPD 问题

标签: html django templates


【解决方案1】:

使用图片的完整路径,包括您的域名。像这样的:

<img src="http://example.com{{MEDIA_URL}}image1.png">

或者您可以在设置中配置域而不是对其进行硬编码,然后将域变量传递给render_to_string 上下文:

# settings.py
DOMAIN = 'http://www.example.com'

################

message = render_to_string('recovery_password.html', {
        "code": code,
        "MEDIA_URL": settings.MEDIA_URL,
        "DOMAIN": settings.DOMAIN,
    })

然后在你的模板中:

<img src="{{DOMAIN}}{{MEDIA_URL}}image1.png">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-06
    • 2021-06-22
    • 1970-01-01
    • 2013-01-10
    • 2011-01-04
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多