Django ModelChoiceField: filtering query set and setting default value as an object

Override the init method and accept a new keyword argument

class AccountDetailsForm(forms.Form):
    ...
    adminuser = forms.ModelChoiceField(queryset=User.objects.all())
    def __init__(self, *args, **kwargs):
        accountid = kwargs.pop('accountid', None)
        super(AccountDetailsForm, self).__init__(*args, **kwargs)

        if accountid:
            self.fields['adminuser'].queryset = User.objects.filter(account=accountid)

form = AccountDetailsForm(accountid=3)

You can always just set the choices manually in the view as well.

form = AccountDetailsForm()
form.fields['adminuser'].queryset = User.objects.filter(account=accountid)

Be warned: you are not setting default values by passing in a dictionary to a form like in your example.

You are actually creating a Bound Form, potentially triggering validation and all that jazz.

To set defaults, use the initials argument.

form = AccountDetailsForm(initial={'adminuser':'3'})

Leave a Comment