forms.ModelChoiceField
的構造函數需要一個查詢集。在請求發生之前,我不知道該查詢集。蒸餾水:如何在forms.Form子類上動態設置models.ModelChoiceField的查詢集
# models.py
class Bar(models.model):
text = models.TextField()
class Foo(models.Model):
name = models.CharField()
bar = models.ForeignKey(Bar)
# forms.py
class FooForm(forms.Form):
name = forms.CharField()
text = forms.CharField(widget=forms.TextArea)
bar = forms.ModelChoiceField(queryset='??????')
什麼我目前做的:
# forms.py
def get_foo_form_class(bars_queryset):
class FooForm(forms.Form):
name = forms.CharField()
text = forms.CharField(widget=forms.TextArea)
bar = forms.ModelChoiceField(queryset=bars_queryset)
return FooForm
然後我就可以使用解析出該URL的參數與URL配置來構造查詢集和獲取類調用它的觀點。這感覺就像是錯誤的做法。有沒有一種在Django中做到這一點的既定方法?