I have 4 classes like below:
from django.db import models
class A(models.Model):
title = models.CharField(max_length=100)
class B(models.Model):
title_b = models.CharField(max_length=100)
a = models.ForeignKey(A, on_delete=models.CASCADE)
class Meta:
constraints = [
models.UniqueConstraint(fields=['title_b'], name='unique_title_b')
]
class C(models.Model):
title_c = models.CharField(max_length=100)
a = models.ForeignKey(A, on_delete=models.CASCADE)
class D(models.Model):
title_d = models.CharField(max_length=100)
a = models.ForeignKey(A, on_delete=models.CASCADE)
All related classes are used as Inline model which described below:
from django.contrib import admin
class BInline(admin.TabularInline):
model = B
class CInline(admin.TabularInline):
model = C
class DInline(admin.TabularInline):
model = D
And Model Admin of class A is defined as
class AAdmin(admin.ModelAdmin):
inlines = [BInline, CInline, DInline]
As you can see class B has a constraint on title uniqueness. If I enter duplicate data for class B in admin panel, an Integrity Error is raised and error page with title IntegrityError at /app/A/81ac3366-4cdb-4cbb-a861-340ff188c760/change/
duplicate key value violates unique constraint “unique_title_b”
DETAIL: Key (title)=(TestDuplicate) already exists. is shown.
In order to show user a friendly message rather than this error page, I override save_related
method in class AAdmin
like below:
def save_related(self, request, form, formsets, change):
try:
with transaction.atomic():
super().save_related(request, form, formsets, change)
except IntegrityError as e:
self.message_user(request, 'A related model constraint was violated: {}'.format(e), level=messages.ERROR)
I expect that after overriding save_related
method, the error page doesn’t display anymore and user stays in the same change model page in admin panel; but error page still shows after I made these changes.
Can someone explain to me where did I go wrong in this?