80 lines
2.6 KiB
Python
80 lines
2.6 KiB
Python
# manually created serializers.py file created to turn DB data into JSON to be used by frontend
|
|
from rest_framework import serializers
|
|
from .models import *
|
|
# import Users
|
|
from django.contrib.auth import get_user_model
|
|
|
|
# return authenticated user as well as user's cart data
|
|
user = get_user_model()
|
|
|
|
|
|
|
|
# creating new users
|
|
class CustomUserCreateSerializer(serializers.ModelSerializer):
|
|
|
|
class Meta:
|
|
model = Users
|
|
fields = ('email',
|
|
'username',
|
|
'password',
|
|
'user_first_name',
|
|
'user_last_name',
|
|
'user_profile_pic',
|
|
'user_favorite_bible_verse')
|
|
extra_kwargs = {'password': {'write_only': True}}
|
|
|
|
def create(self, validated_data):
|
|
profile_pic = validated_data.pop('user_profile_pic', None)
|
|
current_user = self.Meta.model(**validated_data)
|
|
current_user.user_profile_pic = profile_pic
|
|
current_user.save() # Save user instance after adding profile_pic
|
|
return current_user
|
|
|
|
|
|
|
|
# for updating user account info
|
|
class UpdateUserAccountDataSerializer(serializers.Serializer):
|
|
username = serializers.CharField(required=False)
|
|
email = serializers.EmailField(required=False)
|
|
user_first_name = serializers.CharField(required=False)
|
|
user_last_name = serializers.CharField(required=False)
|
|
user_favorite_bible_verse = serializers.CharField(required=False)
|
|
|
|
# automatically called during validation process
|
|
def validate_username(self, value):
|
|
request = self.context.get('request')
|
|
current_user = request.user
|
|
if user.objects.filter(username=value).exists() and current_user.username != value:
|
|
raise serializers.ValidationError('Username already exists.')
|
|
return value
|
|
|
|
def validate_email(self, value):
|
|
request = self.context.get('request')
|
|
current_user = request.user
|
|
if user.objects.filter(email=value).exists() and current_user.email != value:
|
|
raise serializers.ValidationError('Email already exists.')
|
|
return value
|
|
|
|
|
|
|
|
# for displaying account info to user
|
|
class GetUserSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = Users
|
|
fields = (
|
|
"id",
|
|
"email",
|
|
"username",
|
|
"user_first_name",
|
|
"user_last_name",
|
|
"user_favorite_bible_verse",
|
|
"get_profile_pic"
|
|
)
|
|
|
|
# get user's pfp
|
|
class GetUserPfpSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = Users
|
|
fields = (
|
|
"get_profile_pic",
|
|
) |