Archive

Posts Tagged ‘render to string’

[django] create a formatted string with the Django template system

August 4, 2014 Leave a comment

Problem
In an application I wanted to send formatted HTML emails. For producing the body of the email, I wanted to use the Django template system. The task is very similar to creating a view. The difference is that I don’t want to send back the HTML to the client in the browser but I want to store it in a string.

Solution
The solution is very simple:

from django.template.loader import render_to_string

def email():
    context = {'some_key': 'some_value'}
    html = render_to_string('APP_NAME/email.html', context)
    send_email(html)

This tip is from here.

Design a site like this with WordPress.com
Get started