簡體   English   中英

在自定義Django模板標簽中導入Python模塊

[英]Importing a Python Module inside Custom Django Templatetags

我在我的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的外殼和嘗試導入titlecase ,一切都很好,因為titlecase是在sys.pathdev_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而不會出現錯誤。

但是,當我嘗試在我的templatetag庫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可以在視圖模板中import titlecase ,以渲染試圖{% load smarttitle %}的模板,並且沒有錯誤。

我的Django開發服務器開始於...

../dev_environ/bin/python manage.py runserver

綜上所述:

我可以將titlecase模塊導入此templatetag庫之外的任何地方,在該地方它會引發ImportError 是什么賦予了?! 有任何想法嗎?


編輯 :我嘗試首先運行source dev_environ/bin/activate將我的外殼環境切換到我的virtualenv,但這沒有幫助-我仍然在我的templatetag模塊中得到ImportError。 我已經在手動調用適當的python二進制文件。

我知道這太舊了,但是今天我遇到了類似的問題。

問題似乎是為應用程序和模塊使用了相同的名稱 ,因此當嘗試導入時,可能無法在錯誤的位置查找所需的模塊或功能。

我建議您為django應用程序或模塊使用不同的名稱

如評論中所述,即使您已經在訪問正確的Python可執行文件,也需要在運行devserver之前通過執行source bin/activate (或僅. bin/activate )來激活您的virtualenv。

這不是修復程序,而只是為了確定我們正在查看相同的問題/錯誤:

如果將smarttitle.py的導入smarttitle.py

from YOURPROJECT.titlecase import titlecase as _to_titlecase

它可以與“ runserver”一起使用,但在生產時將失敗(在我的情況下為uwsgi / nginx)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM