Search code examples
djangomany-to-manyadmin

How to only display superusers in ManyToManyField field when creating an instance in admin page


We have this model:

# models.py

from django.conf import settings
User = settings.AUTH_USER_MODEL

class Category(models.Model):
    ...
    users = models.ManyToManyField(User, help_text='Choose Superusers only', blank=True)  

The questions is:
when creating an instance in the admin page, how can I force the form to only display superusers in the multiple select?


Solution

  • Given the helptext says you want to select super users only, you probably want to filter on all ModelForms, so the ones in the ModelAdmin, but also in (perhaps) future ModelForms.

    An easy way to do this is with the limit_choices_to=… parameter [Django-doc]. This will then filter the QuerySet it offers to the form for that field, and also do the proper validation:

    from django.conf import settings
    
    
    class Category(models.Model):
        # …
        users = models.ManyToManyField(
            settings.AUTH_USER_MODEL,
            help_text='Choose Superusers only',
            blank=True,
            limit_choices_to={'is_superuser': True},
        )

    This thus will automatically work on a ModelAdmin, since it uses a ModelForm behind the curtains, but also on all "vanilla" Django ModelForms and likely most Django packages, plugins, etc.