From 627681177afd55dbd37c0a812531316b90312a7d Mon Sep 17 00:00:00 2001 From: yujeong Date: Thu, 10 Oct 2024 12:11:04 +0900 Subject: [PATCH] =?UTF-8?q?refactor:=20accounts/serializers.py=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=20-=20=EC=8B=9C=EB=A6=AC=EC=96=BC=EB=9D=BC=EC=9D=B4?= =?UTF-8?q?=EC=A0=80=20=ED=95=84=EB=93=9C=20=EC=B6=94=EA=B0=80(=EC=8B=9C?= =?UTF-8?q?=EB=A6=AC=EC=96=BC=EB=9D=BC=EC=9D=B4=EC=A0=80=20=EC=A4=91?= =?UTF-8?q?=EC=B2=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- accounts/serializers.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/accounts/serializers.py b/accounts/serializers.py index 56f116a..7363dda 100644 --- a/accounts/serializers.py +++ b/accounts/serializers.py @@ -1,4 +1,6 @@ from django.contrib.auth.hashers import check_password +from materials.models import Image +from materials.serializers import ImageSerializer from rest_framework import serializers from .models import CustomUser @@ -127,6 +129,8 @@ class CustomUserDetailSerializer(serializers.ModelSerializer): student_count = serializers.SerializerMethodField() tutor_count = serializers.SerializerMethodField() + profile_image = ImageSerializer(required=False) + class Meta: model = CustomUser fields = [ @@ -135,6 +139,7 @@ class Meta: "nickname", "password", "confirm_password", + "profile_image", "is_active", "is_staff", "is_superuser", @@ -269,7 +274,12 @@ def create(self, validated_data): try: password = validated_data.pop("password", None) validated_data.pop("confirm_password") + profile_image = validated_data.pop("profile_image", None) + user = CustomUser.objects.create_user(password=password, **validated_data) + + if profile_image: + Image.objects.create(user=user, **profile_image) return user except Exception as e: raise serializers.ValidationError("사용자 생성 중 오류가 발생했습니다.") @@ -282,11 +292,23 @@ def update(self, instance, validated_data): password = validated_data.pop("password", None) validated_data.pop("confirm_password", None) + profile_image = validated_data.pop("profile_image", None) + user = super().update(instance, validated_data) + # 업데이트에 비밀번호가 있는 경우 if password: user.set_password(password) user.save() + + # 업데이트에 프로필 이미지가 있는 경우 + if profile_image: + if hasattr(user, 'image'): + for attr, value in profile_image.items(): + setattr(user.image, attr, value) + user.image.save() + else: + Image.objects.create(user=user, **profile_image) return user except Exception as e: raise serializers.ValidationError("사용자 업데이트 중 오류가 발생했습니다.")