2013-10-01 79 views
0

我正在改進標準的民意調查應用程序。Django。裝飾問題。

在那裏,我有一些代碼,需要很多意見要重複:代碼中的鏈接張貼數計算的各種民意調查(有效,無效,流行)的數量,如:

1) View all active polls (number of polls).
2) View all closed polls (number of polls).

etc.

所以,不管事實的,我需要重複這個代碼很多次,我決定做一個裝飾:

def count_number_of_various_polls(func): 
    def count(): 
     # Count the number of active polls. 
     all_active_polls = Poll.active.all() 
     num_of_active_polls = len(all_active_polls) 
     # Count the number of inactive polls. 
     all_inactive_polls = Poll.inactive.all() 
     num_of_inactive_polls = len(all_inactive_polls) 
     # Count the number of popular polls per the last month. 
     popular_polls = Poll.popular.filter(pub_date__gte=timezone.now() 
            - datetime.timedelta(days=days_in_curr_month)) 
     num_of_popular_polls = len(popular_polls) 
     func() 
    return count 

然後我想裝飾我index觀點:

@count_number_of_various_polls 
def index(request): 
    latest_poll_list = Poll.active.all()[:5] 
    return render(request, 'polls/index.html', { 
     'latest_poll_list': latest_poll_list, 
     'num_of_popular_polls': num_of_popular_polls, 
     'num_of_active_polls': num_of_active_polls, 
     'num_of_inactive_polls': num_of_inactive_polls 
     }) 

當我嘗試打開我的開發服務器上投票索引頁,我得到以下錯誤:

TypeError at /polls/ 
count() takes no arguments (1 given) 

我不知道1個論點是什麼。 問題在哪裏?

回答

4

參數是視圖的參數,即request。你需要接受你count()功能這樣的說法,並把它傳遞到func

def count_number_of_various_polls(func): 
    def count(request): 
     ... 
     func(request) 
    return count 

然而,這是不是真的這樣做的一個很好的方式,因爲你仍然依靠視圖本身傳遞將這些元素放入模板上下文中。您應該查看context processorstemplate tags作爲更好的選擇。