__init__ Form Django中的查询集

e4yzc0pl  于 2023-10-21  发布在  Go
关注(0)|答案(2)|浏览(109)
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__() missing 1 required positional argument:'queryset'。如何在__init__表单中使用Queryset

ddrv8njm

ddrv8njm1#

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

如果查询集是 dynamic(这里不是),可以初始设置为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查询)。

kadbb459

kadbb4592#

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

相关问题