🔧 Fix reset_admin foreign key constraint issue - Update existing admin users instead of deleting them - Prevents constraint violations during Railway deployment - Command now safely handles existing admin users with related records 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>

This commit is contained in:
Claude 2025-08-16 14:42:28 +05:30
parent 87ec7cc50a
commit 21157b6955

View File

@ -42,40 +42,47 @@ class Command(BaseCommand):
self.stdout.write("🔄 Resetting admin user...") self.stdout.write("🔄 Resetting admin user...")
# Delete ANY existing admin users (all possible emails/usernames) # Check for existing admin user (update instead of creating new)
deleted_count = 0 existing_admin = None
# Check for users with admin emails # Check for users with admin emails
admin_emails = ['admin@quantumtaskai.com', 'admin@netcop.ai'] admin_emails = ['admin@quantumtaskai.com', 'admin@netcop.ai']
for admin_email in admin_emails: for admin_email in admin_emails:
try: try:
user = User.objects.get(email=admin_email) existing_admin = User.objects.get(email=admin_email)
user.delete() self.stdout.write(f"📧 Found existing admin with email: {admin_email}")
deleted_count += 1 break
self.stdout.write(f"❌ Deleted user with email: {admin_email}")
except User.DoesNotExist: except User.DoesNotExist:
pass pass
# Check for users with admin username # Check for users with admin username if no email match
try: if not existing_admin:
user = User.objects.get(username=username) try:
if user.email not in admin_emails: # Don't double-delete existing_admin = User.objects.get(username=username)
user.delete() self.stdout.write(f"👤 Found existing admin with username: {username}")
deleted_count += 1 except User.DoesNotExist:
self.stdout.write(f"❌ Deleted user with username: {username}") pass
except User.DoesNotExist:
pass
self.stdout.write(f"🗑️ Deleted {deleted_count} existing admin user(s)") if existing_admin:
# Update existing admin user
# Create fresh admin user self.stdout.write("🔄 Updating existing admin user...")
self.stdout.write("🆕 Creating fresh admin user...") existing_admin.username = username
existing_admin.email = email
user = User.objects.create_superuser( existing_admin.set_password(password)
username=username, existing_admin.is_superuser = True
email=email, existing_admin.is_staff = True
password=password, existing_admin.is_active = True
) existing_admin.save()
user = existing_admin
self.stdout.write("✅ Existing admin user updated successfully!")
else:
# Create fresh admin user
self.stdout.write("🆕 Creating fresh admin user...")
user = User.objects.create_superuser(
username=username,
email=email,
password=password,
)
# Add initial balance # Add initial balance
user.add_balance(100, "Initial admin balance") user.add_balance(100, "Initial admin balance")