1
嗨,我有一個基於類的視圖,我想用一些函數來裝飾它的dispatch方法,以便在args/kwargs的基礎上執行一些有用的操作。基於類視圖 代碼是這樣的:基於類視圖的裝飾器
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)
我的簡化裝飾看起來是這樣的:
def view_count(func):
def actual_decorator(*args, **kwargs):
#do something useful here
func(*args, **kwargs)
return actual_decorator
結果是「ProjectDetailView沒有返回HttpResponse對象」。凡做我犯錯和我該怎麼做,我知道它簡單的事情,但這是我的第一個裝飾者做任何有用的事情!