Exemplo n.º 1
0
    def create(self, validated_data):
        data = validated_data.copy()
        tags_data = data.pop("tags")
        content = Content.objects.create(
            owner=self.context["request"].user,
            content_type_id=data["content_type_id"])
        for comp_data in data["components"]:
            serializer = ComponentSerializer2(data=comp_data,
                                              context=self.context)
            if serializer.is_valid():
                comp = serializer.create(serializer.validated_data)
                comp.save()
                content.components.add(comp)
        content.save()

        for tag_data in tags_data:
            tag = Tag.objects.filter(label=tag_data["label"])
            if tag.exists():
                tag = tag.first()
            else:
                serializer = TagSerializer(data=tag_data)
                if serializer.is_valid():
                    tag = serializer.create(serializer.validated_data)
            content.tags.add(tag)
        content.save()
        return content
Exemplo n.º 2
0
    def update(self, instance, validated_data):
        data = validated_data.copy()
        interests_data = data.pop('interests')
        user = instance
        tag_ids=[]

        # update profile except interests
        s = ProfileSerializerBase(instance, data=data, context=self.context, partial=True)
        if s.is_valid():
            s.update(instance, s.validated_data)

        # update interests
        for interest in interests_data:
            tag = Tag.objects.filter(label=interest["label"])
            if tag.exists():
                tag = tag.first()
                t = user.interests.filter(id=tag.id)
                if t.exists():
                    tag_ids.append(t.first().id)
                    continue
            else:
                serializer = TagSerializer(data=interest)
                if serializer.is_valid():
                    tag = serializer.create(serializer.validated_data)
            tag_ids.append(tag.id)
            user.interests.add(tag)

        for tag in user.interests.all():
            if tag.id not in tag_ids:
                user.interests.remove(tag)

        user.save()
        return user
Exemplo n.º 3
0
 def create(self, validated_data):
     data = validated_data.copy()
     interests_data = data.pop('interests')
     user = UserProfile.objects.create(**data)
     for interest in interests_data:
         tag = Tag.objects.filter(label=interest["label"])
         if tag.exists():
             tag = tag.first()
         else:
             serializer = TagSerializer(data=interest)
             if serializer.is_valid():
                 tag = serializer.create(serializer.validated_data)
         user.interests.add(tag)
     user.save()
     return user
Exemplo n.º 4
0
    def create(self, validated_data):
        data = validated_data.copy()
        tags_data = data.pop("tags")
        serializer = IGroupSerializer(data=data)
        instance = None
        if serializer.is_valid():
            instance = serializer.create(serializer.validated_data)

        for tag_data in tags_data:
            tag = Tag.objects.filter(label=tag_data["label"])
            if tag.exists():
                tag = tag.first()
            else:
                serializer = TagSerializer(data=tag_data)
                if serializer.is_valid():
                    tag = serializer.create(serializer.validated_data)
            instance.tags.add(tag)
        instance.owner = self.context["request"].user
        instance.members.add(instance.owner)

        ctypes = ContentType.objects.filter(is_default=True)
        for c in ctypes:
            instance.content_types.add(c)

        instance.save()
        return instance
Exemplo n.º 5
0
    def to_internal_value(self, data):
        print(self.context["request"].user)
        if self.context["request"].user is None:
            return serializers.ValidationError("No authenticated user.")
        data = data.copy()
        tags_data = []
        if "tags" in data:
            tags_data = data.pop("tags")

        serializer = IGroupSerializer(data=data, partial=self.partial)

        validated_data = OrderedDict()
        if serializer.is_valid():
            validated_data = serializer.validated_data
        else:
            raise serializers.ValidationError(serializer.errors)

        validated_data["tags"] = []
        for tag in tags_data:
            t = Tag.objects.filter(label=tag["label"])
            if t.exists():
                validated_data["tags"].append(tag)
            else:
                serializer = TagSerializer(data=tag)
                if serializer.is_valid():
                    validated_data["tags"].append(serializer.validated_data)
                else:
                    print(serializer.errors)
                    raise serializers.ValidationError(serializer.errors)

        return validated_data
