Search code examples
pythondjangotemplatesdjango-templatestemplate-engine

How do I use Django templates without the rest of Django?


I want to use the Django template engine in my (Python) code, but I'm not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO_SETTINGS_MODULE environment variable?

If I run the following code:

>>> import django.template
>>> from django.template import Template, Context
>>> t = Template('My name is {{ my_name }}.')

I get:

ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

Solution

  • An addition to what other wrote, if you want to use Django Template on Django > 1.7, you must give your settings.configure(...) call the TEMPLATES variable and call django.setup() like this :

    from django.conf import settings
    
    settings.configure(TEMPLATES=[
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': ['.'], # if you want the templates from a file
            'APP_DIRS': False, # we have no apps
        },
    ])
    
    import django
    django.setup()
    

    Then you can load your template like normally, from a string :

    from django import template   
    t = template.Template('My name is {{ name }}.')   
    c = template.Context({'name': 'Rob'})   
    t.render(c)
    

    And if you wrote the DIRS variable in the .configure, from the disk :

    from django.template.loader import get_template
    t = get_template('a.html')
    t.render({'name': 5})
    

    Django Error: No DjangoTemplates backend is configured

    http://django.readthedocs.io/en/latest/releases/1.7.html#standalone-scripts