使用Django 3.2
定义了一些全局变量,例如
应用程序/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
在电子邮件模板页脚中使用过
帐户/电子邮件.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()
模板/帐户/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 呈现?