Exemplo n.º 6
0
    def update(self, instance, validated_data):
        data = validated_data.copy()
        tags_data = None
        if "tags" in data:
            tags_data = data.pop("tags")
        print(data)
        serializer = IGroupSerializer(instance, data, partial=self.partial)
        if serializer.is_valid():
            serializer.update(instance, serializer.validated_data)
        # super(InterestGroupSerializer, self).update(instance,data)

        if tags_data is not None:
            print("None")
            tag_ids = []
            print(tags_data)
            for tag_data in tags_data:
                tag = Tag.objects.filter(label=tag_data["label"])
                if tag.exists():
                    tag = tag.first()
                    t = instance.tags.filter(id=tag.id)
                    if t.exists():
                        tag_ids.append(tag.id)
                        continue
                else:
                    serializer = TagSerializer(data=tag_data)
                    if serializer.is_valid():
                        tag = serializer.create(serializer.validated_data)
                tag_ids.append(tag.id)
                instance.tags.add(tag)
            print('---', tag_ids)
            for tag in instance.tags.all():
                if tag.id not in tag_ids:
                    instance.tags.remove(tag)
        instance.save()
        return instance
Exemplo n.º 7
0
    def to_internal_value(self, data):
        data = data.copy()
        interests_data = data.pop("interests")
        serializer = ProfileSerializerBase(data = data, partial = self.partial)
        validated_data = None
        if serializer.is_valid():
            validated_data = serializer.validated_data
        else:
            raise serializers.ValidationError(serializer.errors)

        # print('USER', self.context["request"].user)
        if "owner_id" in data:
            validated_data["owner_id"] = data["owner_id"]

        validated_data["interests"] = []
        for interest in interests_data:
            t = Tag.objects.filter(label=interest["label"])
            if t.exists():
                validated_data["interests"].append(interest)
            else:
                serializer = TagSerializer(data = interest)
                print("interest:", interest)
                if serializer.is_valid():
                    validated_data["interests"].append(serializer.validated_data)
                else:
                    raise serializers.ValidationError(serializer.errors)
        return validated_data
Exemplo n.º 8
0
    def to_internal_value(self, data):
        data = data.copy()
        tags_data = []
        if "tags" in data:
            tags_data = data.pop("tags")

        serializer = IGroupSerializer(data=data, partial=self.partial)

        validated_data = OrderedDict()
        if serializer.is_valid():
            validated_data = serializer.validated_data
        else:
            raise serializers.ValidationError(serializer.errors)

        try:
            validated_data["tags"] = []
            for tag in tags_data:
                t = Tag.objects.filter(label=tag["label"])
                if t.exists():
                    validated_data["tags"].append(tag)
                else:
                    serializer = TagSerializer(data=tag)
                    if serializer.is_valid():
                        validated_data["tags"].append(
                            serializer.validated_data)
                    else:
                        ValidationError(serializer.errors)
        except Exception as e:
            if not self.partial:
                raise serializers.ValidationError(str(e))

        return validated_data
Exemplo n.º 9
0
 def to_internal_value(self, data):
     data = data.copy()
     interests_data = data.pop("interests")
     validated_data = super(ProfileSerializer,self).to_internal_value(data)
     validated_data["interests"] = []
     for interest in interests_data:
         t = Tag.objects.filter(label=interest["label"])
         if t.exists():
             validated_data["interests"].append(interest)
         else:
             serializer = TagSerializer(data = interest)
             if serializer.is_valid():
                 validated_data["interests"].append(serializer.validated_data)
             else:
                 ValidationError(serializer.errors)
     return validated_data
