2012-04-18 28 views
9

我寫在位於應用程序direcroty一個utils.py這funcion:導入錯誤的models.py

from bm.bmApp.models import Client 

def get_client(user): 
    try: 
     client = Client.objects.get(username=user.username) 
    except Client.DoesNotExist: 
     print "User Does not Exist" 
     return None 
    else:  
     return client 

def to_safe_uppercase(string): 
    if string is None: 
     return '' 
    return string.upper() 

然後當我使用功能to_safe_uppercase在我的models.py文件,通過將其導入這種方式:

from bm.bmApp.utils import to_safe_uppercase 

我得到了蟒蛇錯誤:

 from bm.bmApp.utils import to_safe_uppercase 
ImportError: cannot import name to_safe_uppercase 

我得到這個問題的解決方案時,我變化率T他進口的聲明爲:

from bm.bmApp.utils import * 

但我不明白爲什麼這是爲什麼當我導入特定功能時,我得到了錯誤?

+0

這不應該發生。我懷疑還有其他事情正在發生。 – Marcin 2012-04-18 15:41:40

+0

不幸的是,django默認捕獲ImportErrors並用這個錯誤消息替換它們。嘗試修補django,以便它給你回溯,這應該指向問題。我懷疑循環進口或類似的東西。 – ch3ka 2012-04-18 15:46:48

+0

@ ch3ka補丁django不是一個好主意......他也已經獲得了python追溯。當然,他在問題 – Jiaaro 2012-04-18 15:48:02

回答

0

我不確定我能解釋導入錯誤,但我有三個想法。首先,你的功能需要調整。你已經使用了一個保留字'string'作爲參數。考慮重命名。

其次,如果您調用./manage.py shell並手動執行導入,會發生什麼情況。它會給你什麼不同嗎?

第三,儘量刪除您的PYC文件強制Django的重新編譯Python代碼(這個人是一個很長鏡頭......但值得消除)

+0

我以爲是'str' – Jiaaro 2012-04-18 15:46:32

+0

這是str。但字符串是stdlib中的一個模塊... – ch3ka 2012-04-18 15:48:39

7

您正在創建一個圓形進口。

utils.py 
from bm.bmApp.models import Client 
# Rest of the file... 

models.py 
from bm.bmApp.utils import to_safe_uppercase 
# Rest of the file... 

我建議你重構你的代碼,這樣你沒有一個循環依賴DO(即utils的不應該需要進口models.py或反之亦然)。

+0

爲什麼當OP使用'from ... import *'時它會工作? – jadkik94 2012-04-18 16:02:42

+0

請參閱http://docs.python.org/faq/programming.html#what-are-the-best-practices-for-using-import-in-a-module – 2012-04-18 17:01:56

+0

謝謝。你應該考慮在你的答案中增加一些關於它的內容,這是OP問題的一部分。 :) – jadkik94 2012-04-18 19:06:56

10

您正在做所謂的循環導入。

models.py:

from bm.bmApp.utils import to_safe_uppercase 

utils.py:

from bm.bmApp.models import Client 

現在,當你做import bm.bmApp.models的解釋執行以下操作:

  1. models.py - Line 1:嘗試導入bm.bmApp.utils
  2. utils.py - Line 1:嘗試導入bm.bmApp.models
  3. models.py - Line 1:嘗試導入bm.bmApp.utils
  4. utils.py - Line 1:嘗試導入bm.bmApp.models
  5. ...

最簡單的方法是將導入內部功能:

utils.py:

def get_client(user): 
    from bm.bmApp.models import Client 
    try: 
     client = Client.objects.get(username=user.username) 
    except Client.DoesNotExist: 
     print "User Does not Exist" 
     return None 
    else:  
     return client 

def to_safe_uppercase(string): 
    if string is None: 
     return '' 
    return string.upper()