How do I use Django 1.2 templates in my Google App Engine project?
Can anyone suggest a detailed resource for including django 1.2 templating in our GAE apps? So far I have found
- docs describing how to zip up the django files and add them to our project
- docs on running native django projects in GA
- docs about including 1.0 and 1.1 libraries into our projects
but nothing yet describing how to use django 1.2 templates in our projects. Specifically, how to formulate the arcane wizardry at the top of my python script that will magically convince GAE to use my zipped up django library.
I have this in my python script:
import sys
sys.path.insert(0, 'django/django.zip')
And similar to the GAE tutorial, here's how I'm rendering the template:
template_values = {
'formerror': formerror,
'media': media,
'status': status
}
path = os.path.join(os.path.dirname(__file__), formtemplate)
self.response.out.write(te开发者_如何学Pythonmplate.render(path, template_values)
But there is some piece missing for GAE to use Django 1.2 to render the templates. What is it?
I used this:
from google.appengine.dist import use_library
use_library('django', '1.1')
from google.appengine.ext.webapp import template
In this case I used 1.1 version but I think it should work the same for 1.2.
I had the same problem a while ago - I wanted to use version 1.2 version for templates instead of 0.96 (that is provided by GAE). The following code seems to work for me.
# some standard Google App Engine imports (optional)
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext import db
# Remove Django modules (0.96) from namespace
for k in [k for k in sys.modules if k.startswith('django')]:
del sys.modules[k]
# Force sys.path to have our own directory first, in case we want to import
# from it. This way, when we import Django, the interpreter will first search
# for it in our directory.
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
# Must set this env var *before* importing any part of Django
# (that's required in Django documentation)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
# New Django imports
from django.template.loader import render_to_string
from django.conf import settings
# Configure dir with templates
# our template dir is: /templates
TEMPLATE_DIR = os.path.join(os.path.dirname(__file__),'templates')
settings.configure(TEMPLATE_DIRS = (TEMPLATE_DIR,'') )
However, if you need only templates from Django, and no other API, consider using Jinja instead. That's what I'm planning to do.
精彩评论