我有一个基于 Django 类的视图,它覆盖了
dispatch
方法。
我想向这个基于类的视图添加一个混合。
mixin 还重写了
dispatch
方法。
是否可以在基于类的视图自定义
dispatch
方法之前执行 mixins dispatch
方法?如果是这样,我将如何实施?
目前,当我实现我的解决方案时,如以下示例所示,CustomerCreateView 的自定义
dispatch
方法首先触发,这不是我需要的。
class MyMixin(LoginRequiredMixin):
def dispatch(self, request, *args, **kwargs):
....
return super().dispatch(request, *args, **kwargs)
class CustomerCreateView(MyMixin, CreateView):
model = Customer
form_class = CreateCustomerForm
title = "Add a New Customer"
def dispatch(self, request, *args, **kwargs):
...
return super().dispatch(request, *args, **kwargs)
MyMixin 是 CustomerCreateView 的超类。所以
CustomerCreateView.dispatch
总是会首先被调用。但您可以在运行该方法的其余部分之前自己调用 MyMixin.dispatch
:
class CustomerCreateView(MyMixin, CreateView):
model = Customer
form_class = CreateCustomerForm
title = "Add a New Customer"
def dispatch(self, request, *args, **kwargs):
# Call MyMixin.dispatch
response = super().dispatch(request, *args, **kwargs)
# Do other stuff
...
return response
或者,您可以重新安排继承:
class MyMixin(LoginRequiredMixin):
def dispatch(self, request, *args, **kwargs):
...
return super().dispatch(request, *args, **kwargs)
class CustomerCreateView(CreateView):
model = Customer
form_class = CreateCustomerForm
title = "Add a New Customer"
def dispatch(self, request, *args, **kwargs):
...
return super().dispatch(request, *args, **kwargs)
class CorrectView(MyMixin, CustomerCreateView):
# MyMixin.dispatch will be called first