4

我在 Django 1.3 中实现基于类的视图,我发现自己在这种情况下,我的 CreateView、UpdateView 和 DeleteView 几乎相同。有没有办法只用一个视图 CreateUpdateView 或类似的东西来实现它,或者这是实现 CBGV 的标准方法?

此外,在 ThingyAdd 中,我没有像在 ThingyEdit 中那样指定模型,但它们都运行良好。我假设模型是由 form_class 的元部分中定义的模型隐含/拾取的,ThingyForm 是一个 ModelForm。这个假设正确吗?

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

1 回答 1

3

你可以创建另一个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'
于 2012-11-27T15:58:09.967 回答