Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django modelAdmin __init__ and inlines

Hey, I'm fairly new to Django, and I'm looking to edit admin class variables dynamically (The full idea is to hide inlines on adding and only show on editing, but I'm distilling the issue here).

Could someone explain why this doesn't work?

class dbTablePermissionInline(admin.TabularInline):
    model = dbPermission

class adminDbTable(admin.ModelAdmin):

    inlines = [
        dbTablePermissionInline,
    ]

    def __init__(self, *args, **kwargs):
        super(adminDbTable,self).__init__(*args, **kwargs)
        self.inlines = []

when I throw an assert (assert False, self.inlines) above self.inlines = [] it correctly shows the inlines, but the inlines are still appearing? Even though I've emptied the list.

Helps appreciated! Thanks.

like image 684
hcliff Avatar asked Feb 14 '26 05:02

hcliff


2 Answers

The ModelAdmins __init__ method creates instances of the inline admin classes and adds them to self.inline_instances. So setting self.inlines to another value afterwards doesn't change anything. You should find this post, that deals with a similiar problem very helpful!

It also makes no sense to set values like that in __init__, since the Modeladmin instance is created once and may persist for a lot more than one request!

like image 168
Bernhard Vallant Avatar answered Feb 16 '26 23:02

Bernhard Vallant


I would suggest making a custom template which hides inlines when the operation is "create new foo".

Admin templates are very easy to override globally or per-object. It is a lot nicer than overriding ModelAdmin methods and properties in __init__().

like image 23
Paulo Scardine Avatar answered Feb 16 '26 23:02

Paulo Scardine