I have a model form, where I want to filter the choices in the forms.Select widget:
class ControlMemberGroupLineForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queryset = Group.objects.filter(is_inactive=False)
class Meta:
model = Member_Group
fields = (
'group',
'member',
)
error_messages = {
'group': {
'required': 'Please add at least one Group to this member'
}
}
widgets = {
'group': forms.Select(),
#'group': forms.Select(choices=[('yes', 'y'),('no','n')]),
}
Overriding the __init__
in this way seems to achieve nothing, I get the full set of (distinct) objects from Group
. Changing the widgets
attributes to comment out the first line and uncomment the second (with the choices
) also makes no difference (ie I don’t get a choice of ‘yes’/‘no’).
I found a way that does change the choices, removing group
from the various sections of the Meta
class and then adding it in as a directly entered field (non-model?).
group = forms.ModelChoiceField(queryset=Group.objects.filter(is_inactive=False), widget=forms.Select())
In this case I get the select choices I expect, but the option selected
in the select are not populated (just defaults to first in the list), and generally seems to mess up the view with various errors when the form is posted – group
is a many to many choice, so there is a fairly complicated view dealing with formsets.
Is there a way to populate the select widget with the filtered Group
records, while defining the widget in the Meta
?
Thanks