Return 400 instead of 500 on duplicate script module upload

Catch IntegrityError from the unique (file_root, file_path) constraint
and re-raise as a ValidationError so the API returns a 400 with a clear
message rather than a 500.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Arthur
2026-03-30 15:20:38 -07:00
parent c4077bf0eb
commit c5d911c48b

View File

@@ -1,4 +1,5 @@
from django.core.files.storage import storages
from django.db import IntegrityError
from django.utils.translation import gettext_lazy as _
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
@@ -66,7 +67,12 @@ class ScriptModuleSerializer(ValidatedModelSerializer):
upload_file = validated_data.pop('upload_file', None)
if upload_file:
self._save_upload(upload_file, validated_data)
return super().create(validated_data)
try:
return super().create(validated_data)
except IntegrityError:
raise serializers.ValidationError(
_("A script module with this file name already exists.")
)
def update(self, instance, validated_data):
upload_file = validated_data.pop('upload_file', None)