scoopseven
scoopseven

Reputation: 1777

Class Based Generic Views and DRY

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

Upvotes: 4

Views: 490

Answers (1)

czarchaic
czarchaic

Reputation: 6338

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'

Upvotes: 3

Related Questions