tnductam
tnductam

Reputation: 417

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?

Upvotes: 6

Views: 4495

Answers (2)

tnductam
tnductam

Reputation: 417

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()
        )

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

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).

Upvotes: 11

Related Questions