CodexBloom - Programming Q&A Platform

Django Admin Inline Validation: How to Prevent Saving Invalid Related Models

👀 Views: 68 💬 Answers: 1 📅 Created: 2025-06-12
django admin validation models Python

I'm working through a tutorial and I'm having a hard time understanding I've been working on a Django application (version 3.2) where I need to implement validation for inline models in the admin interface. I have two models, `Author` and `Book`, where a book must have a valid author assigned before it can be saved. Currently, when trying to save a book with an invalid author (like an author without a name), the admin interface allows it, and I end up with incomplete data in the database. Here are the relevant model definitions: ```python class Author(models.Model): name = models.CharField(max_length=100, blank=False) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE) ``` In my `admin.py`, I’m using an inline model for `Book` within the `AuthorAdmin`: ```python class BookInline(admin.TabularInline): model = Book extra = 1 class AuthorAdmin(admin.ModelAdmin): inlines = [BookInline] admin.site.register(Author, AuthorAdmin) ``` What I’ve tried so far is overriding the `save_model` method in the `BookInline` to raise a `ValidationError` if the author does not have a name: ```python from django.core.exceptions import ValidationError class BookInline(admin.TabularInline): model = Book extra = 1 def save_related(self, request, formset, change): for form in formset: if form.instance.author and not form.instance.author.name: raise ValidationError('Author must have a name.') super().save_related(request, formset, change) ``` However, I'm getting an error that says `ValidationError` is not defined in `admin.py`. I also want to make sure that this validation properly shows up in the admin interface and prevents the form from being submitted if the author is invalid. How can I correctly implement this validation in the Django admin for inline models? What steps do I need to take to ensure that it works as expected? Thanks for your help in advance! This is part of a larger desktop app I'm building. Any ideas how to fix this?