GreenAsJade
GreenAsJade

Reputation: 14685

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

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

Answers (2)

GreenAsJade
GreenAsJade

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

mimo
mimo

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

Related Questions