我想實現staff_member_required混入:Django中混入了基於類的通用視圖
這裏有兩種方法,我就怎麼做,以便發現:
第一:
class StaffRequiredMixin(object):
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
if not request.user.is_staff:
messages.error(
request,
'You do not have the permission required to perform the '
'requested operation.')
return redirect(settings.LOGIN_URL)
return super(StaffRequiredMixin, self).dispatch(request,
*args, **kwargs)
第二:
class StaffRequiredMixin(object):
@classmethod
def as_view(self, *args, **kwargs):
view = super(StaffRequiredMixin, self).as_view(*args, **kwargs)
return staff_member_required(view)
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
if not request.user.is_staff:
messages.error(
request,
'You do not have the permission required to perform the '
'requested operation.')
return redirect(settings.LOGIN_URL)
return super(StaffRequiredMixin, self).dispatch(request,
*args, **kwargs)
我想知道的是:
爲什麼第二種方法是重寫
as_view()
方法並用staff_member_required
包裝它?通過這樣做我們是否有任何「附加」優勢?
我是這些mixin的新手。請幫忙。