Reputation: 14685
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?
Upvotes: 1
Views: 193
Reputation: 14685
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
Upvotes: 1
Reputation: 2629
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
Upvotes: 3