jmunsch
jmunsch

Reputation: 24089

django .validate() should return the validated data

I am able to get to the pdb.set_trace of the validate() function of the subclassed serializer, however I am still receiving this error:

assert value is not None, '.validate() should return the validated data' AssertionError: .validate() should return the validated data

class UserSerializer(BaseUserSerializer):
    user = BaseUserSerializer()


class UnitSerializer(BaseUnitSerializer):
    prop = BasePropertySerializer()

    def to_internal_value(self, data):
        if isinstance(data, int):
            return self.Meta.model.objects_all.get(pk=data)


class ProjectListViewSerializer(BaseProjectSerializer):
    unit = UnitSerializer()
    coordinators = UserSerializer(many=True)
    due_date = serializers.DateTimeField()
    start_date = serializers.DateTimeField()
    project_type = serializers.ChoiceField(choices=Project.PROJECT_TYPE_CHOICES, )
    name = serializers.CharField()
    description = serializers.CharField()

    def validate(self, attrs):
        if hasattr(attrs, 'unit') and hasattr(attrs['unit'], 'is_active') and not attrs['unit'].is_active:
            raise serializers.ValidationError({'unit': ['Unit is not active, please activate this unit.']})
        coordinators = attrs.get('coordinators', [])
        if not len(coordinators):
            raise serializers.ValidationError('Coordinator(s) required when creating a project.')
        if not attrs.get('due_date', ''):
            raise serializers.ValidationError('Due date required when creating a project.')
        if not attrs.get('start_date', ''):
            raise serializers.ValidationError('Start date required when creating a project.')
        if not attrs.get('project_type', ''):
            raise serializers.ValidationError('Project type required when creating a project.')
        if not attrs.get('name', ''):
            raise serializers.ValidationError('Project name required when creating a project.')
        if not attrs.get('description', ''):
            raise serializers.ValidationError('Project description required when creating a project.')
        import pdb;pdb.set_trace()
        return attrs

    class Meta:
        model = models.Project

Upvotes: 4

Views: 2350

Answers (1)

jmunsch
jmunsch

Reputation: 24089

This was the issue that I was facing in the sub serializer:

def to_internal_value(self, data):
    if isinstance(data, int):
        return self.Meta.model.objects_all.get(pk=data)

    # this was returning None here

I added an else: return self.Meta.model.objects_all.get(pk=data.get('id')) to return an instance.

Upvotes: 3

Related Questions