Exemplo n.º 10
0
class ProfileSerializer(serializers.ModelSerializer):
    interests = TagSerializer(many=True, read_only=False)

    class Meta:
        model = UserProfile
        fields = ('name', 'lastname', 'birthdate', 'gender', 'contacts', 'about', 'is_public', 'facebook_account', 'twitter_account', 'instagram_account', 'interests')
    
    def to_internal_value(self, data):
        data = data.copy()
        interests_data = data.pop("interests")
        validated_data = super(ProfileSerializer,self).to_internal_value(data)
        validated_data["interests"] = []
        for interest in interests_data:
            t = Tag.objects.filter(label=interest["label"])
            if t.exists():
                validated_data["interests"].append(interest)
            else:
                serializer = TagSerializer(data = interest)
                if serializer.is_valid():
                    validated_data["interests"].append(serializer.validated_data)
                else:
                    ValidationError(serializer.errors)
        return validated_data
    
    def create(self, validated_data):
        data = validated_data.copy()
        interests_data = data.pop('interests')
        user = UserProfile.objects.create(**data)
        for interest in interests_data:
            tag = Tag.objects.filter(label=interest["label"])
            if tag.exists():
                tag = tag.first()
            else:
                serializer = TagSerializer(data=interest)
                if serializer.is_valid():
                    tag = serializer.create(serializer.validated_data)
            user.interests.add(tag)
        user.save()
        return user
    
    def update(self, instance, validated_data):
        data = validated_data.copy()
        interests_data = data.pop('interests')
        print(interests_data)
        user = instance
        for interest in interests_data:
            tag = Tag.objects.filter(label=interest["label"])
            if tag.exists():
                tag = tag.first()
                t = user.interests.filter(id=tag.id)
                if t.exists():
                    continue
            else:
                serializer = TagSerializer(data=interest)
                if serializer.is_valid():
                    tag = serializer.create(serializer.validated_data)
            user.interests.add(tag)
        user.save()
        return user
Exemplo n.º 11
0
    def update(self, instance, validated_data):
        print("---update---")
        data = validated_data.copy()

        instance.owner_id = data.get("owner_id", instance.owner_id)
        instance.content_type_id = data.get("content_type_id",
                                            instance.content_type_id)
        instance.save()

        if "components" in data:
            for comp_data in data["components"]:
                comp = instance.components.filter(
                    order=comp_data["order"]).first()
                serializer = ComponentSerializer2(comp,
                                                  many=False,
                                                  data=comp_data,
                                                  context=self.context)
                if serializer.is_valid():
                    comp = serializer.update(comp, serializer.validated_data)
        instance.save()

        print(data)

        if "tags" in data:
            tag_ids = []
            print("we have some tags")
            tags_data = data["tags"]
            for tag_data in tags_data:
                tag = Tag.objects.filter(label=tag_data["label"])
                if tag.exists():
                    tag = tag.first()
                    t = instance.tags.filter(id=tag.id)
                    if t.exists():
                        tag_ids.append(tag.id)
                        continue
                else:
                    serializer = TagSerializer(data=tag_data)
                    if serializer.is_valid():
                        tag = serializer.create(serializer.validated_data)
                tag_ids.append(tag.id)
                instance.tags.add(tag)
            for tag in instance.tags.all():
                if tag.id not in tag_ids:
                    instance.tags.remove(tag)
        instance.save()
        return instance
Exemplo n.º 12
0
 def update(self, instance, validated_data):
     data = validated_data.copy()
     interests_data = data.pop('interests')
     print(interests_data)
     user = instance
     for interest in interests_data:
         tag = Tag.objects.filter(label=interest["label"])
         if tag.exists():
             tag = tag.first()
             t = user.interests.filter(id=tag.id)
             if t.exists():
                 continue
         else:
             serializer = TagSerializer(data=interest)
             if serializer.is_valid():
                 tag = serializer.create(serializer.validated_data)
         user.interests.add(tag)
     user.save()
     return user
Exemplo n.º 13
0
 def to_representation(self, obj):
     response = OrderedDict()
     response['owner'] = UserSerializer(obj.owner,
                                        context=self.context).data
     response['content_type'] = ContentTypeSerializer(
         obj.content_type, context=self.context).data
     response['components'] = ComponentSerializer2(
         obj.components.all(), many=True, context=self.context).data
     response['tags'] = TagSerializer(obj.tags.all(),
                                      many=True,
                                      context=self.context).data
     response['created_date'] = str(obj.created_date)
     response['modified_date'] = str(obj.modified_date)
     return response
