Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template system standalone

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.

like image 383
austinheiman Avatar asked Dec 19 '22 07:12

austinheiman


2 Answers

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.

like image 154
Yannic Hamann Avatar answered Dec 22 '22 09:12

Yannic Hamann


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',),
)
like image 28
catavaran Avatar answered Dec 22 '22 09:12

catavaran