django how to create superuser if does not exists on migration
Open the
models.py
file in your Django app.Import the necessary modules:
from django.contrib.auth.models import User
from django.db.models.signals import post_migrate
from django.dispatch import receiver
- 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')
- Use the
@receiver
decorator to connect the function to thepost_migrate
signal:
@receiver(post_migrate)
def on_migrate(sender, kwargs):
create_superuser(sender)
Save the file.
Run migrations to apply changes:
python manage.py makemigrations
python manage.py migrate
- 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