繁体   English   中英

__init__中的Queryset形式Django

[英]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()

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM