Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Queryset in __init__ Form Django

class PaymentSelectForm(forms.Form):   
    date_from = forms.DateField()
    date_to = forms.DateField()
    website = ModelChoiceField() 
    paymentmethod = forms.ChoiceField(choices=PAYCODE_CHOICES)

    def __init__(self, *args, **kwargs):
        super(PaymentSelectForm, self).__init__(*args, **kwargs)
        applyClassConfig2FormControl(self) 
        self.fields['website'].queryset=Website.objects.all()

I have errors: TypeError: __init__() missing 1 required positional argument: 'queryset'. How can I use Queryset in __init__ Form?

like image 543
tnductam Avatar asked Dec 19 '17 10:12

tnductam


2 Answers

Unless there is some information you are currently hiding, you better declare the queryset in the declaration of the ModelChoiceField:

class PaymentSelectForm(forms.Form):

    date_from = forms.DateField()
    date_to = forms.DateField()
    website = ModelChoiceField(queryset=Website.objects.all()) 
    paymentmethod = forms.ChoiceField(choices=PAYCODE_CHOICES)

    def __init__(self, *args, **kwargs):
        super(PaymentSelectForm, self).__init__(*args, **kwargs)
        applyClassConfig2FormControl(self)

In case the queryset is dynamic (this is not the case here), you can set it to None initially, and then overwrite it in the __init__ function:

class PaymentSelectForm(forms.Form):

    date_from = forms.DateField()
    date_to = forms.DateField()
    website = ModelChoiceField(queryset=None) 
    paymentmethod = forms.ChoiceField(choices=PAYCODE_CHOICES)

    def __init__(self, *args, **kwargs):
        super(PaymentSelectForm, self).__init__(*args, **kwargs)
        applyClassConfig2FormControl(self)
        self.fields['website'].queryset=Website.objects.all()

But this is usually the case if for instance the queryset depends on parameters that are passed to the form, or it depends on other tables (and it can not be written into an SQL query elegantly).

like image 64
Willem Van Onsem Avatar answered Sep 28 '22 00:09

Willem Van Onsem


Use widget.choices

def __init__(self, *args, **kwargs):
        super(PaymentSelectForm, self).__init__(*args, **kwargs)
        applyClassConfig2FormControl(self) 
        self.fields['website'].widget.choices=(
            (choice.pk, choice) for choice in Website.objects.all()
        )
like image 28
tnductam Avatar answered Sep 28 '22 00:09

tnductam