gpt4 book ai didi

python - __init__ 形式 Django 中的查询集

转载 作者:太空宇宙 更新时间:2023-11-03 14:02:16 25 4
gpt4 key购买 nike

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

最佳答案

除非您当前隐藏了某些信息,否则您最好ModelChoiceField 的声明中声明查询集:

class PaymentSelectForm(forms.Form):

date_from = forms.DateField()
date_to = forms.DateField()
website = ModelChoiceField(<b>queryset=Website.objects.all()</b>)
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=<b>None</b>)
paymentmethod = forms.ChoiceField(choices=PAYCODE_CHOICES)

def __init__(self, *args, **kwargs):
super(PaymentSelectForm, self).__init__(*args, **kwargs)
applyClassConfig2FormControl(self)
<b>self.fields['website'].queryset=Website.objects.all()</b>

但这通常是这种情况,例如 queryset 取决于传递给表单的参数,或者它取决于其他表(并且不能优雅地写入 SQL 查询) .

关于python - __init__ 形式 Django 中的查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47884882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com