关于python:具有基于类的视图的装饰器

decorator with class based view

嗨,我有一个基于类的视图,我想用一些函数来修饰它的分派方法,以便在args/kwargs的基础上执行一些有用的操作。基于类的视图的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from django.utils.decorators import method_decorator
class ProjectDetailView(FormMixin, DetailView):
    template_name = 'account/inner-profile-page.html'
    model = ProjectDetail
    form_class = CommentForm
    context_object_name = 'project'

    @method_decorator(view_count)
    def dispatch(self, *args, **kwargs):
        return super(ProjectDetailView,self).dispatch(*args, **kwargs)

    def get_object(self, queryset=None):
        user = User.objects.get(user_slug=self.kwargs['user_slug'])
        title_slug = self.kwargs['title_slug'].replace(' ','-')
        return get_object_or_404(ProjectDetail, title_slug = title_slug, user=user)

我的简化装饰器如下所示:

1
2
3
4
5
def view_count(func):
    def actual_decorator(*args, **kwargs):
        #do something useful here
        func(*args, **kwargs)
    return actual_decorator

结果是"projectdetailview没有返回httpresponse对象"。我在哪里出错,应该怎么做,我知道它很简单,但这是我第一个做任何有用的装饰的人!


你缺少一个return

1
2
3
def actual_decorator(*args, **kwargs):
    #do something useful here
    return func(*args, **kwargs)