【问题标题】:Django context processor not rendering from shellDjango 上下文处理器不从 shell 渲染
【发布时间】: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 中渲染上下文处理器?

【问题讨论】:

标签: python django django-3.2 django-shell


【解决方案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)
    ...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 2014-11-03
    • 2017-10-24
    • 2019-01-14
    • 2019-01-05
    • 2015-06-01
    • 2011-01-15
    相关资源
    最近更新 更多