【发布时间】:2021-11-22 12:03:30
【问题描述】:
使用 Django 3.2
定义了一些全局变量,例如
app/context_processors.py
from app.settings import constants
def global_settings(request):
return {
'APP_NAME': constants.APP_NAME,
'APP_VERSION': constants.APP_VERSION,
'STATIC_URL_HOST': constants.STATIC_URL_HOST
}
在settings.py 文件中
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
...
'app.context_processors.global_settings',
],
},
},
]
曾在邮件模板页脚中使用APP_NAME 喜欢
account/emails.py
def welcome_email(user):
subject_file = 'account/email/welcome_subject.txt'
body_text_file = 'account/email/welcome_message.txt'
body_html_file = 'account/email/welcome_message.html'
subject_text = get_template(subject_file)
body_text = get_template(body_text_file)
body_html = get_template(body_html_file)
context = {
'username': user.username,
}
subject_content = subject_text.render(context)
body_text_content = body_text.render(context)
body_html_content = body_html.render(context)
to = [user.email]
msg = EmailMultiAlternatives(
subject=subject_content,
body=body_text_content,
from_email='{} <{}>'.format('Admin', 'admin@example.com'),
to=to,
)
msg.attach_alternative(body_html_content, 'text/html')
msg.send()
templates/account/welcome_message.html
Hi {{ username }},
Welcome to the application.
{{ APP_NAME }}
当电子邮件从门户网站发送时,APP_NAME 呈现正常,但是当电子邮件发送是从 Django shell 启动时
python manage.py shell
> from account.emails import welcome_email
> welcome_email(user)
那么APP_NAME 不会在邮件中呈现。
如何从 shell 中渲染上下文处理器?
【问题讨论】:
-
welcome_email函数是什么?...请参阅How to Ask以及如何编写minimal reproducible example。 -
@AbdulAzizBarkat 使用
welcome_email函数更新问题
标签: python django django-3.2 django-shell