设置 extra = 1
在我的模型中总是显示 1 个空字段。插入新项目时没问题,但我不想在编辑时显示额外的空字段。我怎样才能做到这一点?
假设我们的模型是这样的:
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
]
最佳答案
覆盖 get_extra方法而不是为额外的类成员设置值。
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):
就像是:
def get_extra(self, request, obj=None, **kwargs):
if obj.bar_set.count() :
return 0
else:
return 1
关于Django Admin 在编辑时将 extra 设置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40083026/