为什么多重继承在Django视图中不起作用?

时间:2014-12-14 21:31:40

标签: django django-views

我试图避免在表单和(基于类)视图中重复字段列表和模型说明符。

This answer建议定义一个“元类”,其中包含字段列表,并在表单和视图中继承该类。

它适用于表单,但以下代码将列表和目标模型继承到视图中会导致此错误:

  

TemplateResponseMixin需要'template_name'的定义或'get_template_names()'的实现

我不知道这种变化是如何导致这种错误的。


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:

    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']     

1 个答案:

答案 0 :(得分:4)

不要混合新样式对象和旧样式对象,将类定义更改为

class ScenarioFormInfo(object)

将你的Mixin作为第一个

class ScenarioUpload(forms.ScenarioFormInfo, generic.CreateView):

阅读有关How does Python's super() work with multiple inheritance?

的问题