在自定义Django模板标签中导入Python模块
我在使用 virtualenv
来管理我的 Python Django 环境。
这是我的 目录结构:
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 的命令行工具并尝试导入 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
,而且没有错误。
我的 Django 开发服务器是这样启动的……
../dev_environ/bin/python manage.py runserver
总结一下:
我可以在 titlecase
模块中 随便 导入,除了在这个模板标签库里,它却抛出了 ImportError
!这是怎么回事呢?!有什么想法吗?
编辑:我尝试先运行 source dev_environ/bin/activate
来切换我的命令行环境到虚拟环境,但这并没有帮助——我在模板标签模块里还是遇到了 ImportError。我已经手动调用了正确的 Python 可执行文件。
3 个回答
这不是解决办法,只是为了确认我们在讨论同一个问题/错误:
如果你把 smarttitle.py
文件里的导入部分改成
from YOURPROJECT.titlecase import titlecase as _to_titlecase
这样在使用 'runserver' 时会正常工作,但在生产环境下(比如我用的 uwsgi/nginx)就会出错。
我知道这个问题有点老旧,但我今天遇到了类似的问题。
问题似乎是因为应用和模块使用了相同的名字,这样在导入的时候可能会出错,因为它会在错误的地方寻找想要的模块或函数。
我建议你给django应用或模块起不同的名字。
正如评论中提到的,你需要通过运行 source bin/activate
(或者直接用 . bin/activate
)来激活你的虚拟环境,才能启动开发服务器。即使你已经在使用正确的Python程序,这一步也是必须的。