2013-11-25 70 views
1

基於類的觀點之前,我urls.py看上去像是:字符串作爲URL調度第二個參數爲CBV

urlpatterns= patterns('mypackage.views', 
         url(r'^$', 'home', name='home'), 
         url(r'other', name='other'), 
        ) 

現在我家的觀點是基於類。因爲我喜歡統一性,所以我想而不是想保持視圖類爲字符串。我試過:

urlpatterns= patterns('mypackage.views', 
         url(r'^$', 'Home.as_view', name='home'), 
         url(r'Other.as_view', name='other'), 
        ) 

和我得到Parent module mypackage.views.Home does not exist。如果我只是給類的名字,如:

urlpatterns= patterns('mypackage.views', 
         url(r'^$', 'Home', name='home'), 
         url(r'Other', name='other'), 
        ) 

我得到:__init__ takes exactly 1 argument, 2 given

有沒有辦法將一個字符串作爲第二個參數傳遞給url功能CBV作爲FBV而不是from mypackage.views import *

編輯: 似乎沒有內置的解決方案。在這種情況下:爲什麼字符串作爲url函數允許的第二個參數:是不是違反了禪宗(「只有一種方法可以做到這一點)?

回答

2

您應該導入基於類的視圖並指定它們這種方式:

from mypackage.views import * 

urlpatterns = patterns('mypackage.views', 
         url(r'^$', Home.as_view(), name='home'), 
         url(r'other', Other.as_view() name='other'), 
         ) 

另外請注意,您的通話url()應該有三個參數:URL模式,視圖和名稱(你寫了一些例子不具有所有這些)

+0

這是我想弄明白,爲什麼有可能傳遞一個字符串作爲第二個參數,如果它只能用於FBV? – ProfHase85

+0

@ ProfHase85由於歷史原因(即FBV)。通過導入視圖對象並調用'as_view()'完成CBV。 –

+0

FWIW,「import *」語句是惡魔。 「from mypackage.views import Home,Other」 – scoopseven

2

如果你想要的。將您的觀點作爲字符串傳遞,然後在您的觀點中執行此操作:

class Home(View): 
    pass 

home = Home.as_view() 

然後在您的網址:

url(r'^$', 'mypackage.views.home', name='home'), 

您需要使用完整路徑。

+0

謝謝,這是一個可能的解決方案,但是這違反了DRY原則,因爲必須爲每個視圖編寫相同的內容 – ProfHase85