How to avoid repeating field list in ModelForm and CreateView class?

ε祈祈猫儿з 提交于 2019-12-11 07:16:18

问题


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?


回答1:


You could create your own Meta class:

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

class ScenarioForm(forms.ModelForm):
    Meta = MetaScenario

class ScenarioUpload(generic.CreateView, MetaScenario):
    pass



回答2:


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


来源:https://stackoverflow.com/questions/27212387/how-to-avoid-repeating-field-list-in-modelform-and-createview-class

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