Django_Basic_Manufacturing/users/management/commands/change_password.py
2025-08-19 12:28:49 +07:00

57 lines
1.8 KiB
Python

from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
import getpass
User = get_user_model()
class Command(BaseCommand):
help = 'Change password for a user'
def add_arguments(self, parser):
parser.add_argument('username', nargs='?', type=str, help='Username to change password for')
def handle(self, *args, **options):
username = options['username']
if not username:
username = input("Enter username: ")
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
self.stdout.write(
self.style.ERROR(f'User "{username}" does not exist')
)
return
# Get new password
while True:
new_password = getpass.getpass("Enter new password: ")
confirm_password = getpass.getpass("Confirm new password: ")
if new_password != confirm_password:
self.stdout.write(
self.style.ERROR("Passwords do not match. Please try again.")
)
continue
# Validate password
try:
validate_password(new_password, user)
except ValidationError as e:
self.stdout.write(
self.style.ERROR(f"Password validation failed: {', '.join(e.messages)}")
)
continue
break
# Set new password
user.set_password(new_password)
user.save()
self.stdout.write(
self.style.SUCCESS(f'Successfully changed password for user "{username}"')
)