Skip to content
Advertisement

Django Admin set extra to 0 when editing

Setting extra = 1 in my model always shows a 1 empty field. It is OK while inserting a new item but I don’t want to show an additional empty field while editing. How can I do this?

models.py:

class Foo(models.Model):
    bar = models.ForeignKey(Bar, models.CASCADE, related_name='bars')
    title = models.CharField(_('Title'), max_length=255)
    body = models.TextField(_('Body'))
    __str__(self):
        return '%s' % (self.title)

admin.py:

class FooInline(admin.StackedInline):
    model = Foo
    extra = 1 #Also shows 1 extra empty field while editing.
              #I don't want to show if there is already a non-empty field

class FooAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('title',)}
    inlines = [FooInline]

Advertisement

Answer

Override the get_extra method instead of setting a value for extra class member.

Returns the number of extra inline forms to use. By default, returns the InlineModelAdmin.extra attribute.

Override this method to programmatically determine the number of extra inline forms. For example, this may be based on the model instance (passed as the keyword argument obj):

Something like:

def get_extra(self, request, obj=None, **kwargs):
    if obj.bar_set.count() :
        return 0
    else: 
        return 1
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement