Django Admin 在编辑时将 extra 设置为 0

标签 django django-admin

设置 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/

相关文章:

python - 启动 Django 项目无效语法

python - 如何使用 pre_save 信号检查 django admin 中是否选择了新文件?

Django 管理操作日志记录 : how to display initial and result value of field changes?

python - 为什么我们需要使用rabbitmq

django - 如何将具有 ManytoMany 字段的 Django 模型转换为 elasticsearch_dsl DocType 类?

python - 无法在heroku上恢复postgres转储

django - 在 Django 模板中使用 JSON

python - 如何修复 "django-admin not recognized"

python - 将 Django 中的 DateTimeField 转换为 Unix 时间

django - 如何在 Django 管理员的索引中分隔不同模块中的模型?