fix: complete v1.2 account and profile P0 fixes

This commit is contained in:
2026-08-10 00:12:53 +08:00
parent 587962f9c9
commit 97ca20413e
14 changed files with 346 additions and 12 deletions
@@ -0,0 +1,69 @@
import os
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from accounts.models import User
class Command(BaseCommand):
help = "仅在 DEBUG 环境创建或修复本地测试管理员"
def add_arguments(self, parser):
parser.add_argument(
"--username",
default=os.getenv("LOCAL_ADMIN_USERNAME", "local_admin"),
)
parser.add_argument(
"--password",
default=os.getenv("LOCAL_ADMIN_PASSWORD", "LocalAdmin2026!"),
)
parser.add_argument(
"--email",
default=os.getenv("LOCAL_ADMIN_EMAIL", "local-admin@example.test"),
)
parser.add_argument(
"--reset-password",
action="store_true",
help="已存在账号时也重置密码",
)
def handle(self, *args, **options):
if not settings.DEBUG:
raise CommandError("init_local_admin 仅允许在 DJANGO_DEBUG=true 时运行")
username = options["username"].strip()
password = options["password"]
if not username or len(password) < 8:
raise CommandError("用户名不能为空,密码至少需要 8 个字符")
user, created = User.objects.get_or_create(
username=username,
defaults={
"nickname": "本地管理员",
"email": options["email"],
"is_staff": True,
"is_superuser": True,
"is_active": True,
},
)
changed_fields = []
for field in ("is_staff", "is_superuser", "is_active"):
if not getattr(user, field):
setattr(user, field, True)
changed_fields.append(field)
if not user.nickname:
user.nickname = "本地管理员"
changed_fields.append("nickname")
if created or options["reset_password"] or not user.has_usable_password():
user.set_password(password)
changed_fields.append("password")
if changed_fields:
user.save(update_fields=changed_fields)
action = "已创建" if created else "已确认"
self.stdout.write(
self.style.SUCCESS(
f"{action}本地管理员 {username};后台地址 http://127.0.0.1:8000/admin/"
)
)