解决django ImportError: Settings cannot be imported错误
转:http://www.iyouf.info/fixed-django-settings-error.html 今天在练习django的模板引擎的时候出了这么一个错误
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
root@ubuntu:~# python Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information.
from django.template import Template t = Template("my name is {{name}}") Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.6/dist-packages/django/template/init.py", line 156, in init if settings.TEMPLATE_DEBUG and origin is None: File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 276, in getattr self._setup() File "/usr/local/lib/python2.6/dist-packages/django/conf/init.py", line 38, in _setup raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE) ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. 这是因为我在命令行下使用python命令进入交互模式的,Template(str)在构照模板的时候依赖django.conf.settings.这个变量,但是在当前的环境中没有这个变量,这时,它就会抛出异常了
办法就是 要想使用django的模板你必须导入settings
from django.conf import settings settings.configure() 你在运行t = Template("my name is {{name}}") 就不会出错了
还有一种方法就是使用python manager.py shell运行
root@ubuntu:/home/python/cms# python manage.py shell Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole)
from django.template import Template,Context t=Template('my name is {{name}}') c=Context({'name':'dengmin'}) t.render(c) u'my name is dengmin'
这是因为python manager.py shell的时候djano会去查找settings.py,这个文件包含了这个Django实例的所有配置选项
打开这个文件我们可以看到这样的配置
List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader',
'django.template.loaders.eggs.Loader',
) 这个是django提供的模板加载器
在目录/usr/local/lib/python2.6/dist-packages/django/template/loaders下找到这两个文件
filesystem.py app_directories.py,这两个文件中都导入from django.conf import settings
最后,在使用django的模板时,应该使用python manager.py shell来进入交互模式,这样可以避免很多不必要的麻烦