Exemplo n.º 14
0
    def create(self, validated_data):
        data = validated_data.copy()
        tags_data = data.pop("tags")
        serializer = IGroupSerializer(data=data)
        instance = None
        if serializer.is_valid():
            instance = serializer.create(serializer.validated_data)

        for tag_data in tags_data:
            tag = Tag.objects.filter(label=tag_data["label"])
            if tag.exists():
                tag = tag.first()
            else:
                serializer = TagSerializer(data=tag_data)
                if serializer.is_valid():
                    tag = serializer.create(serializer.validated_data)
            instance.tags.add(tag)
        instance.save()
        return instance
Exemplo n.º 15
0
class InterestGroupSerializer(serializers.HyperlinkedModelSerializer):
    tags = TagSerializer(many=True, read_only=False)
    logo_img = serializers.SerializerMethodField()
    cover_img = serializers.SerializerMethodField()

    def get_logo_img(self, obj):
        if not obj.logo_img:
            return None
        else:
            return "http://" + self.context["request"].META[
                'HTTP_HOST'] + "/" + obj.logo_img.url

    def get_cover_img(self, obj):
        if not obj.cover_img:
            return None
        else:
            return "http://" + self.context["request"].META[
                'HTTP_HOST'] + "/" + obj.cover_img.url

    class Meta:
        model = InterestGroup
        fields = ('id', 'name', 'is_public', 'description', 'tags', 'logo_img',
                  'cover_img', 'owner')
        read_only_fields = (
            'logo_img',
            'cover_img',
        )

    def to_internal_value(self, data):
        print(self.context["request"].user)
        if self.context["request"].user is None:
            return serializers.ValidationError("No authenticated user.")
        data = data.copy()
        tags_data = []
        if "tags" in data:
            tags_data = data.pop("tags")

        serializer = IGroupSerializer(data=data, partial=self.partial)

        validated_data = OrderedDict()
        if serializer.is_valid():
            validated_data = serializer.validated_data
        else:
            raise serializers.ValidationError(serializer.errors)

        validated_data["tags"] = []
        for tag in tags_data:
            t = Tag.objects.filter(label=tag["label"])
            if t.exists():
                validated_data["tags"].append(tag)
            else:
                serializer = TagSerializer(data=tag)
                if serializer.is_valid():
                    validated_data["tags"].append(serializer.validated_data)
                else:
                    print(serializer.errors)
                    raise serializers.ValidationError(serializer.errors)

        return validated_data

    def create(self, validated_data):
        data = validated_data.copy()
        tags_data = data.pop("tags")
        serializer = IGroupSerializer(data=data)
        instance = None
        if serializer.is_valid():
            instance = serializer.create(serializer.validated_data)

        for tag_data in tags_data:
            tag = Tag.objects.filter(label=tag_data["label"])
            if tag.exists():
                tag = tag.first()
            else:
                serializer = TagSerializer(data=tag_data)
                if serializer.is_valid():
                    tag = serializer.create(serializer.validated_data)
            instance.tags.add(tag)
        instance.owner = self.context["request"].user
        instance.members.add(instance.owner)

        ctypes = ContentType.objects.filter(is_default=True)
        for c in ctypes:
            instance.content_types.add(c)

        instance.save()
        return instance

    def update(self, instance, validated_data):
        data = validated_data.copy()
        tags_data = None
        if "tags" in data:
            tags_data = data.pop("tags")
        print(data)
        serializer = IGroupSerializer(instance, data, partial=self.partial)
        if serializer.is_valid():
            serializer.update(instance, serializer.validated_data)
        # super(InterestGroupSerializer, self).update(instance,data)

        if tags_data is not None:
            print("None")
            tag_ids = []
            print(tags_data)
            for tag_data in tags_data:
                tag = Tag.objects.filter(label=tag_data["label"])
                if tag.exists():
                    tag = tag.first()
                    t = instance.tags.filter(id=tag.id)
                    if t.exists():
                        tag_ids.append(tag.id)
                        continue
                else:
                    serializer = TagSerializer(data=tag_data)
                    if serializer.is_valid():
                        tag = serializer.create(serializer.validated_data)
                tag_ids.append(tag.id)
                instance.tags.add(tag)
            print('---', tag_ids)
            for tag in instance.tags.all():
                if tag.id not in tag_ids:
                    instance.tags.remove(tag)
        instance.save()
        return instance
