How to show different inlines depending of current object field value

前端 未结 6 1469
不知归路
不知归路 2021-02-14 21:56

Given a model named MainModel and a RelatedModel, where the later has a ForeignKey field to MainModel:

class          


        
6条回答
  •  佛祖请我去吃肉
    2021-02-14 22:23

    @Yuji 'Tomita' Tomitayou the idea was good, i had the same but once trying, i realized you must also remove specific key from self.inlines because in change_view and add_view method self.get_inline_instances(request) is called before get_formsets(). Therefore i moved inlines handling to get_form() method.

    Here is how i sucessfully did it:

    class SampleAdmin(ModelAdmin):
        inlines = []
    
        def get_inlines(self):
            return [SampleInline, SampleInline2]
    
        def get_form(self, request, obj=None, **kwargs):
            # due to django admin form fields caching you must 
            # redefine inlines on every `get_form()` call
            if (obj): self.inlines = self.get_inlines()
            for inline in self.inlines:
                # Here change condition based on your needs and manipulate
                # self.inlines as you like (remove, change, etc). 
                # I used inline.__name__ to detect if this is correct inline 
                # for my obj
                if obj.CONDITION:
                    self.inlines.remove(inline)
            return super(SampleAdmin, self).get_form(request, obj, **kwargs)
    

提交回复
热议问题