Skip to content

Instantly share code, notes, and snippets.

@bukowa
Last active February 7, 2023 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bukowa/728b6020e6b3fb6837961e680b2f2861 to your computer and use it in GitHub Desktop.
Save bukowa/728b6020e6b3fb6837961e680b2f2861 to your computer and use it in GitHub Desktop.
django constraint error message for field
from django.core.exceptions import ValidationError
from django.db import models
class ViolationFieldNameMixin:
"""
Mixin for BaseConstraint subclasses that builds custom
ValidationError message for the `violation_field_name`.
By this way we can bind the error to the field that caused it.
This is useful in ModelForms where we can display the error
message next to the field and also avoid displaying unique
constraint violation error messages more than once for the same field.
"""
def __init__(self, *args, **kwargs):
self.violation_field_name = kwargs.pop("violation_field_name", None)
self.violation_code = kwargs.pop("violation_code", None)
super().__init__(*args, **kwargs)
def validate(self, *args, **kwargs):
try:
value = super().validate(*args, **kwargs)
except ValidationError as e:
# Create a new ValidationError with the violation_field_name attribute as the key
e = ValidationError({self.violation_field_name: e})
# Set the error code to None
# See https://code.djangoproject.com/ticket/34319#ticket
e.code = self.violation_code
raise e
return value
def deconstruct(self):
path, args, kwargs = super().deconstruct()
kwargs["violation_field_name"] = self.violation_field_name
kwargs["violation_code"] = self.violation_code
return path, args, kwargs
def __eq__(self, other):
return (
super().__eq__(other)
and self.violation_field_name == getattr(other, "violation_field_name", None)
and self.violation_code == getattr(other, "violation_code", None)
)
class UniqueConstraint(ViolationFieldNameMixin, models.UniqueConstraint):
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment