简体   繁体   中英

Django FormView inheritance

I am new in python and django, please can someone explain me inheritance mechanizm in django/python class based views? 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:

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++? Thank you very much.

Because you are calling super() in FormViewB , which means the form_valid method of FormViewA . If you don't want to see 'in FormViewA' you should either

  1. Don't call super() at all: In this case, you must be sure that super does not include any crucial code you will require. Because when you skip calling FormViewA.super() you are not calling FormView.super() either.

  2. Inherit directly from FormView . If you have common code in both FormViewA and FormViewB , you can extract this code to another method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM