0

Hello guys, this morning i want to share simply how to custom command to handle deploy Django with quickly.

  • ./manage.py deploy --yes <username> <password> <email>

  • ./manage.py deploy --yes --username=myusername --password=mypassword

Let see, the email has default empty string, so you can fill with your email or just passed it.

For example, i need custom my command to can do database migrations and create the superuser.

Inside file of: yourapp/management/commands/deploy.py

from django.db.utils import IntegrityError
from django.contrib.auth.models import User
from django.core.management import call_command
from django.core.management.base import (BaseCommand, CommandError)


class Command(BaseCommand):
    help = 'Command to handle deploy django with quickly!'

    def add_arguments(self, parser):
        parser.add_argument(
            '--yes',
            action='store_true',
            help='Activate deploy command action.'
        )
        parser.add_argument(
            '--username',
            help='Username for superuser.'
        )
        parser.add_argument(
            '--password',
            help='Password for superuser.'
        )
        parser.add_argument(
            '--email', default='',
            help='Optional email address for superuser.'
        )

    def handle(self, *args, **options):
        """
        Command to handle all arguments.
        You can do stuff here...
        """
        if options['yes'] and options['username'] and options['password']:
            # Do database migrations.
            call_command('migrate')
            call_command('makemigrations')
            call_command('migrate')

            # Creating the superuser
            try:
                superuser = User.objects.create(
                    username=options['username'],
                    password=options['password'],
                    email=options['email'],
                    is_superuser=True,
                    is_staff=True
                )
                superuser.save()
                self.stdout.write(
                    self.style.SUCCESS(
                        "Superuser as `{}` successfully created!".format(
                            options['username']
                        )
                    )
                )
            except IntegrityError:
                raise CommandError('The user as `{}` already exist!'.format(
                    options['username']
                ))
            except Exception as e:
                raise CommandError(e)
        else:
            return self.print_help('deploy', '-h')

Script above is just an example. you also can custom it with what your needs.

See also: https://docs.djangoproject.com/en/dev/howto/custom-management-commands/

server solution django python tricks

Your Answer

blog comments powered by Disqus