Making inlines conditional in the Django admin

后端 未结 8 2324
长发绾君心
长发绾君心 2021-02-07 21:45

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.da         


        
8条回答
  •  [愿得一人]
    2021-02-07 22:32

    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)
    

提交回复
热议问题