pythondjangoformsdjango-formsdjango-queryset

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?


Solution

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