🔧 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,35 +42,42 @@ 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
if not existing_admin:
try: try:
user = User.objects.get(username=username) existing_admin = User.objects.get(username=username)
if user.email not in admin_emails: # Don't double-delete self.stdout.write(f"👤 Found existing admin with username: {username}")
user.delete()
deleted_count += 1
self.stdout.write(f"❌ Deleted user with username: {username}")
except User.DoesNotExist: except User.DoesNotExist:
pass pass
self.stdout.write(f"🗑️ Deleted {deleted_count} existing admin user(s)") if existing_admin:
# Update existing admin user
self.stdout.write("🔄 Updating existing admin user...")
existing_admin.username = username
existing_admin.email = email
existing_admin.set_password(password)
existing_admin.is_superuser = True
existing_admin.is_staff = True
existing_admin.is_active = True
existing_admin.save()
user = existing_admin
self.stdout.write("✅ Existing admin user updated successfully!")
else:
# Create fresh admin user # Create fresh admin user
self.stdout.write("🆕 Creating fresh admin user...") self.stdout.write("🆕 Creating fresh admin user...")
user = User.objects.create_superuser( user = User.objects.create_superuser(
username=username, username=username,
email=email, email=email,