示例#1
0
    def validate(self, attrs):
        # Validate name/slug uniqueness, this has to be done prior docfile/zipfile
        # extracting
        for field in ("name", "slug"):
            # Skip optional fields on PATCH
            if field not in attrs:
                continue
            # Skip non changed fields
            if self.instance and getattr(self.instance, field) == attrs[field]:
                continue
            # Look for existing components
            if attrs["project"].component_set.filter(**{
                    field: attrs[field]
            }).exists():
                raise serializers.ValidationError(
                    {field: f"Component with this {field} already exists."})

        # Handle uploaded files
        if self.instance:
            for field in ("docfile", "zipfile"):
                if field in attrs:
                    raise serializers.ValidationError({
                        field:
                        "This field is for creation only, use /file/ instead."
                    })
        if "docfile" in attrs:
            fake = create_component_from_doc(attrs)
            attrs["template"] = fake.template
            attrs["new_base"] = fake.template
            attrs["filemask"] = fake.filemask
            attrs.pop("docfile")
        if "zipfile" in attrs:
            try:
                create_component_from_zip(attrs)
            except BadZipfile:
                raise serializers.ValidationError(
                    {"zipfile": "Failed to parse uploaded ZIP file."})
            attrs.pop("zipfile")
        # Handle non-component arg
        disable_autoshare = attrs.pop("disable_autoshare", False)

        # Call model validation here, DRF does not do that
        if self.instance:
            instance = copy(self.instance)
            for key, value in attrs.items():
                setattr(instance, key, value)
        else:
            instance = Component(**attrs)
        instance.clean()

        if not self.instance and not disable_autoshare:
            repo = instance.suggest_repo_link()
            if repo:
                attrs["repo"] = instance.repo = repo
                attrs["branch"] = instance.branch = ""
        return attrs
示例#2
0
 def validate(self, attrs):
     # Call model validation here, DRF does not do that
     instance = Component(**attrs)
     instance.clean()
     return attrs