production-taskbar / backend / config / management / commands / initadmin.py
initadmin.py
Raw
# type: ignore
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User


class Command(BaseCommand):
    help = f'Initialize default superuser admin'

    def handle(self, *args, **options):
        username = 'admin'
        password = 'admin'    #NOSONAR
        try:
            admin = User.objects.filter(username=username).first()
            if not admin:
                admin = User.objects.create_superuser(email='',
                                                      username=username,
                                                      password=password)

                admin.is_active = True
                admin.save()
                self.stdout.write(
                    self.style.SUCCESS(
                        f'initadmin => superuser {username} with password {password} created.'
                    ))
            else:
                self.stdout.write(
                    self.style.WARNING(
                        f'initadmin => {username} already exists (superuser: {admin.is_superuser}, active: {admin.is_active})'
                    ))
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(
                    f'initadmin => error on creating superuser {username}: {e}'
                ))