Add a management command to create an admin

This commit is contained in:
Tom Hubrecht 2022-01-11 15:08:27 +01:00
parent f9271f5690
commit 932a20fd17
3 changed files with 35 additions and 0 deletions

View file

View file

View file

@ -0,0 +1,35 @@
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")
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)
user.full_name = kwargs["full_name"] or ""
user.save()
Permission.objects.get(codename="election_admin").user_set.add(user)
Permission.objects.get(codename="faq_admin").user_set.add(user)