[Django]-How to dynamically set the queryset of a models.ModelChoiceField on a forms.Form subclass

77👍

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

17👍

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())
👤radtek

Leave a comment