2017-05-07 23 views
1

我使用Django和我需要動態地從給定模板的HTML文件(lab.html):Django的錯誤:沒有DjangoTemplates後端配置

from django.template import Template, Context 
from django.conf import settings 

settings.configure() 
f = qc.QFile('lab.html') 
f.open(qc.QFile.ReadOnly | qc.QFile.Text) 
stream = qc.QTextStream(f) 
template = stream.readAll() 
print(template) 
f.close() 

t = Template(template) 
c = Context({"result": "test"}) #result is the variable in the html file that I am trying to replace 

不過,我不斷收到這個奇怪的錯誤經過一些研究後我沒有找到任何地方。有什麼想法嗎?

Traceback (most recent call last): 
    File "/Users/gustavorangel/PycharmProjects/help/HelpUI.py", line 262, in filesSearch 
    t = Template(template) 

    File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/template/base.py", line 184, in __init__ 
    engine = Engine.get_default() 

    File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/template/engine.py", line 83, in get_default 
    "No DjangoTemplates backend is configured.") 

django.core.exceptions.ImproperlyConfigured: No DjangoTemplates backend is configured. 

回答

3

Django的> 1.7的settings.py你應該在TEMPLATES列表中BACKEND關鍵一定的價值。基本上你應該在你的設置是這樣的

TEMPLATES = [ 
    { 
     'BACKEND': 'django.template.backends.django.DjangoTemplates', 
     'DIRS': [], 
     'APP_DIRS': True, 
     'OPTIONS': { 
      # ... some options here ... 
     }, 
    }, 
] 

從文檔:

BACKEND是虛線Python的路徑實現Django的模板後端API模板引擎類。內置後端是django.template.backends.django.DjangoTemplatesdjango.template.backends.jinja2.Jinja2

Link

編輯: 要加載命令行,而不是使用render方法的視圖模板,你必須做一些更多的工作。

如果你不想使用從磁盤模板,你可以使用以下命令:

from django.conf import settings 
settings.configure() 
from django.template import Template, Context 
Template('Hello, {{ name }}!').render(Context({'name': 'world'})) 

但是,如果你想從磁盤加載模板,這需要更多的努力。像這樣將工作:

import django 
from django.conf import settings 
TEMPLATES = [ 
    { 
     'BACKEND': 'django.template.backends.django.DjangoTemplates', 
     'DIRS': ['/path/to/template'], 
    } 
] 
settings.configure(TEMPLATES=TEMPLATES) 
django.setup() 
from django.template.loader import get_template 
from django.template import Context 
template = get_template('my_template.html') 
template.render(Context({'name': 'world'}) 
+0

謝謝你的答案加勒特,但我的settings.py看起來就像您發佈的一個! :/ –

+0

嘿@GustavoRangel,我已經更新了我的評論,因爲你是在Python shell中而不是從應該工作的視圖中執行此操作。試試這個解決方案! –