Solved: django how to create superuser if does not exists on migration

If a superuser does not exist on the migration, Django will create one.


I have a migration that creates a superuser if it does not exist. 
<code>def create_superuser(apps, schema_editor):
    User = apps.get_model('auth', 'User')

    if not User.objects.filter(username='admin').exists():
        User.objects.create_superuser('admin', 'admin@example.com', 'password')


class Migration(migrations.Migration):

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

    operations = [
        migrations.RunPython(create_superuser),
    ] 
</code>

The first line creates a function that will create a superuser if one does not already exist.
The second line gets the User model from the ‘auth’ app.
The third line checks to see if a user with the username ‘admin’ exists. If not,
the fourth line creates a superuser with the username ‘admin’, email address ‘admin@example.com’, and password ‘password’.
The fifth and sixth lines create a migration class and specify that it depends on the migration ‘0001_initial’ in the app ‘myapp’.
The seventh line specifies that the migration should run the function ‘create_superuser’.

What is a Superuser

A superuser is a user with administrative privileges on a Django site. They can do things like create and manage models, views, and applications.

Related posts:

Leave a Comment