JoeFrank
JoeFrank

Reputation: 71

Django Admin restrict users to be added to more than one group

I am creating a customised Django Admin and I want to restrict users to be associated to no more than one group. I am using Django 4.1 and Python 3.11

admin.py:

from django.contrib import admin
from typing import Set

from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from django.utils.translation import gettext_lazy as _

from .models import User


@admin.register(User)
class UserAdmin(DjangoUserAdmin):
    ordering = ('is_staff', 'is_active', 'email', 'organisation')
    list_display = ('email', 'name', 'organisation', 'is_staff', 'is_active', 'is_superuser', 'date_joined')
    fieldsets = (
        ("Personal info", {'fields': ('name', 'email', 'password', 'organisation')}),
        ("Permissions", {'fields': (
            # 'is_active',
            # 'is_staff',
            # 'is_superuser',
            'groups',
            # 'user_permissions'
            )}))

    add_fieldsets = (
        (None, {'classes': ('wide',), 'fields': ('name', 'email', 'password1', 'password2', 'organisation')}),
    )

Is there a way to change this in the admin code?

Or it is possible to disable the group widget ("Choose all") on the page? if so which html page is used for groups?

Upvotes: 1

Views: 150

Answers (1)

Sunderam Dubey
Sunderam Dubey

Reputation: 8837

Yes, it is possible to restrict the number of groups a user can be associated with in Django. One way to do this is to override the save_model() method in your custom UserAdmin class and perform the check there, so:

@admin.register(User)
class UserAdmin(DjangoUserAdmin):
    # ... other stuff
    # ... other stuff

    def save_model(self, request, obj, form, change):
        if obj.groups.count() > 1:
            self.message_user(request, _('Users can only be associated with one group.'), level=messages.ERROR)
        else:
            super().save_model(request, obj, form, change)

Upvotes: 1

Related Questions