Django: access the parent instance from the Inline model admin

后端 未结 3 1632
独厮守ぢ
独厮守ぢ 2020-12-14 03:33

How can I access the parent instance from the inline model admin?

My goal is to override the has_add_permission function based on the status of the pare

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-14 03:36

    You only need to add obj parameter and check the parent model status

    class ChildInline(admin.TabularInline):
       model = Child
       form = ChildForm
    
       fields = (
        ...
        )
       extra = 0
       #You only need to add obj parameter 
       #obj is parent object now you can easily check parent object status
       def has_add_permission(self, request, obj=None):
            if obj.status == 1:
               return True
            else:
               return False
    
    
       class ParentAdmin(admin.ModelAdmin):
             inlines = [ChildInline,]
    

提交回复
热议问题