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

后端 未结 2 1495
离开以前
离开以前 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 18:56

    You can also do it in your view before you present the form in the template. I use this and find it more flexible incase you re-use the form in other views and need to change the queryset each time:

    from assets.models import Asset
    location_id = '123456'
    edit_form = AsssetSelectForm(request.POST or None, instance=selected_asset)
    edit_form.fields["asset"].queryset = Asset.objects.filter(location_id=location_id)
    

    I also set the default queryset to none in the forms.py:

    class AsssetSelectForm(forms.Form):
        asset = forms.ModelChoiceField(queryset=Asset.objects.none())
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题