I am a newbie of python, I want to create 3 class, as the following:
class ProtectTemplate(TemplateView):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ProtectTemplate, self).dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
context['phone'] = xxx
return context
class ProtectList(ListView):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ProtectList, self).dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
context['phone'] = xxx
return context
class ProtectDetail(DetailView):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ProtectDetail, self).dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
context['phone'] = xxx
return context
I think it is terrible. So I try to do as the following:
login_class = [
('ProtectTemplate', TemplateView),
('ProtectList', ListView),
('ProtectDetail', DetailView),
]
for c, v in login_class:
class c(v):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(self.__class__, self).dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
context['phone'] = xxx
return context
But it does not work. Is there anyway to batch create the 3 class?