Python import_module 的 Django 1.9 导入错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32761566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:12:22  来源:igfitidea点击:

Django 1.9 ImportError for import_module

pythondjangodjango-1.9

提问by Matt

When trying to run either runserveror shellusing manage.pyI get an ImportErrorexception. I'm using Django 1.9.

尝试运行runservershell使用时manage.py出现ImportError异常。我正在使用 Django 1.9。

ImportError: No module named 'django.utils.importlib'

采纳答案by knbk

django.utils.importlibis a compatibility library for when Python 2.6 was still supported. It has been obsolete since Django 1.7, which dropped support for Python 2.6, and is removed in 1.9 per the deprecation cycle.

django.utils.importlib是仍然支持 Python 2.6 时的兼容性库。它从 Django 1.7 开始就已经过时了,Django 1.7 放弃了对 Python 2.6 的支持,并在每个弃用周期中在 1.9 中被删除。

Use Python's import_modulefunction instead:

改用 Python 的import_module函数:

from importlib import import_module

The reason you can import it from django.utils.module_loadingis that importlib.import_moduleis imported in that module, it is notbecause module_loadingin any way defines the actual function.

你可以从导入它的原因django.utils.module_loadingimportlib.import_module是,模块进口,这是不是因为module_loading以任何方式限定的实际功能。

Since django.utils.module_loading.import_moduleis not part of the public API, it can be removed at any time if it is no longer used - even in a minor version upgrade.

由于django.utils.module_loading.import_module它不是公共 API 的一部分,因此如果不再使用它,可以随时将其删除 - 即使是在次要版本升级中。

回答by Matt

I solved this with the following:

我用以下方法解决了这个问题:

try:
    # Django versions >= 1.9
    from django.utils.module_loading import import_module
except ImportError:
    # Django versions < 1.9
    from django.utils.importlib import import_module