基于类的通用视图和DRY [英] Class Based Generic Views and DRY
问题描述
我正在Django 1.3中实现基于类的视图,并且在这种情况下,我的CreateView,UpdateView和DeleteView几乎相同.有没有一种方法可以仅使用单个视图CreateUpdateView或类似的视图来实现,或者这是实现CBGV的标准方法吗?
I'm implementing class based views in Django 1.3 and I find myself in this scenario where my CreateView, UpdateView and DeleteView are almost identical. Is there a way to implement this with only a single view CreateUpdateView or something like that or is this the standard way to implement CBGV's?
此外,在ThingyAdd中,我没有像在ThingyEdit中那样指定模型,但是它们都可以正常工作.我假设该模型是由form_class ThingyForm(是ModelForm)的元部分中定义的模型隐含/拾取的.这个假设正确吗?
Also, in ThingyAdd I haven't specified the model like I have in ThingyEdit, yet they both function fine. I'm making the assumption that the model is implied/picked-up by the model defined in the meta portion of the form_class, ThingyForm, which is a ModelForm. Is this assumption correct?
class ThingyAdd(AuthMixin, CreateView):
form_class = ThingyForm
context_object_name='object'
template_name='change_form.html'
success_url='/done/'
class ThingyEdit(AuthMixin, UpdateView):
model = Thingy
form_class = ThingyForm
context_object_name='object'
template_name='change_form.html'
success_url='/done/'
class ThingyDelete(AuthMixin, DeleteView):
model = Thingy
form_class = ThingyForm
context_object_name='object'
template_name='delete_confirmation.html'
success_url='/done/'
推荐答案
您可以创建另一个mixin
You could create another mixin
class ThingyMixin(object):
model=Thingy
form_class=ThingyForm
template_name='change_form.html'
context_object_name='object'
success_url='/done/'
然后在您的视图中:
class ThingyAdd( AuthMixin, ThingyMixin, CreateView ):
pass
class ThingyEdit( AuthMixin, ThingyMixin, UpdateView ):
pass
class ThingyDelete( AuthMixin, ThingyMixin, DeleteView ):
template_name='delete_confirmation.html'
这篇关于基于类的通用视图和DRY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!