Django的render_to_string方法中的context_processors [英] Django custom context_processors in render_to_string method

查看:110
本文介绍了Django的render_to_string方法中的context_processors的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个发送电子邮件的功能,我需要在电子邮件的HTML模板中使用context_processor变量,但这不起作用。

I'm building a function to send email and I need to use a context_processor variable inside the HTML template of the email, but this don't work.

示例:

def send_email(plain_body_template_name, html_body_template_name):
    plain_body = loader.render_to_string(plain_body_template_name, context)
    html_body = loader.render_to_string(html_body_template_name, context)
    email_msg = EmailMultiAlternatives(body=plain_body)
    email_msg.attach_alternative(html_body, 'text/html')
    email_message.send()

在我的自定义 context_processor.py 中,我只有一个函数,该函数接收 HttpRequest 并返回 {'foo':'bar'} 之类的字典,然后在我尝试使用 {{foo}} 渲染模板。

In my custom context_processor.py I just have a function that receive a HttpRequest and return a dict like {'foo': 'bar'}, and in the template I try to render using {{foo}}.

我在<$ c $中添加了context_processor c> TEMPLATE ['OPTIONS'] ['context_processors'] 也是如此。

推荐答案

假设您在 TEMPLATE 中将 django 后端与

'BACKEND':'django.template.backends.django.DjangoTemplates',

django看到您尚未传递请求,而是选择了基本的 Context 来包装字典,而不是 RequestContext 将处理您定义的 context_processors

django is seeing that you haven't passed in a request and opting for a basic Context to wrap your dict instead of a RequestContext which will handle the context_processors you've defined.

您可能会逃脱

html_body = loader.render_to_string(html_body_template_name ,上下文,request = request)

,但您需要传递请求对象。

but you'd need to pass in the request object.

这可能没有道理。您是通过电子邮件发送请求的人吗?包括上下文是否有意义?

This might not make sense though. Are you emailing the person making the request? Does the context make sense to include?

如果上下文处理器不需要 request ,那么我要么将其设为一个简单的实用函数( (如果仅在此处调用)或将request参数设为可选,将其导入到此模块中,然后将其直接添加到上下文中

If your context processor doesn't need the request then I'd either make it a simple utility function (if it's only called here) or make the request parameter optional, import it into this module, and add it directly into the context

context = { my_var:1}
context.update(your_extra_context())
loader.render_to_string(...)

有一些复杂的方法可以分层更新 Context(),但我认为这不是必需的。

There are some complicated ways of updating a Context() in layers, but I don't think that's necessary here.

这篇关于Django的render_to_string方法中的context_processors的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