Django custom context_processors in render_to_string method
<p>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.</p>

<p>Example:</p>

<pre><code>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()
</code></pre>

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

<p>I added the context_processor in the <code>TEMPLATE['OPTIONS']['context_processors']</code> too.</p>

<p>Assuming you're using the <code>django</code> backend in your <code>TEMPLATE</code> with</p>

<p><code>'BACKEND': 'django.template.backends.django.DjangoTemplates',
</code></p>

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

<p>You can probably get away with doing</p>

<p><code>html_body = loader.render_to_string(html_body_template_name, context, request=request)
</code></p>

<p>but you'd need to pass in the request object.</p>

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

<p>If your context processor doesn't need the <code>request</code> 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</p>

<p><code>context = {"my_var": 1}
context.update(your_extra_context())
loader.render_to_string(...)
</code></p>

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

python django