Login

Display user-friendly values of a ManyToManyRawIdWidget

Author:
luc_j
Posted:
July 15, 2010
Language:
Python
Version:
1.2
Tags:
django-admin ManyToManyField rawid
Score:
3 (after 3 ratings)

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

 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. DefaultValueWidget by miracle2k 7 years, 8 months ago
  2. Currency Fields with newforms by sago 7 years, 11 months ago
  3. Honeypot Field by SmileyChris 8 years ago
  4. DisableableSelectWidget by notanumber 2 years, 10 months ago
  5. Datetime widget by pigletto 7 years, 7 months ago

Comments

luc_j (on September 13, 2010):

Updated: Use smart_unicode rather than unicodedata.normalize

#

Please login first before commenting.