I need to disable adding new users in the admin panel once the number of users exceeds a particular value. The code below works to remove the "add user" button when I test it with hard coded integers. However, this line does not appear to be returning the count of users without hard coding a count: usercount = CustomUser.objects.count()
Any ideas for getting the count of users already added?
models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import Group
from django.contrib import admin
from django.db.models import Count
from django.db.models.signals import post_save
class CustomUser(AbstractUser):
full_name = models.CharField(max_length=250, null=True)
age = models.PositiveIntegerField(null=True, blank=True)
employee_type = models.ForeignKey(Group, null=True, on_delete=models.SET_NULL, default=1)
is_active = models.BooleanField(null=False, default=True)
# disable add new user in the admin panel
class RemoveAddNew(admin.ModelAdmin):
usercount = CustomUser.objects.count()
if usercount > 5:
def has_add_permission(self, request, obj=None):
return False
admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser, RemoveAddNew
class CustomUserAdmin(RemoveAddNew, UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['username', 'email', 'full_name', 'age', 'is_staff', 'is_active']
fieldsets = UserAdmin.fieldsets (
(None, {'fields': ('full_name', 'age', )}),
)
add_fieldsets = UserAdmin.add_fieldsets (
(None, {'fields': ('email','full_name', 'age', 'employee_type', 'is_active')}),
)
admin.site.register(CustomUser,CustomUserAdmin)
CodePudding user response:
I think you over code it. My solution is simpler and shorter:
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['username', 'email', 'full_name', 'age', 'is_staff', 'is_active']
fieldsets = UserAdmin.fieldsets (
(None, {'fields': ('full_name', 'age', )}),
)
add_fieldsets = UserAdmin.add_fieldsets (
(None, {'fields': ('email','full_name', 'age', 'employee_type', 'is_active')}),
)
def has_add_permission(self, request):
return CustomUser.objects.count() < 6
admin.site.register(CustomUser,CustomUserAdmin)