1

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?

GreenAsJade
  • 14,459
  • 11
  • 63
  • 98
  • One ways is defined a class outside say `class OMeta` with class attributes `model` and `fields`. Then (1) defined `class ScenarioForm(forms.ModelForm): class Meta = OMeta` and (2) `class ScenarioUpload(generic.CreateView, OMeta):` – Grijesh Chauhan Nov 30 '14 at 10:58

2 Answers2

3

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
mimo
  • 2,469
  • 2
  • 28
  • 49
  • Waw.. Great minds think alike! Lol -- I suggested same trick in comment. – Grijesh Chauhan Nov 30 '14 at 10:59
  • But ... I went to implement it and it doesn't work :( Unfortunately, replacing the contents of the `ScenarioUpload` class with the Meta class parent results in "TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'". I don't see how anything even "knows" about the difference! – GreenAsJade Dec 10 '14 at 09:52
1

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
GreenAsJade
  • 14,459
  • 11
  • 63
  • 98