【发布时间】:2011-03-16 20:25:29
【问题描述】:
我在我的 Python Django 安装中使用 virtualenv。
这是我的目录结构:
project/
dev_environ/
lib/
python2.6/
site-packages/
...
django/
titlecase/ # <-- The titlecase module
PIL/
...
bin/
...
python # <-- Python
...
include/
django_project/
localsite/
templatetags/
__init__.py
smarttitle.py # <-- My templatetag module
foo_app/
bar_app/
settings.py
manage.py
如果我启动我的 Django shell 并尝试导入 titlecase 一切都很好,因为 titlecase 在 sys.path dev_environ/lib/python2.6/site-packages/titlecase 中。
$:django_project cwilcox$ ../dev_environ/bin/python manage.py shell
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import titlecase # <-- No Import Error!
>>>
我什至可以在我的settings.py 文件中创建import titlecase 而不会出错。
但是,当我尝试在我的模板标签库 smarttitle.py 中使用 import titlecase 时,我得到一个 ImportError。
smarttitle.py如下。
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
from titlecase import titlecase as _to_titlecase
@register.filter
@stringfilter
def smarttitle(value):
return _to_titlecase(value)
smarttitle.is_safe = True
不仅如此,我什至可以在呈现模板的视图中 import titlecase 尝试 {% load smarttitle %} 并且没有错误。
我的 Django 开发服务器启动于...
../dev_environ/bin/python manage.py runserver
总结:
我可以导入titlecase 模块任何地方,除了在这个模板标签库中,它会抛出一个ImportError!是什么赋予了?!有什么想法吗?
编辑:我尝试先运行source dev_environ/bin/activate 将我的shell env 切换到我的virtualenv,但这没有帮助——我的模板标签模块中仍然出现 ImportError。我已经手动调用了正确的 python 二进制文件。
【问题讨论】:
-
可能是一个愚蠢的问题,但您正在执行“source dev_environ/bin/activate”或类似的操作?
-
我不知道
source dev_environ/bin/activate是什么。听起来我错过了一些重要的东西。我想当我安装一些东西时我所要做的就是dev_environ/bin/pip install <module>。 -
运行 'source
/bin/activate' 将您的 $PATH 更改为指向 virtualenv 目录 - 而不是您计算机上的全局 python 安装。在终端中,尝试运行“source dev_environ/bin/activate”,然后运行“python manage.py runserver”——它应该都能正常工作吗? -
@user608 好的,我查了一下
bin/activate做了什么。看起来这只是修改了你的 shell,我已经直接调用了正确的 bin/python,所以我认为这不是问题(我将进行编辑以使其更清楚)。 -
我也有同样的问题。
标签: python django django-templates python-import