Making inlines conditional in the Django admin

2019-03-25 10:24发布

I have a model that I want staff to be able to edit up to the date for the event. Like this:

class ThingAdmin(admin.ModelAdmin):
    model = Thing

    if obj.date < today: #Something like that
        inlines = [MyInline,]

The problem is, I don't have access to the obj instance at this level. I've tried overriding get_formset(), but didn't get anywhere.

Please advise?

7条回答
叛逆
2楼-- · 2019-03-25 11:11

The most turnkey way to do this now is to override and super call to get_inline_instances.

class ThingAdmin(models.ModelAdmin):
    inlines = [MyInline,]

    def get_inline_instances(self, request, obj=None):
        unfiltered = super(ThingAdmin, self).get_inline_instances(request, obj)
        #filter out the Inlines you don't want
        keep_myinline = obj and obj.date < today
        return [x for x in unfiltered if not isinstance(x,MyInline) or keep_myinline]

This puts MyInline in when you want it and not when you don't. If you know the only inline you have in your class is MyInline, you can make it even simpler:

class ThingAdmin(models.ModelAdmin):
    inlines = [MyInline,]

    def get_inline_instances(self, request, obj=None):
        if not obj or obj.date >= today:
            return []
        return super(ThingAdmin, self).get_inline_instances(request, obj)
查看更多
登录 后发表回答