Display user-friendly values of a ManyToManyRawIdWidget

 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
38
from django.contrib.admin.widgets import ManyToManyRawIdWidget
from django.utils.encoding import smart_unicode
from django.utils.html import escape

class VerboseManyToManyRawIdWidget(ManyToManyRawIdWidget):
    """
    A Widget for displaying ManyToMany ids in the "raw_id" interface rather than
    in a <select multiple> box. 
    Display user-friendly value like the ForeignKeyRawId widget
    """
    def __init__(self, rel, attrs=None):
        self._rel = rel
        super(VerboseManyToManyRawIdWidget, self).__init__(rel, attrs)

    def label_for_value(self, value):
        values = value.split(',')
        str_values = []
        key = self.rel.get_related_field().name
        for v in values:
            try:
                obj = self.rel.to._default_manager.using(self.db).get(**{key: v})
                # manage unicode error 
                x = smart_unicode(obj)
                # no HTML
                str_values += [escape(x)]
            except self.rel.to.DoesNotExist:
                str_values += [u'???']
        return u'&nbsp;<strong>%s</strong>' % (u',&nbsp;'.join(str_values))


class MyAdmin(admin.ModelAdmin):
     ...
     def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name in ('groups',):
            kwargs.pop('request', None)
            kwargs['widget'] = VerboseManyToManyRawIdWidget(db_field.rel)
            return db_field.formfield(**kwargs)
        return super(MyAdmin,self).formfield_for_dbfield(db_field,**kwargs)

More like this

  1. Link raw_id_fields (both ForeignKeys and ManyToManyFields) to their change pages by EmilStenstrom 2 years, 7 months ago
  2. ManyToManyField no syncdb by powerfox 4 years, 4 months ago
  3. ForeignKey filterspec by luc_j 2 years, 8 months ago
  4. Admin Hack: Quick lookup of GenericForeignKey id by ContentType by adnan 4 years, 8 months ago
  5. django-mptt enabled FilteredSelectMultiple m2m widget by anentropic 3 years, 6 months ago

Comments

luc_j (on September 13, 2010):

Updated: Use smart_unicode rather than unicodedata.normalize

#

EmilStenstrom (on October 4, 2010):

I've posted an updated version of this widget here: http://djangosnippets.org/snippets/2217/

It adds links to each object's change page, and also works for ForeignKeys.

#

(Forgotten your password?)