Class Based Generic Views and DRY

折月煮酒 提交于 2021-01-23 00:33:33

问题


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?

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/'

回答1:


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/'

Then in your views:

class ThingyAdd( AuthMixin, ThingyMixin, CreateView ):
  pass

class ThingyEdit( AuthMixin, ThingyMixin, UpdateView ):
  pass

class ThingyDelete( AuthMixin, ThingyMixin, DeleteView ):
  template_name='delete_confirmation.html'


来源:https://stackoverflow.com/questions/13587506/class-based-generic-views-and-dry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!