- Author:
- anentropic
- Posted:
- October 26, 2009
- Language:
- Python
- Version:
- 1.1
- Score:
- 0 (after 0 ratings)
This builds on a couple of other people's hacks to effectively manage django-mptt models via the admin.
One problem you find is if you use the actions drop-down menu to ‘delete selected’ items from your mptt model… the bulk actions bypass the model’s delete method so your left/right values for the tree aren’t updated.
What you need is a way to automatically rebuild the tree after a bulk action.
This code provides that facility.
Full details on my blog: http://anentropic.wordpress.com/2009/10/26/
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 33 34 35 36 37 | from django.conf import settings
from django.contrib.admin import actions
from django.utils.translation import ugettext_lazy, ugettext as _
from feincms.admin import editor
"""
For this hack to work the django-mptt managers.py has to have been patched:
http://code.google.com/p/django-mptt/issues/detail?id=13
"""
def delete_selected_tree(modeladmin, request, queryset):
return_val = actions.delete_selected(modeladmin, request, queryset)
if return_val is None:
# this means deletion was completed
tree_manager = getattr(modeladmin.model._meta,'tree_manager_attr','tree')
tree = getattr(modeladmin.model,tree_manager)
tree.rebuild()
return return_val
delete_selected_tree.short_description = ugettext_lazy("Delete selected %(verbose_name_plural)s")
class MPTTModelAdmin(editor.TreeEditor):
# see: http://magicrebirth.wordpress.com/2009/08/18/django-admin-and-mptt-2/
# this extends the method already found in (FeinCMS) TreeEditor class
def _actions_column(self, obj):
actions = super(MPTTModelAdmin, self)._actions_column(obj)
actions.insert(0,
u'<a title="%s" href="add/?%s=%s"><img src="%simg/admin/icon_addlink.gif" alt="%s" /></a>' % (getattr(self.model._meta,'parent_attr','parent'), obj.pk, 'Add child', settings.ADMIN_MEDIA_PREFIX, _('Add child'))
)
actions.insert(0,
u'<a title="%s" href="%s" target="_blank"><img src="%simg/admin/selector-search.gif" alt="%s" /></a>' % (obj.get_absolute_url(), 'View on site', settings.ADMIN_MEDIA_PREFIX, _('View on site'))
)
return actions
def get_actions(self, request):
actions = super(MPTTModelAdmin, self).get_actions(request)
actions['delete_selected'] = (delete_selected_tree, 'delete_selected', delete_selected_tree.short_description) # replace the default delete action
return actions
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
Please login first before commenting.