Created
June 14, 2016 08:21
-
-
Save doismellburning/44346c5a47815775204c482ed6ab9a13 to your computer and use it in GitHub Desktop.
Non-interactively create/set a Django superuser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django.core.management.base import BaseCommand, CommandError | |
from django.contrib.auth import get_user_model | |
from django.conf import settings | |
from django.db import transaction | |
class Command(BaseCommand): | |
help = ( | |
'Create a django.contrib.auth superuser noninteractively. ' | |
'This allows easy creation at deployment-time with EB. ' | |
'Environment variables: SUPERUSER_USERNAME, ' | |
'SUPERUSER_EMAIL and SUPERUSER_PASSWORD must be set.' | |
) | |
def handle(self, *args, **options): | |
if None in (settings.SUPERUSER_USERNAME, | |
settings.SUPERUSER_EMAIL, | |
settings.SUPERUSER_PASSWORD): | |
raise CommandError( | |
'One of required environment variables is not set ' | |
'(SUPERUSER_USERNAME, SUPERUSER_EMAIL, SUPERUSER_PASSWORD)') | |
user_model = get_user_model() | |
with transaction.atomic(): | |
try: | |
user = user_model.objects.select_for_update().get( | |
username=settings.SUPERUSER_USERNAME) | |
user.set_password(settings.SUPERUSER_PASSWORD) | |
user.email = settings.SUPERUSER_EMAIL | |
user.save() | |
except user_model.DoesNotExist: | |
user = user_model.objects.create_superuser( | |
settings.SUPERUSER_USERNAME, | |
settings.SUPERUSER_EMAIL, | |
settings.SUPERUSER_PASSWORD, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment