Django小技巧15: 使用基于類視圖的Mixins
Posted November 05, 2018
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAjM2EzLcd3LcJzLcJzdllmVldWYtl2PnVGcq5CehdDc14GdyU3bvwFN1AjNxQTMtUGall3LcVmdhNXLwRHdo9CXt92YucWbpRWdvx2Yx5yazF2Lc9CX6MHc0RHaiojIsJye.jpeg)
翻譯整理自: simpleisbetterthancomplex.com
今天講述三點關于 Mixins 使用的一些規範:
- Django 提供的View 保持在繼承的最右邊.
- Mixins 在基本視圖的左側
- Mixins 應該繼承Python的内置對象類型(object).
下面舉例說明規則
Python
class FormMessageMixin(object):
@property
def form_valid_message(self):
return NotImplemented
form_invalid_message = 'Please correct the errors below.'
def form_valid(self, form):
messages.success(self.request, self.form_valid_message)
return super(FormMessageMixin, self).form_valid(form)
def form_invalid(self, form):
messages.error(self.request, self.form_invalid_message)
return super(FormMessageMixin, self).form_invalid(form)
class DocumentCreateView(FormMessageMixin, CreateView):
model = Document
fields = ('name', 'file')
success_url = reverse_lazy('documents')
form_valid_message = 'The document was successfully created!'
複制
依類似的方式, 你可以在UpdateView中, 重用相同的FormMessageMixin, 并覆寫預設的
form_invalid_message
方法.
Python
class DocumentUpdateView(FormMessageMixin, UpdateView):
model = Document
fields = ('name', )
success_url = reverse_lazy('documents')
form_valid_message = 'The document was successfully updated!'
form_invalid_message = 'There are some errors in the form below.'
複制
Django 1.9開始, 内置的LoginRequiredMixin和UserPassesTestMixin. 如果你要在視圖中使用它們, 它們始終位于最左側:
Python
Mixins在左,View在後
class DocumentUpdateView(LoginRequiredMixin, FormMessageMixin, UpdateView):
model = Document
fields = ('name', )
success_url = reverse_lazy('documents')
form_valid_message = 'The document was successfully updated!'
複制