cookiecutter / cookiecutter-django

Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly.
https://cookiecutter-django.readthedocs.io
BSD 3-Clause "New" or "Revised" License
11.97k stars 2.87k forks source link

Generate Default Admin User using Django Migrations. #2851

Closed arnav13081994 closed 3 years ago

arnav13081994 commented 3 years ago

Description

What are you proposing? How should it be implemented?

I propose to generate a default admin superuser by adding a migration file that would pick up the env vars DJANGO_SUPERUSER_USERNAME and DJANGO_SUPERUSER_EMAIL and DJANGO_SUPERUSER_PASSWORD from .django env file.

Example, the following migration file could be added to {{cookiecutter.project_slug}}/users/migrations folder:

from django.db import migrations

def generate_superuser(apps, schema_editor):
    """Create a new superuser """
    from django.contrib.auth import get_user_model
    from django.conf import settings

    superuser = get_user_model().objects.create_superuser(
        username=settings.DJANGO_SUPERUSER_USERNAME,
        email=settings.DJANGO_SUPERUSER_EMAIL,
        password=settings.DJANGO_SUPERUSER_PASSWORD,
    )
    superuser.save()

class Migration(migrations.Migration):

    dependencies = [
        ("users", "0001_initial"),
    ]

    operations = [
        migrations.RunPython(generate_superuser),
    ]

Rationale

Why should this feature be implemented?

This would make getting started with this template a lot easier and faster and is much easier than to use the django shell through the terminal or through the django container. Moreover the proposed solution would require no input from the user! We would generate random strings for the username and password just like it is done for database passwords etc.

Andrew-Chen-Wang commented 3 years ago

Just for ideas: for my projects, I have a shell script that calls call_command to run (I have other commands that create test data using factory boy) instead of putting this inside a migrations file which might cause some errors in, for example, testing and actual deployment.

arnav13081994 commented 3 years ago

@Andrew-Chen-Wang I tried doing that too but I am unable to create a password. It creates the user but not the password for some reason. I just figured it was for some security reason.

Were you able to create an admin superuser and access django admin with the same creds?

Andrew-Chen-Wang commented 3 years ago

@arnav13081994 There's a specific function called make_password that you need to pass in: https://docs.djangoproject.com/en/dev/topics/auth/passwords/#django.contrib.auth.hashers.make_password

arnav13081994 commented 3 years ago

Thanks! I'll take a look.