Skip to content

Commit

Permalink
refactor: accounts/serializers.py 수정 - 시리얼라이저 필드 추가(시리얼라이저 중첩
Browse files Browse the repository at this point in the history
  • Loading branch information
devnproyj22 committed Oct 10, 2024
1 parent 0ad20a2 commit 6276811
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions accounts/serializers.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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 = [
Expand All @@ -135,6 +139,7 @@ class Meta:
"nickname",
"password",
"confirm_password",
"profile_image",
"is_active",
"is_staff",
"is_superuser",
Expand Down Expand Up @@ -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("사용자 생성 중 오류가 발생했습니다.")
Expand All @@ -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("사용자 업데이트 중 오류가 발생했습니다.")
Expand Down

0 comments on commit 6276811

Please sign in to comment.