Login

Admin related widget wrapper with edit / delete link (python model admin)

Author:
nasp
Posted:
October 7, 2011
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

Here's the python code to produce an admin related widget with the edit and delete link also.

 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
from django.contrib import admin
from django.forms.widgets import SelectMultiple
from django.http import HttpResponse
from django.utils.html import escape, escapejs

#from the_module_where_you_stored_it import RelatedFieldWidgetWrapper

class RelatedWidgetWrapperAdmin(admin.ModelAdmin):

    def formfield_for_dbfield(self, db_field, **kwargs):
        formfield = super(cls, self).formfield_for_dbfield(db_field, **kwargs)
        if (formfield and
            isinstance(formfield.widget, admin.widgets.RelatedFieldWidgetWrapper) and
            not isinstance(formfield.widget.widget, SelectMultiple)):
            request = kwargs.pop('request', None)
            related_modeladmin = self.admin_site._registry.get(db_field.rel.to)
            can_change_related = bool(related_modeladmin and
                                      related_modeladmin.has_change_permission(request))
            can_delete_related = bool(related_modeladmin and
                                      related_modeladmin.has_delete_permission(request))
            widget = RelatedFieldWidgetWrapper.from_contrib_wrapper(formfield.widget,
                                                                    can_change_related,
                                                                    can_delete_related)
            formfield.widget = widget
        return formfield

    def response_change(self, request, obj):
        if '_popup' in request.REQUEST:
            pk_value = obj._get_pk_val()
            return HttpResponse('<script type="text/javascript">opener.dismissEditRelatedPopup(window, "%s", "%s");</script>' % \
            # escape() calls force_unicode.
            (escape(pk_value), escapejs(obj)))
        else:
            return super(cls, self).response_change(request, obj)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

benjaoming (on June 14, 2012):

Hi! Thanks for your work! I updated it for Django 1.4 and made an application:

github: django-relatedwidget

#

Please login first before commenting.