from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password from django.contrib.auth.models import Permission from django.core.management.base import BaseCommand, CommandError User = get_user_model() class Command(BaseCommand): help = "Creates an administrator role with the specified credentials" def add_arguments(self, parser): # Credentials parser.add_argument("base_username", type=str, help="Username") parser.add_argument("password", type=str, help="Password") parser.add_argument("full_name", nargs="?", type=str, help="Full name") parser.add_argument( "--superuser", action="store_true", help="Create a superuser account" ) def handle(self, *args, **kwargs): base_username = kwargs["base_username"] password = kwargs["password"] user, created = User.objects.get_or_create(username=f"pwd__{base_username}") if not created: raise CommandError("Un utilisateur avec ce nom existe déjà") user.is_staff = True user.password = make_password(password) if kwargs["full_name"]: user.full_name = kwargs["full_name"] if kwargs["superuser"]: user.is_superuser = True user.save() Permission.objects.get(codename="election_admin").user_set.add(user) Permission.objects.get(codename="faq_admin").user_set.add(user)