django how to create superuser if does not exists on migration

  1. Open the models.py file in your Django app.

  2. Import the necessary modules:

from django.contrib.auth.models import User
from django.db.models.signals import post_migrate
from django.dispatch import receiver
  1. Create a function to check for the existence of the superuser:
def create_superuser(sender, kwargs):
    if not User.objects.filter(is_superuser=True).exists():
        User.objects.create_superuser('admin', '[email protected]', 'admin_password')
  1. Use the @receiver decorator to connect the function to the post_migrate signal:
@receiver(post_migrate)
def on_migrate(sender, kwargs):
    create_superuser(sender)
  1. Save the file.

  2. Run migrations to apply changes:

python manage.py makemigrations
python manage.py migrate
  1. The superuser 'admin' with the specified email and password will be created if it does not already exist. Replace 'admin_password' with the desired password for the superuser.

Note: After the superuser is created, it's recommended to change the password using the Django management command:

python manage.py changepassword admin