- Author:
- chris.dickinson
- Posted:
- January 5, 2009
- Language:
- Python
- Version:
- 1.0
- Score:
- 0 (after 0 ratings)
There are several nice ModelAdmin subclasses that provide useful functionality (such as django-batchadmin, django-reversion, and others), but unfortunately a ModelAdmin can really only subclass one at a time, making them mutually exclusive.
This snippet aims to make mixing these classes in as easy as possible -- you can inherit your model admin from it, add a tuple of mixins, and it will dynamically change the inheritance tree to match. This isn't guaranteed to work with all ModelAdmins, but so long as the mixins play nice with django modeladmin they should work.
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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
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?
#
I think this snipper was not copied completly... I am missing a MixinModelAdmin Class somewhere
#
Please login first before commenting.