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
]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With