aus*_*man 4 django templates django-templates django-settings
我正在尝试使用 Django 模板系统作为 python 脚本中的工具来输出文件。我不需要 Django 框架的其他组件。
我按照说明将模板系统配置为独立模式,但是当我尝试使用template.loader.render_to_string()、template.loader.get_template()或 时,template.render(Content())我得到了AppRegistryNotReady异常:
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
Run Code Online (Sandbox Code Playgroud)
settings.configure()如文档中所述,我有以下调用:
settings.configure(
DEBUG=DEBUG,
TEMPLATE_DEBUG=True,
TEMPLATE_DIRS=(
POSTS_DIR,
TEMPLATES_DIR,
PAGES_DIR,
),
)
Run Code Online (Sandbox Code Playgroud)
我也尝试添加INSTALLED_APPS=(),同样的问题。我只想使用模板系统。除了模板加载器之外我不需要任何东西,所以我可以使用extend模板。
如果您的代码确实是独立的,您必须调用django.setup():
import os
import django
from django.conf import settings
from django.template.loader import render_to_string
settings.configure(
TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.dirname(os.path.realpath(__file__))], # script dir
}]
)
django.setup()
message = render_to_string(
'mail_template.html',
{'variable1337': 1337}
)
print(message)
Run Code Online (Sandbox Code Playgroud)
另外,TEMPLATE_DIRS已弃用。当前接受的答案不再正确。