I have the following code in one of the classes related to the admin page:
def save_model(self, request, obj, form, change):
if change:
if form.initial['delivered'] != form.cleaned_data['delivered']:
for line in obj.lines.all():
book = line.book
if not book.is_available and not obj.delivered:
raise ValidationError('Error')
if obj.delivered:
number = line.book.number + 1
line.book.is_available = True
else:
number = book.number - 1
if not number:
book.is_available = False
line.book.number = number
line.book.save()
obj.save()
return super().save_model(request, obj, form, change)
The problem is that when the code reaches the raise ValidationError('Error') line and is executed, it doesn't show the error on the page and shows it like django debug errors, and this error is displayed only when DEBUG=True. How can I show this error like the django admin form errors?
I also tried this code with django signals but it had the same result.
Only when I wrote a class form myself and gave it to the admin class, it displayed the error correctly, but I cannot implement the conditions here in the form class. Is there a way to fix it in the save_model?
you may try with (not tested):