Categories
Python Answers

How to automate createsuperuser on Python Django?

Spread the love

Sometimes, we want to automate createsuperuser on Python Django.

In this article, we’ll look at how to automate createsuperuser on Python Django.

How to automate createsuperuser on Python Django?

To automate createsuperuser on Python Django, we can create a command.

For instance, we write

from django.contrib.auth.management.commands import createsuperuser
from django.core.management import CommandError


class Command(createsuperuser.Command):
    help = 'Crate a superuser, and allow password to be provided'

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--password', dest='password', default=None,
            help='Specifies the password for the superuser.',
        )

    def handle(self, *args, **options):
        password = options.get('password')
        username = options.get('username')
        database = options.get('database')

        if password and not username:
            raise CommandError("--username is required if specifying --password")

        super(Command, self).handle(*args, **options)

        if password:
            user = self.UserModel._default_manager.db_manager(database).get(username=username)
            user.set_password(password)
            user.save()

to create the Command class that’s a subclass of the createsuperuser.Command class.

In it, we add the password argument within the add_arguments method.

And then in the handle method, we get the command line arguments from options.get.

Next, we add some validation with if statements and call save is the password and username are set.

Conclusion

To automate createsuperuser on Python Django, we can create a command.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *