#Help Creating Superuser From Migrations

7 messages · Page 1 of 1 (latest)

leaden bear
#

How to automate makemigrations and create a superuser without typing email and password each time?

I'm working on a Django project and wondering how to streamline the development setup a bit.

Right now, every time I run makemigrations and then want to create a superuser, I have to manually type the email and password. I'd like to automate this, ideally by:

Running makemigrations and migrate as part of setup.

Creating a superuser automatically, without interactive prompts (e.g., by providing the email and password in advance).

Here’s the situation:

I have an apps folder with my accounts app inside it: apps/accounts.

In apps/accounts/apps.py, I set the app config like this:

class AccountsConfig(AppConfig):
    name = "apps.accounts"

In a migration (0001_superuser.py), I’m trying to automatically create a superuser using values from environment variables:

from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import migrations

def generate_superuser():
    email = settings.DJANGO_SUPERUSER_EMAIL
    password = settings.DJANGO_SUPERUSER_PASSWORD

    user = get_user_model().objects.create_superuser(
        email=email,
        password=password,
        is_staff=True,
        is_superuser=True
    )
    user.save()

class Migration(migrations.Migration):

    initial = False

    dependencies = [
        ("apps.accounts", "0001_initial"),
    ]

    operations = [
        migrations.RunPython(generate_superuser),
    ]

But when I run python manage.py makemigrations, I get:

django.db.migrations.exceptions.NodeNotFoundError:
Migration accounts.0001_superuser dependencies reference nonexistent parent node ('apps.accounts', '0001_initial')
elfin tartan
#

The migration is failing because apps/accounts/0001_initial.py does not exist.

#

Creating that migration should fix it. However, I recommend using a management command instead of a data migration.

leaden bear
leaden bear
#

thank you for the response tho ❤️

flint nova