2013-10-01 83 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作为更好的选择。