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

后端 未结 13 1025
天命终不由人
天命终不由人 2020-11-29 16:17

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)

13条回答
  •  既然无缘
    2020-11-29 16:54

    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

提交回复
热议问题