Spaces:
Sleeping
Sleeping
| #!/usr/bin/env python | |
| import json | |
| import os | |
| import sys | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| if BASE_DIR not in sys.path: | |
| sys.path.insert(0, BASE_DIR) | |
| os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mbti_site.settings") | |
| import django | |
| django.setup() | |
| from django.contrib.auth import get_user_model | |
| from database_management.add_questions_from_json import get_question_dimension_and_pole | |
| from database_management.populate_personality_data import personality_data | |
| from mbti.models import Question, Questionnaire, TypeProfile | |
| def ensure_admin(): | |
| user_model = get_user_model() | |
| username = os.getenv("DJANGO_SUPERUSER_USERNAME", "admin") | |
| email = os.getenv("DJANGO_SUPERUSER_EMAIL", "admin@example.com") | |
| password = os.getenv("DJANGO_SUPERUSER_PASSWORD", "admin@123..") | |
| user, created = user_model.objects.get_or_create( | |
| username=username, | |
| defaults={"email": email, "is_staff": True, "is_superuser": True}, | |
| ) | |
| if created: | |
| user.set_password(password) | |
| user.save() | |
| elif not user.is_superuser or not user.is_staff: | |
| user.is_staff = True | |
| user.is_superuser = True | |
| user.set_password(password) | |
| user.save() | |
| def ensure_questions(): | |
| json_path = os.path.join(BASE_DIR, "data", "questions_standard_mbti_93.json") | |
| with open(json_path, "r", encoding="utf-8") as f: | |
| questions_data = json.load(f) | |
| qnn, _ = Questionnaire.objects.get_or_create( | |
| key="mbti_standard_93", | |
| defaults={ | |
| "name": "标准MBTI 93题测试", | |
| "description": "标准MBTI人格类型测试,共93题", | |
| "is_active": True, | |
| }, | |
| ) | |
| Questionnaire.objects.exclude(pk=qnn.pk).update(is_active=False) | |
| if not qnn.is_active: | |
| qnn.is_active = True | |
| qnn.save(update_fields=["is_active"]) | |
| for item in questions_data: | |
| question_id = item["id"] | |
| question_text = item["question"].strip() | |
| option_a = item["optionA"].strip() | |
| option_b = item["optionB"].strip() | |
| dimension, keyed_pole = get_question_dimension_and_pole(question_id) | |
| full_text = f"{question_id}. {question_text} A) {option_a} B) {option_b}" | |
| Question.objects.update_or_create( | |
| questionnaire=qnn, | |
| order=question_id, | |
| defaults={ | |
| "text": full_text, | |
| "dimension": dimension, | |
| "keyed_pole": keyed_pole, | |
| "weight": 1, | |
| "active": True, | |
| }, | |
| ) | |
| def ensure_profiles(): | |
| for code, data in personality_data.items(): | |
| profile, created = TypeProfile.objects.get_or_create(code=code, defaults=data) | |
| if not created: | |
| for field, value in data.items(): | |
| setattr(profile, field, value) | |
| profile.save() | |
| def main(): | |
| ensure_admin() | |
| ensure_questions() | |
| ensure_profiles() | |
| print("Bootstrap completed.") | |
| if __name__ == "__main__": | |
| main() | |