Newer
Older
GestionHoteleriaApi / apps / user / serializer.py
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import Group
from django.core.exceptions import ValidationError
from rest_framework import serializers
from apps.user.models import Gender, User, Region
from hotelApi.tricks import Base64ImageField, image_user


class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = '__all__'


class UserSerializer(serializers.ModelSerializer):
    photo = Base64ImageField(
        max_length=None, use_url=True, required=False
    )

    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        groups = validated_data.pop('groups')
        email = validated_data.pop('email')

        if (User.objects.filter(email=email).exists() and groups[0].id in
                [d['groups'] for d in User.objects.filter(email=email).values('groups') if 'groups' in d]):
            raise serializers.ValidationError("Disculpa, este correo ya se encuentra registrado con otro usuario")

        user = User.objects.create(first_name=validated_data.pop('first_name').title(),
                                   last_name=validated_data.pop('last_name').title(),
                                   password=make_password(validated_data.pop('password')),
                                   email=email,
                                   username=validated_data.pop('username'), **validated_data)
        user.photo = image_user(str(user.username))
        user.groups.set(groups)
        user.save()

        return user

    def update(self, instance, validated_data):

        if 'first_name' in validated_data:
            validated_data['first_name'] = validated_data['first_name'].title()
        if 'last_name' in validated_data:
            validated_data['last_name'] = validated_data['last_name'].title()
        if 'password' in validated_data:
            validated_data['password'] = make_password(validated_data.pop('password'))
        if 'groups' in validated_data:
            groups = validated_data.pop('groups')
            instance.groups.set(groups)

        data = validated_data.copy()

        if 'old_password' and 'new_password' in data:
            old_password = data['old_password']
            new_password = data['new_password']
            if instance.check_password(old_password):
                instance.password = make_password(new_password)
                instance.save()

                return instance
            else:
                raise ValidationError(
                    message='La contraseƱa actual no coincide con la registrada en la Base de Datos'
                )

        for key, val in data.items():
            setattr(instance, key, val)
        instance.save()

        return instance


class GenderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Gender
        fields = '__all__'


class RecursiveSerializer(serializers.Serializer):
    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        pass

    def to_representation(self, value):
        serializer = self.parent.parent.__class__(value, context=self.context)
        return serializer.data


class RegionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Region
        fields = '__all__'


class RegionSerializer2(serializers.ModelSerializer):
    governed = RecursiveSerializer(many=True, read_only=True)

    class Meta:
        model = Region
        fields = '__all__'