Making inlines conditional in the Django admin

后端 未结 8 2347
长发绾君心
长发绾君心 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:30

    As of Django 2.2.2 (current latest version as of this writing), I would use the solution provided earlier by @aggieNick02, which is to override get_inline_instances shown below.

    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)
    

    I'm posting this new answer because as of April 17th, 2019 in this commit, it looks like the future recommended way to do this would be to instead override the get_inlines method. So in later versions, the solution to this could look like the code below, which allows you to specify different sets of inlines and use them based on a condition.

    class ThingAdmin(admin.ModelAdmin):
        model = Thing
    
        inlines = [inline]
        other_set_of_inlines = [other_inline]
    
        def get_inlines(self, request, obj):
            if obj.date > datetime.date(2012, 1, 1):
                return self.inlines
            else:
                return self.other_set_of_inlines
    

提交回复
热议问题