在自定义Django Templatetags中导入Python模块

2024-09-26 18:06:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在pythondjango安装中使用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位于dev_environ/lib/python2.6/site-packages/titlecase的{}中。在

^{pr2}$

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

但是,当我试图在我的templatetag库smarttitle.pyimport titlecase时,我得到了一个ImportError。在

智能标题.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模块导入到任何的地方,除了在这个templatetag库中,它抛出一个ImportError!什么给予?!有什么想法吗?在


编辑:我首先尝试运行source dev_environ/bin/activate来将我的shell env切换到virtualenv,但这没用——我仍然在templatetag模块中获取ImportError。我已经手动调用了正确的python二进制文件。在


Tags: djangofrompydevimportprojectbinvirtualenv
3条回答

这不是一个修复程序,但只是为了确定我们看到的是相同的问题/错误:

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

from YOURPROJECT.titlecase import titlecase as _to_titlecase

它可以与“runserver”一起工作,但在生产环境中会失败(在我的例子中是uwsgi/nginx)

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

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

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

我建议您为django应用程序或模块指定不同的名称。在

相关问题 更多 >

    热门问题