'Django override the error message that Django shows for UniqueConstraint error?
I want to customize Meta class constraints default message. Here is my model that I have been working out.
class BusRoute(BaseModel):
route = models.ForeignKey(Route, on_delete=models.PROTECT)
shift = models.ForeignKey(
Shift,
null=True,
on_delete=models.PROTECT
)
journey_length = models.TimeField(null=True)
class Meta:
default_permissions = ()
verbose_name = 'Bus Route'
verbose_name_plural = 'Bus Routes'
constraints = [
models.UniqueConstraint(
fields=['route', 'shift'],
name='unique_bus_company_route'
)
]
The default constraint error message is as following
Bus Route with this Shift already exists.
Is there any way out I can customize this constraint message to something like,
Bus Route and shift already in use please validate again
Solution 1:[1]
I just figured out how to create a custom UniqueConstraint error while using the CBV CreateView and the form ModelForm.
On the ModelForm I added this:
def validate_unique(self):
"""
Call the instance's validate_unique() method and update the form's
validation errors if any were raised.
"""
exclude = self._get_validation_exclusions()
try:
self.instance.validate_unique(exclude=exclude)
except ValidationError as e:
error = {'__all__': "Custom error message."}
self._update_errors(error)
This is mostly the class's default code, except I edited the contents in the except block.
Solution 2:[2]
You could use a try and except statement to catch the UniqueConstraint error, and raise your own instead. As far as I know, django doesn't have any provisions to override the unique constraint error directly, so this may be considered as best practice.
Implementation of the idea:
bus_route = BusRoute(**field_data)
try:
bus_route.save()
except IntegrityError as err:
raise CustomException('CUSTOM ERROR MESSAGE')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pusher91 |
Solution 2 | Aryan Iyappan |