Skip to content

Instantly share code, notes, and snippets.

@inirudebwoy
Created March 13, 2015 12:18
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save inirudebwoy/7eb2d74ea950c38559e5 to your computer and use it in GitHub Desktop.
Save inirudebwoy/7eb2d74ea950c38559e5 to your computer and use it in GitHub Desktop.
Django 1.7+ migration for creating superuser
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.admin import User
def create_superuser(apps, schema_editor):
superuser = User()
superuser.is_active = True
superuser.is_superuser = True
superuser.is_staff = True
superuser.username = 'admin'
superuser.email = 'admin@admin.net'
superuser.set_password('admin')
superuser.save()
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.RunPython(create_superuser)
]
@danken00
Copy link

danken00 commented Aug 6, 2017

Thanks for this, really helpful :)

@riacookie
Copy link

Thanks, this is really help me out

@PiotrWegrzyn
Copy link

thanks

@Nastaliss
Copy link

Adding this :

dependencies = [
        ('auth', '0001_initial')
    ]

in the migrations allowed me to execute this migration on database creation with the base django user model.

I also had to add this line:
superuser.last_login = datetime.datetime.now()
to prevent a non-NULL constraint in that case.

@richardARPANET
Copy link

improved version:

import os

from django.db import migrations
from django.utils import timezone
from django.contrib.auth import get_user_model


def create_superuser(apps, schema_editor):
    superuser = get_user_model()(
        is_active=True,
        is_superuser=True,
        is_staff=True,
        username=os.environ['ADMIN_USERNAME'],
        email=os.environ['ADMIN_EMAIL'],
        last_login=timezone.now(),
    )
    superuser.set_password(os.environ['ADMIN_PASSWORD'])
    superuser.save()


class Migration(migrations.Migration):

    dependencies = []

    operations = [migrations.RunPython(create_superuser)]

@virginia-garcia
Copy link

Hello, can you help me? I added this file but I don't know how to use it to create the super user, help ahaha

@richardARPANET
Copy link

@virginia-garcia you need to add the file to your Django migrations/ folder and run python manage.py migrate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment