Hello fellow Django enthusiasts,
I’ve been trying to achieve a specific customization in the Django Admin regarding duplicate key errors, and I’m looking for some guidance or insights on how to best approach this.
I’m working on a project where I want to handle duplicate key errors in the Django Admin in a more user-friendly way. Specifically, I want to display a custom validation error message to the user when they attempt to save a record that would result in a duplicate key violation.
I’ve tried a few approaches, including overriding the save_model
method and raising a ValidationError
with my custom error message. However, in all attempts, I’ve encountered challenges like the default success message being displayed alongside the custom error message, the ValidationError
being raised to the user instead of being shown a validation error message, or the error not being handled at all.
I’m aiming to achieve the following:
- When a duplicate key error occurs, display my custom error message to the user (not the error page).
- Prevent the default success message from being shown.
The latest approach I’ve tried involves overriding the save_model
method to handle in the Django Admin.
Code (simplified):
def save_model(self, request, obj, form, change):
assert request.user.account is not None
obj.owner = request.user.account
try:
super().save_model(request, obj, form, change)
except IntegrityError as err:
if "identifier" in str(err):
raise ValidationError({"identifier": "This identifier is already in use."}) from err
raise err
While I’m able to catch the duplicate key error and raise a ValidationError
, the issue is that this error is being directly displayed to the user. And (in debug mode) I see the yellow error page with the following error message:
ValidationError at /admin/app/my_model/add/
{'identifier': ['This identifier is already in use.']}
I’d greatly appreciate any suggestions, advice, or alternative approaches you might have to achieve my goal. If anyone has successfully tackled a similar scenario or can shed light on how to suppress the default success message while showing only a custom error message for duplicate key errors, I’d be very grateful to learn from your experience.
Thank you in advance for your assistance and insights!
Best regards.