简体   繁体   中英

Django CreateView - How do I call form class __init__?

I have a django create view and I want to call the __init__ of the form class and I don't know how to do that.

class PersonCreateView(CreateView):
    model = Person
    form_class = PersonForm

In the form class I made some logic to redefine the queryset of some combos. My problem is that I don't know how to call the __init__ method, or any other method, of the PersonForm

Thanks in advance for any help.

You shouldn't call it yourself. You can override get_form_kwargs to provide extra arguments to pass to the form instantiation.

class PersonCreateView(CreateView):
    model = Person
    form_class = PersonForm

    def get_form_kwargs(self, *args, **kwargs):
        form_kwargs = super(PersonCreateView, self).get_form_kwargs(*args, **kwargs)
        form_kwargs['my_extra_queryset_param'] = get_my_extra_queryset()
        return form_kwargs

The init method is actually called automatically by the class when a new instance of the object is instantiated.

Consider the following example:

class House():
    __init__(self,x,y):
        self.x = x
        self.y = y
        self.z = x*y

To call init , we just do the following:

h = House(5,7)

This will create the object and automatically invoke the init function. It works the same way for django views.

I see Daniel beat me to an answer, perhaps his is more what you're looking for. Anyways, hope this helps a little at least!

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