Exemplo n.º 16
0
class ProfileSerializer(serializers.ModelSerializer):
    interests = TagSerializer(many=True, read_only=False)
    photo = serializers.SerializerMethodField()

    def get_photo(self, obj):
        if not obj.photo:
            return None
        else:
            return "http://" + self.context["request"].META['HTTP_HOST'] + "/" + obj.photo.url

    class Meta:
        model = UserProfile
        fields = ('name', 'lastname', 'birthdate', 'gender', 'contacts', 'about', 'is_public', 'facebook_account', 'twitter_account', 'instagram_account', 'interests', 'photo')
    
    def to_internal_value(self, data):
        data = data.copy()
        interests_data = data.pop("interests")
        serializer = ProfileSerializerBase(data = data, partial = self.partial)
        validated_data = None
        if serializer.is_valid():
            validated_data = serializer.validated_data
        else:
            raise serializers.ValidationError(serializer.errors)

        # print('USER', self.context["request"].user)
        if "owner_id" in data:
            validated_data["owner_id"] = data["owner_id"]

        validated_data["interests"] = []
        for interest in interests_data:
            t = Tag.objects.filter(label=interest["label"])
            if t.exists():
                validated_data["interests"].append(interest)
            else:
                serializer = TagSerializer(data = interest)
                print("interest:", interest)
                if serializer.is_valid():
                    validated_data["interests"].append(serializer.validated_data)
                else:
                    raise serializers.ValidationError(serializer.errors)
        return validated_data
    
    def create(self, validated_data):
        data = validated_data.copy()
        interests_data = data.pop('interests')
        user = UserProfile.objects.create(**data)
        user.save()
        for interest in interests_data:
            tag = Tag.objects.filter(label=interest["label"])
            if tag.exists():
                tag = tag.first()
            else:
                serializer = TagSerializer(data=interest)
                if serializer.is_valid():
                    tag = serializer.create(serializer.validated_data)
            user.interests.add(tag)
        user.save()
        return user
    
    def update(self, instance, validated_data):
        data = validated_data.copy()
        interests_data = data.pop('interests')
        user = instance
        tag_ids=[]

        # update profile except interests
        s = ProfileSerializerBase(instance, data=data, context=self.context, partial=True)
        if s.is_valid():
            s.update(instance, s.validated_data)

        # update interests
        for interest in interests_data:
            tag = Tag.objects.filter(label=interest["label"])
            if tag.exists():
                tag = tag.first()
                t = user.interests.filter(id=tag.id)
                if t.exists():
                    tag_ids.append(t.first().id)
                    continue
            else:
                serializer = TagSerializer(data=interest)
                if serializer.is_valid():
                    tag = serializer.create(serializer.validated_data)
            tag_ids.append(tag.id)
            user.interests.add(tag)

        for tag in user.interests.all():
            if tag.id not in tag_ids:
                user.interests.remove(tag)

        user.save()
        return user
