Django Admin Customization: How to Properly Override Default Form Behavior for Admin Inline Models
I'm stuck on something that should probably be simple. I tried several approaches but none seem to work... I'm working on a Django application (version 3.2) where I need to customize the admin interface for an inline model. I have a `Book` model that has a foreign key to an `Author` model, and I want to ensure that when adding or editing the `Book` inline in the `Author` admin, the `ISBN` field is generated automatically if left blank. I've tried overriding the `InlineFormSet`'s `save_new` method to set the `ISBN` if it's not provided, but I'm running into issues where the ISBN sometimes gets overwritten with an empty string, which leads to validation errors. Here's what I've implemented so far: ```python from django import forms from django.contrib import admin from .models import Author, Book class BookInlineForm(forms.ModelForm): class Meta: model = Book fields = '__all__' def save(self, commit=True): book = super().save(commit=False) if not book.isbn: book.isbn = self.generate_isbn() # Custom method to generate an ISBN if commit: book.save() return book class BookInline(admin.TabularInline): model = Book form = BookInlineForm class AuthorAdmin(admin.ModelAdmin): inlines = [BookInline] admin.site.register(Author, AuthorAdmin) ``` However, I'm getting the following behavior when trying to save a new book without an ISBN: `django.db.utils.IntegrityError: NOT NULL constraint failed: myapp_book.isbn`. I suspect this is because the `ISBN` field is required in the model, and my logic to generate it isnβt effectively capturing the absence of an existing value before the save operation completes. How can I adjust my approach to ensure that the ISBN is generated correctly without running into integrity errors? Is there a more Django-esque way to handle this, perhaps leveraging signals or overriding a different method? Any advice would be greatly appreciated! What am I doing wrong? Any ideas what could be causing this?