python - 使用 django 独立版与 python3 的异常

标签 python django python-3.x

尝试在独立模式下使用 django 模板。 我得到了这些异常(exception)(如下)。 python新手,想知道是否有人愿意帮忙。

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“导入 django; print(django.get_version())” ---> 1.9.7

我的Python版本:

Python 3.4.3

最佳答案

调用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了解更多信息。

关于python - 使用 django 独立版与 python3 的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38312660/

相关文章:

python测量两个相似图像的质量

python - django-mptt:如何成功移动节点

python - 为什么从 Spark 写入 Vertica DB 比从 Spark 写入 MySQL 需要更长的时间?

javascript - 从 JavaScript 调用 Django View

python - 无法在基于 Django 的基本网站上显示 mysql 数据库

python - 带有 flat=True 的 Values_list 仍显示括号

python - 如何编写 setup.py 以包含 Git 存储库作为依赖项

python - 在 Django 1.10 中使用 Postgres 搜索时出现 NotImplementedError

Python asyncio任务列表生成而不执行函数

python - 在Python中使简单的绘图变得平滑