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 :
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)