Exemplo n.º 17
0
class ContentSerializer(serializers.HyperlinkedModelSerializer):
    components = ComponentSerializer2(many=True)
    owner = UserSerializer(read_only=True, allow_null=False, many=False)
    content_type = ContentTypeSerializer(read_only=True,
                                         allow_null=True,
                                         many=False)
    tags = TagSerializer(many=True, read_only=False)
    groups = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Content
        fields = ("id", "content_type", "created_date", "modified_date",
                  "owner", 'components', 'tags', 'groups')

    def to_internal_value(self, data):
        data = data.copy()
        validated_data = OrderedDict()
        print("to_internal_value")
        try:
            if not ContentType.objects.filter(
                    id=data['content_type_id']).exists():
                raise serializers.ValidationError(
                    "No content type with given content_type_id.")
            content_type = ContentType.objects.get(pk=data['content_type_id'])
            validated_data["content_type_id"] = data["content_type_id"]

            validated_data["components"] = []

            if len(data["components"]) != len(content_type.components):
                raise serializers.ValidationError(
                    "Number of components does not match with content type.")

            for component in data["components"]:
                print('comp:', component)
                serializer = ComponentSerializer2(data=component,
                                                  context=self.context)
                if not serializer.is_valid():
                    print("ehehe")
                    print(serializer.errors)
                    error = serializer.errors
                    raise serializers.ValidationError(error)
                if component["component_type"] != content_type.components[
                        component["order"] - 1]:
                    print("ohoho")
                    raise serializers.ValidationError(
                        "Order of the components does not match with content type"
                    )

                print("end")
                validated_data["components"].append(serializer.validated_data)

        except Exception as e:
            if not self.partial:
                raise serializers.ValidationError(str(e))

        # print("to_internal_value")

        try:
            if "tags" in data:
                validated_data["tags"] = []
            for tag in data["tags"]:
                t = Tag.objects.filter(label=tag["label"])
                if t.exists():
                    validated_data["tags"].append(tag)
                else:
                    serializer = TagSerializer(data=tag)
                    if serializer.is_valid():
                        validated_data["tags"].append(
                            serializer.validated_data)
                    else:
                        ValidationError(serializer.errors)
        except Exception as e:
            if not self.partial:
                raise serializers.ValidationError(str(e))

        return validated_data

    def create(self, validated_data):
        data = validated_data.copy()
        tags_data = data.pop("tags")
        content = Content.objects.create(
            owner=self.context["request"].user,
            content_type_id=data["content_type_id"])
        for comp_data in data["components"]:
            serializer = ComponentSerializer2(data=comp_data,
                                              context=self.context)
            if serializer.is_valid():
                comp = serializer.create(serializer.validated_data)
                comp.save()
                content.components.add(comp)
        content.save()

        for tag_data in tags_data:
            tag = Tag.objects.filter(label=tag_data["label"])
            if tag.exists():
                tag = tag.first()
            else:
                serializer = TagSerializer(data=tag_data)
                if serializer.is_valid():
                    tag = serializer.create(serializer.validated_data)
            content.tags.add(tag)
        content.save()
        return content

    def update(self, instance, validated_data):
        print("---update---")
        data = validated_data.copy()

        instance.owner_id = data.get("owner_id", instance.owner_id)
        instance.content_type_id = data.get("content_type_id",
                                            instance.content_type_id)
        instance.save()

        if "components" in data:
            for comp_data in data["components"]:
                comp = instance.components.filter(
                    order=comp_data["order"]).first()
                serializer = ComponentSerializer2(comp,
                                                  many=False,
                                                  data=comp_data,
                                                  context=self.context)
                if serializer.is_valid():
                    comp = serializer.update(comp, serializer.validated_data)
        instance.save()

        print(data)

        if "tags" in data:
            tag_ids = []
            print("we have some tags")
            tags_data = data["tags"]
            for tag_data in tags_data:
                tag = Tag.objects.filter(label=tag_data["label"])
                if tag.exists():
                    tag = tag.first()
                    t = instance.tags.filter(id=tag.id)
                    if t.exists():
                        tag_ids.append(tag.id)
                        continue
                else:
                    serializer = TagSerializer(data=tag_data)
                    if serializer.is_valid():
                        tag = serializer.create(serializer.validated_data)
                tag_ids.append(tag.id)
                instance.tags.add(tag)
            for tag in instance.tags.all():
                if tag.id not in tag_ids:
                    instance.tags.remove(tag)
        instance.save()
        return instance
