From 66c982047e7d53a98e8003c8f37e26102db487f8 Mon Sep 17 00:00:00 2001 From: ashkan <71752736+oneashkan@users.noreply.github.com> Date: Thu, 16 Oct 2025 17:12:15 +0330 Subject: [PATCH] Update services.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Summary This pull request improves the `model_update` function by adding proper handling for Django `ValidationError`. It now converts it into DRF's `ValidationError` to ensure consistent API responses (HTTP 400 instead of 500). ### Changes - Added `try/except` block around `instance.full_clean()` and `instance.save()`. - Converted `django.core.exceptions.ValidationError` → `rest_framework.exceptions.ValidationError`. - Ensured clean, consistent error handling across all model update operations. ### Why Previously, unhandled validation errors resulted in server errors (500). This update ensures that all validation issues are returned properly as JSON API responses. ### Testing - Manually tested with invalid model fields. - Confirmed correct 400 responses in API. --- styleguide_example/common/services.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/styleguide_example/common/services.py b/styleguide_example/common/services.py index c064fdb1..8a228d88 100644 --- a/styleguide_example/common/services.py +++ b/styleguide_example/common/services.py @@ -4,7 +4,8 @@ from django.utils import timezone from styleguide_example.common.types import DjangoModelType - +from rest_framework.exceptions import ValidationError as DRFValidationError +from django.core.exceptions import ValidationError def model_update( *, instance: DjangoModelType, fields: List[str], data: Dict[str, Any], auto_updated_at=True @@ -69,13 +70,14 @@ def user_update(*, user: User, data) -> User: if "updated_at" in model_fields and "updated_at" not in update_fields: update_fields.append("updated_at") instance.updated_at = timezone.now() # type: ignore - - instance.full_clean() - # Update only the fields that are meant to be updated. - # Django docs reference: - # https://docs.djangoproject.com/en/dev/ref/models/instances/#specifying-which-fields-to-save - instance.save(update_fields=update_fields) - + try: + instance.full_clean() + instance.save(update_fields=update_fields) + + except ValidationError as e: + + raise DRFValidationError(e.message_dict) + for field_name, value in m2m_data.items(): related_manager = getattr(instance, field_name) related_manager.set(value)