[英]Django FormView inheritance
I am new in python and django, please can someone explain me inheritance mechanizm in django/python class based views? 我是python和django的新手,有人可以在基于django / python类的视图中向我解释继承机制吗? Example is here:
示例在这里:
class FormViewA(FormView):
form_class = MyFormClass
template_name = 'mytemplate.html'
def get_success_url(self):
return reverse('my_url')
def form_valid(self, form):
form.save()
print "in FormViewA"
return super(FormViewA, self).form_valid(form)
class FormViewB(FormViewA):
def form_valid(self, form):
form.save()
print "in FormViewB"
return super(FormViewB, self).form_valid(form)
If I use FormViewB
to create a form in my templates the code from form_valid
from FormViewA
still run and I see this output: 如果我使用
FormViewB
在模板中创建表单,则FormViewA
form_valid
的代码仍将运行,并且会看到以下输出:
in FormViewB
in FormViewA
Explain me please, what am I missing, why the code from overridden method still works here? 请向我解释,我想念什么,为什么覆盖方法中的代码在这里仍然有效? Is it overridden like in the c++?
是否像c ++中那样被覆盖? Thank you very much.
非常感谢你。
Because you are calling super()
in FormViewB
, which means the form_valid
method of FormViewA
. 因为你调用
super()
在FormViewB
,这意味着form_valid
的方法FormViewA
。 If you don't want to see 'in FormViewA'
you should either 如果您不想在
'in FormViewA'
看到,则应该
Don't call super()
at all: In this case, you must be sure that super does not include any crucial code you will require. 根本不要调用
super()
:在这种情况下,您必须确保super不包含所需的任何关键代码。 Because when you skip calling FormViewA.super()
you are not calling FormView.super()
either. 因为当您跳过调用
FormViewA.super()
您也不会调用FormView.super()
。
Inherit directly from FormView
. 直接从
FormView
继承。 If you have common code in both FormViewA
and FormViewB
, you can extract this code to another method. 如果
FormViewA
和FormViewB
都有通用代码,则可以将此代码提取到另一个方法中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.