I want to be able to set some default selected users on the right side of a Django Admin FilteredSelectMultiple widget.
This is my model:
class UserAdminForm(forms.ModelForm):
users = forms.ModelMultipleChoiceField(
queryset=User.objects.all(),
widget=FilteredSelectMultiple("Users",
is_stacked=False))
class Meta:
model = User
exclude = ()
Is there a way to do this with JavaScript so that I don't have to hand-select these defaults each time I create a new item?
You can specify the initial data by setting the initial=…
parameter [Django-doc] with:
class UserAdminForm(forms.ModelForm):
users = forms.ModelMultipleChoiceField(
queryset=User.objects.all(),
initial=User.objects.filter(username__in=['johnsmith', 'janedoe']),
widget=FilteredSelectMultiple('Users', is_stacked=False)
)
class Meta:
model = User
fields = '__all__'
Here we thus set as initial selected users johnsmith
and janedoe
. You can of course pick other users.