__init__中的Queryset形式Django

时间:2017-12-19 10:27:47

标签: python django forms

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

我有错误:TypeError:__init__()缺少1个必需的位置参数:'queryset'。如何在Queryset表单中使用__init__

2 个答案:

答案 0 :(得分:3)

除非您目前隐藏某些信息,否则最好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)

如果查询集是动态(这不是这种情况),您可以将其初始设置为None ,然后在__init__功能:

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

但是,如果例如queryset依赖于传递给表单的参数,或者它依赖于其他表(并且它不能优雅地写入SQL查询),则通常会出现这种情况。

答案 1 :(得分:0)

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