我使用django.forms.ModelForm
和django.views.generic.CreateView
为我的模型创建了一个创建视图。
我发现我最终得到了这段代码:
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
这似乎是非常糟糕的重复。有什么我做错了,或者某种方式我可以避免这种情况?
答案 0 :(得分:3)
您可以创建自己的Meta类:
class MetaScenario:
model = Scenario
fields = ['scenario_name', 'description',
'scenario_file', 'preview']
class ScenarioForm(forms.ModelForm):
Meta = MetaScenario
class ScenarioUpload(generic.CreateView, MetaScenario):
pass
答案 1 :(得分:1)
Tony的答案有正确的想法,但它实际上必须编码的方式是使用" new style"类,在派生类中首先列出的mixin:
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