2016-07-11 33 views
1

嘗試在獨立模式下使用django模板。 我得到這些例外(如下)。 python新手,想知道是否有人願意幫忙。使用django獨立於python3的例外

Django用於在此處未顯示的腳本中進行模板化。 但是,啓動它時會出現完全相同的例外情況。

>>> from django.template import Template, Context 
>>> from django.conf import settings 
>>> settings.configure() 
>>> t = Template('My name is {{ my_name }}.') 
Traceback (most recent call last): 
    File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py", line 86, in __getitem__ 
    return self._engines[alias] 
KeyError: 'django' 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/local/lib/python3.4/dist-packages/django/template/base.py", line 182, in __init__ 
    engine = Engine.get_default() 
    File "/usr/lib/python3.4/functools.py", line 472, in wrapper 
    result = user_function(*args, **kwds) 
    File "/usr/local/lib/python3.4/dist-packages/django/template/engine.py", line 88, in get_default 
    django_engines = [engine for engine in engines.all() 
    File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py", line 110, in all 
    return [self[alias] for alias in self] 
.... 
.... 
    File "/usr/local/lib/python3.4/dist-packages/django/apps/registry.py", line 137, in get_app_configs 
    self.check_apps_ready() 
    File "/usr/local/lib/python3.4/dist-packages/django/apps/registry.py", line 124, in check_apps_ready 
    raise AppRegistryNotReady("Apps aren't loaded yet.") 
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. 

我的Django的版本:

python3 -c "import django; print(django.get_version())" ---> 1.9.7

我的Python版本:

Python 3.4.3

+0

[使用django進行CLI工具]的可能重複(http://stackoverflow.com/questions/32088702/using-django-for-cli-tool) – e4c5

回答

2

調用settings.configure()之後,你必須調用django.setup()

import django 
from django.conf import settings 
settings.configure() 
django.setup() 
from django.template import Template, Context 
t = Template('My name is {{ my_name }}.') 
c=Context({'my_name': 'Mindaugas'}) 
t.render(c) 

更多信息,請參見the docs