我正在使用 Django,我需要从给定的模板 (lab.html) 动态生成一个 HTML 文件:
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
Run Code Online (Sandbox Code Playgroud)
但是,我不断收到这个奇怪的错误,经过一些研究,我在任何地方都找不到。有什么想法吗?
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.
Run Code Online (Sandbox Code Playgroud)
Gar*_*lak 10
对于 Django > 1.7,您settings.py应该为列表中的BACKEND键设置一些值TEMPLATES。基本上你应该在你的设置中有这样的东西
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
# ... some options here ...
},
},
]
Run Code Online (Sandbox Code Playgroud)
从文档:
BACKEND是实现 Django 模板后端 API 的模板引擎类的虚线 Python 路径。内置后端是django.template.backends.django.DjangoTemplates和django.template.backends.jinja2.Jinja2。
编辑:要从命令行而不是使用该render方法的视图加载模板,您必须做更多的工作。
如果不想使用磁盘中的模板,可以使用以下命令:
from django.conf import settings
settings.configure()
from django.template import Template, Context
Template('Hello, {{ name }}!').render(Context({'name': 'world'}))
Run Code Online (Sandbox Code Playgroud)
但是,如果您想从磁盘加载模板,则需要更多的努力。像这样的事情会起作用:
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'})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4002 次 |
| 最近记录: |