How to dynamically set the queryset of a models.ModelChoiceField on a forms.Form subclass

后端 未结 2 1494
离开以前
离开以前 2020-12-13 18:16

The constructor for forms.ModelChoiceField requires a queryset. I do not know the queryset until the request happens. Distilled:

# models.py
cla         


        
2条回答
  •  既然无缘
    2020-12-13 19:01

    Override the form's __init__ method and set the queryset there.

    class FooForm(forms.Form):
        bar = forms.ModelChoiceField(queryset=Bar.objects.none())
    
        def __init__(self, *args, **kwargs):
            qs = kwargs.pop('bars')
            super(FooForm, self).__init__(*args, **kwargs)
            self.fields['bar'].queryset = qs
    

提交回复
热议问题