Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Let's say our model is this:

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)

,

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
    ]
like image 632
Kaan Avatar asked Oct 17 '16 09:10

Kaan


1 Answers

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
like image 131
e4c5 Avatar answered Sep 23 '22 18:09

e4c5