Play nice with ModelAdmin mixins

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
    def generate_mixin_chain(self):
        mixins = []
        cursor = self.__class__
        while cursor is not ModelAdmin and cursor is not None:
            if hasattr(cursor, 'mixins'):
                mixins += [mixin for mixin in cursor.mixins if mixin not in mixins]
            cursor = cursor.__base__

        mixin_len = len(mixins)
        if mixin_len > 0:
            for index, mixin in enumerate(mixins):
                target = ModelAdmin
                if index != (mixin_len-1):
                    target = mixins[index+1]
                mixin.__bases__ = (target,)
            MixinModelAdmin.__bases__ = (mixins[0],)


# example usage:

class MyModelAdmin(MixinModelAdmin):
    """ 
        The resultant inheritance tree will look like so: 
        ModelAdmin
        DispatchableModelAdmin
        WidgetModelAdmin
        MixinModelAdmin
        MyModelAdmin

        where ModelAdmins subclass the ModelAdmin directly above them.
    """
    mixins = (WidgetModelAdmin, DispatchableModelAdmin, )

More like this

  1. Django Admin CSV Export Mixin by Ceran 1 year ago
  2. Ordered items in the database by Leonidas 6 years, 11 months ago
  3. Custom Django manager that excludes subclasses by sciyoshi 5 years, 8 months ago
  4. View mixin and utils to generate PDF documents from html using xhtml2pdf by frankban 2 years, 7 months ago
  5. Django Admin Replacer Code by riccardodivirgilio 3 years, 5 months ago

Comments

carljm (on January 5, 2009):

Ok, so I haven't played with this and am probably missing something, but: what advantage does all this have over Plain Old Multiple Inheritance? Multiple inheritance works just fine for me in most cases (as long as super() is used properly for calling up the tree), and I've definitely used it for Models; does ModelAdmin break it in some way that this fixes?

#

digi604 (on January 29, 2009):

I think this snipper was not copied completly... I am missing a MixinModelAdmin Class somewhere

#

(Forgotten your password?)