在Custom Django Templatetags中导入Python模块

时间:2011-03-16 20:25:29

标签: python django django-templates python-import

我在我的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!
>>> 

我甚至可以在import titlecase文件中执行settings.py而不会出错。

但是,当我在模板标签库import titlecase中尝试smarttitle.py时,我得到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,但这没有帮助 - 我仍然在我的templatetag模块中获取ImportError。我已经手动调用了正确的python二进制文件。

3 个答案:

答案 0 :(得分:2)

如评论中所述,您需要在运行devserver之前通过source bin/activate(或仅. bin/activate)激活您的virtualenv,即使您已经访问了正确的Python可执行文件。

答案 1 :(得分:2)

我知道这太旧了,但今天我遇到了类似的问题。

问题似乎使用相同名称的应用程序和模块,因此当它尝试导入时,可能无法在错误的位置查找所需的模块或功能。

我建议您为django应用或模块提供不同的名称

答案 2 :(得分:-1)

这不是解决方法,只是为了确定我们正在查看相同的问题/错误:

如果您将smarttitle.py中的导入更改为

from YOURPROJECT.titlecase import titlecase as _to_titlecase

它将与'runserver'一起使用但在生产时会失败(在我的情况下是uwsgi / nginx)