Add superuser management script

This commit is contained in:
Chris Nagy
2021-03-14 19:43:22 +01:00
parent e4909c3133
commit e3ba968fef
3 changed files with 45 additions and 1 deletions

View File

@@ -0,0 +1,30 @@
import os
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = """
Creates a Django superuser based on env variables.
""".replace(" ", "")
def handle(self, *args, **options):
# Get user details from env variables
PAPERLESS_ADMIN_USER=os.getenv('PAPERLESS_ADMIN_USER')
PAPERLESS_ADMIN_MAIL=os.getenv('PAPERLESS_ADMIN_MAIL', 'root@localhost')
PAPERLESS_ADMIN_PASSWORD=os.getenv('PAPERLESS_ADMIN_PASSWORD')
# If PAPERLESS_ADMIN_USER env variable is set
if PAPERLESS_ADMIN_USER:
try:
# Check if user exists already, leave as is if it does
if User.objects.filter(username=PAPERLESS_ADMIN_USER).exists():
self.stdout.write(f'The user "{PAPERLESS_ADMIN_USER}" already exists! Leaving user as is.')
elif PAPERLESS_ADMIN_PASSWORD:
# Create superuser based on env variables
User.objects.create_superuser(PAPERLESS_ADMIN_USER, PAPERLESS_ADMIN_MAIL, PAPERLESS_ADMIN_PASSWORD)
self.stdout.write(f'Created superuser "{PAPERLESS_ADMIN_USER}" with provided password.')
except Exception as error:
self.stdout.write(f'Exception occured while managing superuser: {error}')