问题
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