Exemplo n.º 18
0
    def to_internal_value(self, data):
        data = data.copy()
        validated_data = OrderedDict()
        print("to_internal_value")
        try:
            if not ContentType.objects.filter(
                    id=data['content_type_id']).exists():
                raise serializers.ValidationError(
                    "No content type with given content_type_id.")
            content_type = ContentType.objects.get(pk=data['content_type_id'])
            validated_data["content_type_id"] = data["content_type_id"]

            validated_data["components"] = []

            if len(data["components"]) != len(content_type.components):
                raise serializers.ValidationError(
                    "Number of components does not match with content type.")

            for component in data["components"]:
                print('comp:', component)
                serializer = ComponentSerializer2(data=component,
                                                  context=self.context)
                if not serializer.is_valid():
                    print("ehehe")
                    print(serializer.errors)
                    error = serializer.errors
                    raise serializers.ValidationError(error)
                if component["component_type"] != content_type.components[
                        component["order"] - 1]:
                    print("ohoho")
                    raise serializers.ValidationError(
                        "Order of the components does not match with content type"
                    )

                print("end")
                validated_data["components"].append(serializer.validated_data)

        except Exception as e:
            if not self.partial:
                raise serializers.ValidationError(str(e))

        # print("to_internal_value")

        try:
            if "tags" in data:
                validated_data["tags"] = []
            for tag in data["tags"]:
                t = Tag.objects.filter(label=tag["label"])
                if t.exists():
                    validated_data["tags"].append(tag)
                else:
                    serializer = TagSerializer(data=tag)
                    if serializer.is_valid():
                        validated_data["tags"].append(
                            serializer.validated_data)
                    else:
                        ValidationError(serializer.errors)
        except Exception as e:
            if not self.partial:
                raise serializers.ValidationError(str(e))

        return validated_data
Exemplo n.º 19
0
class InterestGroupSerializer(serializers.HyperlinkedModelSerializer):
    tags = TagSerializer(many=True, read_only=False)

    class Meta:
        model = InterestGroup
        fields = ('id', 'name', 'is_public', 'description', 'logo',
                  'cover_photo', 'tags')

    def to_internal_value(self, data):
        data = data.copy()
        tags_data = []
        if "tags" in data:
            tags_data = data.pop("tags")

        serializer = IGroupSerializer(data=data, partial=self.partial)

        validated_data = OrderedDict()
        if serializer.is_valid():
            validated_data = serializer.validated_data
        else:
            raise serializers.ValidationError(serializer.errors)

        try:
            validated_data["tags"] = []
            for tag in tags_data:
                t = Tag.objects.filter(label=tag["label"])
                if t.exists():
                    validated_data["tags"].append(tag)
                else:
                    serializer = TagSerializer(data=tag)
                    if serializer.is_valid():
                        validated_data["tags"].append(
                            serializer.validated_data)
                    else:
                        ValidationError(serializer.errors)
        except Exception as e:
            if not self.partial:
                raise serializers.ValidationError(str(e))

        return validated_data

    def create(self, validated_data):
        data = validated_data.copy()
        tags_data = data.pop("tags")
        serializer = IGroupSerializer(data=data)
        instance = None
        if serializer.is_valid():
            instance = serializer.create(serializer.validated_data)

        for tag_data in tags_data:
            tag = Tag.objects.filter(label=tag_data["label"])
            if tag.exists():
                tag = tag.first()
            else:
                serializer = TagSerializer(data=tag_data)
                if serializer.is_valid():
                    tag = serializer.create(serializer.validated_data)
            instance.tags.add(tag)
        instance.save()
        return instance

    def update(self, instance, validated_data):
        data = validated_data.copy()
        tags_data = None
        if "tags" in data:
            tags_data = data.pop("tags")
        print(data)
        serializer = IGroupSerializer(instance, data, partial=self.partial)
        if serializer.is_valid():
            serializer.update(instance, serializer.validated_data)
        # super(InterestGroupSerializer, self).update(instance,data)

        if tags_data is not None:
            print("None")
            tag_ids = []
            print(tags_data)
            for tag_data in tags_data:
                tag = Tag.objects.filter(label=tag_data["label"])
                if tag.exists():
                    tag = tag.first()
                    t = instance.tags.filter(id=tag.id)
                    if t.exists():
                        tag_ids.append(tag.id)
                        continue
                else:
                    serializer = TagSerializer(data=tag_data)
                    if serializer.is_valid():
                        tag = serializer.create(serializer.validated_data)
                tag_ids.append(tag.id)
                instance.tags.add(tag)
            print('---', tag_ids)
            for tag in instance.tags.all():
                if tag.id not in tag_ids:
                    instance.tags.remove(tag)
        instance.save()
        return instance