I am trying to use the Django template system as a tool in a python script to output files. I need no other component of the Django framework.
I followed the instructions to configure the template system for standalone mode, but when I try to use template.loader.render_to_string()
, template.loader.get_template()
, or template.render(Content())
I get back the AppRegistryNotReady
exception:
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I have the following settings.configure()
call as described in the docs:
settings.configure(
DEBUG=DEBUG,
TEMPLATE_DEBUG=True,
TEMPLATE_DIRS=(
POSTS_DIR,
TEMPLATES_DIR,
PAGES_DIR,
),
)
And I tried adding in INSTALLED_APPS=()
as well, same problem. I just want to use the templating system. I don't need anything except for template loaders so I can extend
templates.
If your code is truly standalone you have to invoke 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)
Also, TEMPLATE_DIRS
is deprecated. The current accepted answer is no longer correct.
I suspect that this error is thrown from django.template.loaders.app_directories.Loader
. Try to add TEMPLATE_LOADERS
setting:
settings.configure(
DEBUG=DEBUG,
TEMPLATE_DEBUG=True,
TEMPLATE_DIRS=(
POSTS_DIR,
TEMPLATES_DIR,
PAGES_DIR,
),
TEMPLATE_LOADERS=('django.template.loaders.filesystem.Loader',),
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With