【问题标题】:Class Based Generic Views and DRY基于类的通用视图和 DRY
【发布时间】:2012-11-15 06:24:48
【问题描述】:

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

【问题讨论】:

    标签: django django-views


    【解决方案1】:

    你可以创建另一个 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'
    

    【讨论】:

    • 太好了,谢谢。我什至需要指定模型属性,还是由 form_class 上的模型隐含?
    • 您应该只需要在 DeleteView 上提供一个模型属性。
    猜你喜欢
    • 2011-10-04
    • 2012-02-21
    • 2012-12-14
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 2016-08-06
    • 2011-10-01
    相关资源
    最近更新 更多