如何避免在ModelForm和CreateView类中重复字段列表? [英] How to avoid repeating field list in ModelForm and CreateView class?

查看:121
本文介绍了如何避免在ModelForm和CreateView类中重复字段列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 django.forms.ModelForm django.views.generic.CreateView 创建一个创作查看我的模型。



我发现我最终得到这个代码:



forms.py: / p>

  class ScenarioForm(forms.ModelForm):
class Meta:
model = Scenario
fields = ['scenario_name','description',
'scenario_file','preview']

views.py:

  class ScenarioUpload(generic.CreateView):
model = Scenario
fields = ['scenario_name','description',
'scenario_file','preview']
form_class = ScenarioForm

似乎真的很糟糕的重复。有没有什么我做错了,还是有些方法可以避免这种情况?

解决方案

Tony的回答有正确的想法,但是它实际上必须被编码的方式是使用新风格类,混合列表首先列在派生类中:

  class MetaScenario(object):
model = Scenario
fields = ['scenario_name','description',
'scenario_file','preview']

class ScenarioForm (forms.ModelForm):
Meta = MetaScenario

class ScenarioUpload(MetaScenario,generic.CreateView):
form_class = ScenarioForm
/ pre>

I'm using django.forms.ModelForm and django.views.generic.CreateView to create a creation view for my model.

I find that I end up with this code:

forms.py:

class ScenarioForm(forms.ModelForm):
    class Meta:
        model = Scenario
        fields = ['scenario_name', 'description',
                  'scenario_file', 'preview']     

views.py:

class ScenarioUpload(generic.CreateView):
    model = Scenario
    fields = ['scenario_name', 'description',
              'scenario_file', 'preview']     
    form_class = ScenarioForm

It seems like really bad repetition. Is there something I'm doing wrong, or some way I can avoid this?

解决方案

Tony's answer has the right idea, but the way it actually has to be coded is using "new style" classes, with the mixin listed first in the derived class:

class MetaScenario(object):   
    model = Scenario
    fields = ['scenario_name', 'description',
              'scenario_file', 'preview']

class ScenarioForm(forms.ModelForm):
    Meta = MetaScenario

class ScenarioUpload(MetaScenario, generic.CreateView):
    form_class = ScenarioForm

这篇关于如何避免在ModelForm和CreateView类中重复字段列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