Reputation: 1797
In my django project, I want that there will be only one super user and no more super users can be create by python manage.py createsuperuser
Is it possible? If possible how?
Upvotes: 2
Views: 3021
Reputation: 298
You can write a script to check number of superuser. Suppose you want 10 superusers then every time a superuser is created count if its more than 10 or not and give error/success message accordingly.
You can count superusers as follows:
from django.contrib.auth.models import User
from django.http import HttpResponse
user_obj = User.objects.all()
c = 0
for i in user_obj:
if i.is_superuser():
c += 1
if c > 10:
return HttpResponse('Cannot add anymore superusers')
else:
new_user = User.objects.create_user(username = name, password = password)
of course you will have to make a form to accept username and password but I have given the basic idea.
You can also use python's threading
library to make things async
Upvotes: 1
Reputation: 34992
Any person able to run python manage.py createsuperuser
should be able to run python manage.py dbshell
and create the super user manually in the database. So, this should be a trusted person anyway.
If only trusted persons can add superusers, then just tell them not to create multiple superusers (though I wonder what is the purpose of limiting to only one superuser).
However, if you want to prevent from creating more than one superuser by mistake with python manage.py createsuperuser
, you can override this command:
from django.contrib.auth.management.commands import createsuperuser
from django.core.management.base import CommandError
class Command(createsuperuser.Command):
def handle(self, *args, **options):
if self.UserModel.objects.filter(is_superuser=True).exists():
raise CommandError("There is no room for two, go your way!")
super().handle(*args, **options)
Note that this won't prevent from setting a user as being a superuser from django admin interface.
If you want to completely make it impossible to create two superusers, you can add the constraint on the database level directly.
Another way to do it would be to subclass django.contrib.auth.models.User
and define:
SUPERUSER_ID = 1 # or whatever
@property
def is_superuser(self):
return self.id == self.SUPERUSER_ID
Upvotes: 1