[Answer]-How to limit the number of users in a group in Django-Admin

1👍

this code should be what you need:

change the group name (‘LIMITED’ in the example and the value LIMIT for your needs.

Anyway this code does not guarantee 100% what you are looking for, as 2 different processes that run simultaneously can by-pass this check (both read group.user_set.count() < LIMIT and allow the operation)

there is no out of the box solution to prevent this in django

from django.contrib.auth.admin import UserAdmin as _UserAdmin, User
from django.contrib.auth.forms import UserChangeForm as _UserChangeForm

class UserChangeForm(_UserChangeForm):
    def clean_groups(self):
        groups = self.cleaned_data.get('groups', [])
        for group in groups:
            if group.name == 'LIMITED' and group.user_set.count() == LIMIT: 
                raise ValidationError('Group %s does not accept more users' % group.name)
        return self.cleaned_data.get('groups')

class UserAdmin(_UserAdmin):
    form = UserChangeForm

admin.site.unregister(User)
admin.site.register(User, UserAdmin)
👤sax

Leave a comment