how to render django template from code instead of file on Google App Engine
In order to render a template 'in memory', there are a few things you'll need to do:
App Engine Setup
First of all, you'll need to ensure that everything is set up correctly for Django. There's a lot of information on the Third-party libraries page, but I'll include it here for your benefit.
In main.py
, or (whatever your script handler is), you'll need to add the following lines:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.2') # Change to a different version as you like
Don't forget to include django
in your app.yaml
:
libraries:
- name: django
version: "1.2"
Code Setup
Second of all, you'll need to create a Template
object, as denoted in the Google App Engine template documentation. For example:
from google.appengine.ext.webapp import template
# Your code...
template_string = "Hello World"
my_template = template.Template(template_string)
# `context` is optional, but will be useful!
# `context` is what will contain any variables, etc. you use in the template
rendered_output = template.render(context)
# Now, do what you like with `rendered_output`!
You can instantiate a template from text in Django with just template.Template(my_text)
.