2011-01-24 99 views
3

我注意到一個奇怪的行爲與Django如何處理我的url模式。用戶應該登錄,然後重定向到他們的個人資料頁面。我也有能力讓用戶編輯他們的個人資料。Django - 查看,網址奇怪

這裏是我的我的應用程序的一個URL模式:

urlpatterns=patterns('student.views', 
    (r'profile/$', login_required(profile,'student')), 
    (r'editprofile/$', login_required(editprofile,'student')), 
) 

這是被稱爲學生的應用程序。如果用戶轉到/ student/profile,他們應該得到配置文件視圖。如果他們去/學生/ editprofile他們應該得到editprofile視圖。我設置了一個名爲login_required的函數來對用戶進行一些檢查。這比僅僅註釋可以處理的要複雜一點。

這裏的login_required:

def login_required(view,user_type='common'): 
    print 'Going to '+str(view) 
    def new_view(request,*args,**kwargs): 
     if(user_type == 'common'): 
      perm = '' 
     else: 
      perm = user_type+'.is_'+user_type 
     if not request.user.is_authenticated(): 
      messages.error(request,'You must be logged in. Please log in.') 
      return HttpResponseRedirect('/') 
     elif request.user.is_authenticated() and user_type != 'common' and not request.user.has_perm(perm): 
      messages.error(request,'You must be an '+user_type+' to visit this page. Please log in.') 
      return HttpResponseRedirect('/') 
     return view(request,*args,**kwargs) 
    return new_view 

不管怎麼說,奇怪的事情是,當我訪問/學生/ profile文件,即使我得到正確的頁面,login_required打印以下內容:

Going to <function profile at 0x03015DF0> 
Going to <function editprofile at 0x03015BB0> 

爲什麼要同時打印?爲什麼它試圖訪問這兩個?

更加古怪,當我試圖訪問/學生/ editprofile,個人資料頁是什麼樣的負載,這是集團的印刷什麼:

Going to <function profile at 0x02FCA370> 
Going to <function editprofile at 0x02FCA3F0> 
Going to <function view_profile at 0x02FCA4F0> 

view_profile是在一個完全不同的應用程序的功能。

+3

關於decorators.login_required()和decorators.permission_required()是什麼讓人無法忍受? – hop 2011-01-24 19:11:20

回答

2

這兩種模式:

(r'profile/$', login_required(profile,'student')), 
(r'editprofile/$', login_required(editprofile,'student')), 

都匹配http://your-site/student/editprofile

嘗試:

(r'^profile/$', login_required(profile,'student')), 
(r'^editprofile/$', login_required(editprofile,'student')), 

Django使用誰的模式首先匹配(see number 3 here)的觀點。

+0

這是個問題。我認爲,因爲這urls.py被包含在另一個urls.py,我不會在前面使用'^',但事實證明我需要。謝謝! – JPC 2011-01-24 21:31:04

1

您的login_required看起來像是一個Python裝飾器。任何你需要在你的urls.py中擁有它的理由?

我認爲print 'Going to '+str(view)線正在被評估,當urlpatterns被讀取,以確定要執行的視圖。它看起來很奇怪,但我認爲它不會傷害你。

print 'Going to '+str(view)就不會在每次視圖被擊中時執行,只有當URL模式進行評估(我認爲)。在new_view的代碼是將對於某些執行作爲視圖的一部分的唯一代碼。

+0

也許我可以用它作爲裝飾。但即使如此...確實,你對new_view的執行是正確的,但是爲什麼當我嘗試編輯配置文件時會加載錯誤的視圖 – JPC 2011-01-24 21:26:19

2

不知道爲什麼你不能使用標準@login_required裝飾 - 似乎你的版本實際上提供的功能,因爲它總是重定向到\,而不是實際的登錄視圖。

在任何情況下,爲什麼既被打印的原因是因爲所述print語句是在裝飾的頂層,因此當URL配置是評價被執行。如果將它放在內部new_view函數中,它只會在實際調用時執行,並且應只打印相關的視圖名稱。

+0

您對打印語句是正確的,但爲什麼錯誤的視圖仍然返回editprofile – JPC 2011-01-24 21:26:56