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

Django邮件模板引用失败求助:如何正确指向模板发送通知邮件

解决Django邮件模板找不到的问题

看起来你的核心问题是Django无法定位到邮件模板的父模板,同时还有几个小细节需要调整,我一步步帮你梳理:

1. 修正模板继承路径

报错提示找不到authors/apps/authentication/templates/emailing_template.html,这是因为你在模板里写了绝对路径,但Django的模板查找机制是基于已注册App的templates目录的。

把你的notifications.html里的继承语句修改为:

{% extends 'authentication/emailing_template.html' %}

这样Django会自动去authentication App的templates目录下查找父模板,无需写全路径。

2. 确保相关App已注册到INSTALLED_APPS

Django只会扫描已注册App的templates目录,所以你需要在项目的settings.py里把authentication和notifications这两个App加进去:

INSTALLED_APPS = [
    # 保留其他默认App
    'authors.apps.authentication',
    'authors.apps.notifications',
]

3. 确认TEMPLATES配置正确

检查settings.py里的模板配置,确保APP_DIRS设为True,这是让Django自动扫描App内templates目录的关键:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],  # 如果你有项目级别的模板目录可以添加在这里
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

4. 修复信号函数里的冗余查询

你的信号函数里有个逻辑错误:recipients = User.objects.filter(email=user),这里的user已经是instance.recipient(一个User实例),不需要再去数据库查询,直接使用即可,优化后代码如下:

def email_notification(sender, instance, created, **kwargs):
    """ sends an email notification for notifications """
    user = instance.recipient
    deactivation_link = "link.com"
    # 直接判断当前用户的邮件通知开关状态
    if created and user.email_notification:
        mail_helper.send_mail(
            subject="Author's Haven notifications",  # 修正拼写错误:notifictions → notifications
            to_addrs=[user.email],
            multiple_alternatives=True,
            template_name='notifications.html',
            template_values={
                'username': user.username,
                'optout_link': deactivation_link,
                'description': instance.description
            }
        )
post_save.connect(email_notification, sender=Notification)

5. 模板变量匹配修正

你的邮件模板里用了{{ activation_link }},但信号函数里传递的变量名是optout_link,所以需要把模板里的对应代码改成:

<p>If the button doesn't work, copy the link below and paste it in your browser: {{ optout_link }}</p>

做完以上调整后,Django应该就能正确找到模板并发送邮件了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:03:40