2

I'm attemping to add copies of a book through a books admin page.

Inside models.py I have:

class Book(models.Model):
    ...

class BookCopy(models.Model):
    book = models.ForeignKey(
        'Book',
        related_name='copies',
        on_delete=models.CASCADE
    )
    # No additional fields here



class BookCopyInline(admin.StackedInline):
    model = BookCopy
    can_delete = False
    verbose_name_plural = 'copies'

Inside admin.py I have the following:

class BookCopyInline(admin.StackedInline):
    model = BookCopy
    can_delete = False
    verbose_name_plural = 'copies'


@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    inlines = (BookCopyInline,)



@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    model = Book
    list_display = ('isbn', 'title', 'subtitle')
    prepopulated_fields = {'slug': ('title',)}
    inlines = (BookCopyInline,)

I'd like to be able to add book copies inside the Books Admin page. But since the BookCopy model defines no additional fields the instances are never saved.

Adding a field to BookCopy and filling that in each time allows BookCopies to be created as normal, but I don't require any additional fields right now.

The image below demonstrates the issue I'm facing, new rows can be added, but when save is clicked, no BookCopies are created

enter image description here

Is there a way to have the admin save the instances regardless?

Jack Evans
  • 1,697
  • 3
  • 17
  • 33
  • I would suggest that you tailor your database to your current needs i.e. a simple `PositiveIntegerField` on the `Book` model. Database migrations in Django are very powerful and intuitive. – demux Dec 03 '17 at 00:31
  • 2
    I ran into the same issue when I stumbled upon this question. I found an answer here: https://stackoverflow.com/questions/34355406/django-admin-not-saving-pre-populated-inline-fields-which-are-left-in-their-init TLDR: the answer lies in the `ModelForm.has_changed` method. – modulitos May 08 '19 at 20:51

0 Answers0