from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS


class Command(BaseCommand):
    help = "Quietly change a user's password for django.contrib.auth."

    requires_system_checks = False

    def add_arguments(self, parser):
        parser.add_argument('username', type=str,
            help='Username to change password for.')
        parser.add_argument('password', type=str,
            help='Password (will not be validated).')
        parser.add_argument('--database', action='store', dest='database',
            default=DEFAULT_DB_ALIAS,
            help='Specifies the database to use. Default is "default".')

    def handle(self, *args, **options):

        username = options['username']
        password = options['password']

        user_model_cls = get_user_model()

        try:
            u = user_model_cls._default_manager \
                    .using(options.get('database')) \
                    .get(**{user_model_cls.USERNAME_FIELD: username})
        except user_model_cls.DoesNotExist:
            raise CommandError("user '%s' does not exist" % username)

        u.set_password(password)
        u.save()

        return "Password changed successfully for user '%s'" % u

Add 'manage.py' command for unattended password setup
Add 'manage.py' command for unattended password setup

Unfortunately, there is no standard way to non-interactively create
superuser account, neither in Django, nor in django-extensions. All the
following commands require manual pasword-typing:

 - createsuperuser
 - changepassword
 - passwd
 - set_fake_passwords (works with DEBUG=True only)

So it was really necessary to invent our own wheel in order to make
convenient unattended deploys (see: Docker, Heroku) possible.

Signed-off-by: Pavel Kretov <7cae407f1f3b56350827d1394be40a3e8f9cb303@gmail.com>
