Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin SelectMultiple Widget

In my model I have many to many relationship between 2 tables Users and Groups. In the admin interface I see the SelectMultiple widget for Groups. Actually, I am using filter_horizontal, I see the available groups and the selected groups in 2 separate lists. Is it possible to filter the list of available groups that I can see (based on some criteria). I do not want to show all the groups in the groups table. Thank you


1 Answers

In your form class, you can specify a custom queryset for the group-field, which then determines which Group-instances are available in the form:

class UserForm(forms.ModelForm):
    # override the default groups field
    groups = forms.ModelMultipleChoiceField(
        queryset=Groups.objects.filter(YOUR_CONDITIONS),
        widget=forms.SelectMultiple,
    )

    class Meta:
        model = User
like image 195
Guðmundur H Avatar answered Feb 03 '26 06:02

Guðmundur H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!