Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To achieve this, you need to customize the form used in the admin page for creating instances of the Category model. You can override the formfield_for_manytomany method of the ModelAdmin class to filter the queryset of the users field to only include superusers. Here’s how you can do it:

# admin.py

from django.contrib import admin
from .models import Category
from django.contrib.auth.models import User

class CategoryAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "users":
            kwargs["queryset"] = User.objects.filter(is_superuser=True)
        return super().formfield_for_manytomany(db_field, request, **kwargs)

admin.site.register(Category, CategoryAdmin)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading