How to automate createsuperuser on django?

后端 未结 16 1572
情歌与酒
情歌与酒 2020-11-29 15:57

I want to auto run manage.py createsuperuser on django but it seams that there is no way of setting a default password.

How can I get this?

16条回答
  •  星月不相逢
    2020-11-29 16:46

    I would suggest running a Data Migration, so when migrations are applied to the project, a superuser is created as part of the migrations. The username and password can be setup as environment variables. This is also useful when running an app in a container (see this thread as an example)

    Your data migration would then look like this:

    import os
    from django.db import migrations
    
    class Migration(migrations.Migration):
        dependencies = [
            ('', ''),
        ] # can also be emtpy if it's your first migration
    
        def generate_superuser(apps, schema_editor):
            from django.contrib.auth.models import User
    
            DJANGO_DB_NAME = os.environ.get('DJANGO_DB_NAME', "default")
            DJANGO_SU_NAME = os.environ.get('DJANGO_SU_NAME')
            DJANGO_SU_EMAIL = os.environ.get('DJANGO_SU_EMAIL')
            DJANGO_SU_PASSWORD = os.environ.get('DJANGO_SU_PASSWORD')
    
            superuser = User.objects.create_superuser(
                username=DJANGO_SU_NAME,
                email=DJANGO_SU_EMAIL,
                password=DJANGO_SU_PASSWORD)
    
            superuser.save()
    
        operations = [
            migrations.RunPython(generate_superuser),
        ]
    

    Hope that helps!

    EDIT: Some might raise the question how to set these environment variables and make Django aware of them. There are a lot of ways and it's been answered in other SO posts, but just as a quick pointer, creating a .env file is a good idea. You could then use the python-dotenv package, but if you have setup a virtual environment with pipenv, it will automatically set the envvars in your .env file. Likewise, running your app via docker-compose can read in your .env file.

提交回复
热议问题