1

使用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 呈现?

4

1 回答 1

1

上下文处理器将对象作为输入HttpRequest,因此要在调用模板方法时运行上下文处理器,render需要将请求传递给它template.render(context, request)。您的welcome_email功能不接受请求,自然无法通过它。

如果从某个视图调用此函数,您只需将请求作为参数并将其传递给模板render方法:

def welcome_email(user, request):
    ...
    subject_content = subject_text.render(context, request)
    body_text_content = body_text.render(context, request)
    body_html_content = body_html.render(context, request)
    ...

如果它是由一些没有请求对象的自动化进程调用的,那么由于您的处理器甚至不需要请求,并且您使用的值是恒定的,只需自己从函数中传递它们即可。

于 2021-09-30T17:16:16.500 回答