为什么在Django视图中不能继承多重继承? [英] Why doesn't multiple inheritance work in Django views?
问题描述
我试图避免在表单和(基于类)视图中重复字段和模型说明符列表。
I am trying to avoid repeating the list of fields and model specifier in both a form and a (class based) view.
这个答案建议定义一个元类,其中包含字段列表,并在表单和视图中继承该类。
This answer suggested defining a "meta class" that has the field list in it, and inheriting that class in both the form and the view.
表单正常工作,但以下代码将列表和目标模型继承到视图中会导致此错误:
It works fine for the form, but the following code inheriting the list and target model into the view results in this error:
TemplateResponseMixin需要定义template_name或get_template_names()的实现
TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'
I不幸的是看到这个变化是如何导致这个错误的。
I'm at a loss to see how this change causes that error.
forms.py:
class ScenarioFormInfo:
model = Scenario
fields = ['scenario_name', 'description', 'game_type',
'scenario_size', 'weather', 'battle_type', 'attacker',
'suitable_for_axis_vs_AI', 'suitable_for_allies_vs_AI',
'playtested_H2H', 'suitable_for_H2H',
'scenario_file', 'preview']
class ScenarioForm(forms.ModelForm):
Meta = ScenarioFormInfo
views.py: / p>
views.py:
class ScenarioUpload(generic.CreateView, forms.ScenarioFormInfo):
form_class = ScenarioForm
# model = Scenario
# fields = ['scenario_name', 'description', 'game_type',
# 'scenario_size', 'weather', 'battle_type', 'attacker',
# 'suitable_for_axis_vs_AI', 'suitable_for_allies_vs_AI',
# 'suitable_for_H2H', 'playtested_H2H',
# 'scenario_file', 'preview']
推荐答案
不要混用新样式对象和旧样式对象,将类定义更改为
do not mix new style object and old style object, change your class definitions as
class ScenarioFormInfo(object)
将您的Mixin作为第一个
put your Mixin as first
class ScenarioUpload(forms.ScenarioFormInfo, generic.CreateView):
这篇关于为什么在Django视图中不能继承多重继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!