views:

38

answers:

2

For the following code:

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    author = models.ForeignKey(Author)
    title = models.CharField(max_length=100)

class BookInline(admin.TabularInline):
    model = Book
    extra = 1

class AuthorAdmin(admin.ModelAdmin):
    inlines = [
        BookInline,
    ]

If I add a new Author through the admin, it will show me one Book entry because of the extra=1. If I edit an existing Author who has one Book, the admin will show the existing book and a new field to add a new one.

Current behaviour with Edit an Author who has 1 book:

Author: Someone
Book: The book title
Book #2:

Wanted behaviour with Edit an Author who has 1 book:

Author: Someone
Book: The book title

Is it possible in the admin.pyfor the above code to check whether I'm in the add or edit page? My goal is to set extra=1 for add and extra=0 for edit.

A: 

Perhaps you could have a function that returned a conditional value based on the quantity of Books for the given inline?

Something like...

class BookInline(admin.TabularInline):
    model = Book
    extra = extra_count

    def extra_count(self):
        if self.model.objects.count > 0:
            return 1
        else
            return 0

This is sort of an odd behavior you're requesting. Just out of curiosity, why exactly do you not want it to show an extra entry row in edit mode?

T. Stone
From the current requirement 1 row is needed but the model has been coded to anticipate future requirement changes. I'm not sure if it's a good practice but that's the way it is at the moment.
Thierry Lam
+1  A: 

Nevermind, I just used max_num=1 instead of extra=1, it solves my issue. Here's the reference.

Thierry Lam