2017-08-27 77 views
0

在「MYAPP」我有一個模型「資料」,這股與我的自定義用戶模型OnetoOneField關係。在我的許多觀點中,我需要檢查用戶是否設置了配置文件。所以,我創建了一個模塊「profilecheck」包含此功能:自定義函數來查詢數據庫跨Django的意見

def has_profile(req): 
    try:  
     profile = Profile.objects.get(user=req.user) 
     return profile 
    except: 
     return False 

在我的views.py,我有以下幾點:

from myapp.utils.profilecheck import has_profile 
from myapp.models import Profile 

def viewprofile(request): 
    if has_profile(request): 
     context = { 
      'profile': has_profile(request) 
     } 
     return render(request, 'profile.html', context)   
    else: 
     return render(request, 'setup_profile.html', {}) 

當在視圖中調用,has_profile(總是)返回假。任何想法爲什麼?

+0

編輯響應阿米爾阿德南 –

+0

如果你嘗試'打印(Profile.objects.all())'發生了什麼?也許您的個人資料數據還沒有建立,或者你還沒有登錄.. –

回答

0

因爲你試圖在has_profile功能使用一個未定義的變量。您正在嘗試使用request.user,但沒有定義request因此它提出了哪些獲取except子句捕獲的異常,並返回False,你需要傳遞請求作爲參數has_profile功能。

+0

我已經試過了,但它仍然返回False –

+0

告訴我你如何更新'has_profile'功能,你現在是如何調用它。 –

+0

已編輯的問題,請看看 –