From fceca8258ac9502b8da9702ccd44badb6f12a623 Mon Sep 17 00:00:00 2001 From: Aroy-Art Date: Tue, 28 Jan 2025 22:09:47 +0100 Subject: [PATCH] Add: UserProfile & User model serializers --- backend/api/user/serializers.py | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 backend/api/user/serializers.py diff --git a/backend/api/user/serializers.py b/backend/api/user/serializers.py new file mode 100644 index 0000000..1c10d23 --- /dev/null +++ b/backend/api/user/serializers.py @@ -0,0 +1,42 @@ +# api/user/serializers.py +from rest_framework import serializers +from .models import UserProfile +from django.contrib.auth.models import User + + +class UserProfileSerializer(serializers.ModelSerializer): + class Meta: + model = UserProfile + fields = ["show_mature"] + + def update(self, instance, validated_data): + # Use setattr to assign values to the instance fields + for attr, value in validated_data.items(): + setattr(instance, attr, value) + instance.save() # Save the changes to the database + return instance + + +class UserSerializer(serializers.ModelSerializer): + profile = UserProfileSerializer(source="userprofile", read_only=False) + + class Meta: + model = User + fields = ["username", "email", "first_name", "last_name", "profile"] + + def update(self, instance, validated_data): + # Extract profile data if it exists + profile_data = validated_data.pop("userprofile", None) + + # Update the UserProfile instance + if profile_data: + userprofile_instance = instance.userprofile # The related UserProfile instance + profile_serializer = self.fields["profile"] # Get the nested serializer + profile_serializer.update(userprofile_instance, profile_data) # Update the UserProfile + + # Update the User fields + for attr, value in validated_data.items(): + setattr(instance, attr, value) + instance.save() # Save the User instance + return instance +