views:

132

answers:

1

Hello,

I have an app using raw_id on both ForeignKeyField and ManyToManyField. The admin displays the value of the foreign key on the right of the edit box.

Unfortunatey, it doesn't work with ManyToMany. I've checked the code and I think that it is the normal behavior. However I would like to know if someone has an easy tip to change this behavior?

Thanks in advance

Update: I've tried to subclass the ManyToManyRawIdWidget but I don't know how to say that the raw_id_fields should use my custom widget. formfield_overrides doesn't seem to work with raw_id fields

+1  A: 

Finally I succeed to make it working.

from django.contrib.admin.widgets import ManyToManyRawIdWidget

class VerboseManyToManyRawIdWidget(ManyToManyRawIdWidget):
    def __init__(self, rel, attrs=None):
        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})
                str_values += [escape(u'%s' % obj)]
            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 ('foo', 'bar'):
            try:
                del kwargs['request']
            except KeyError:
                pass
            kwargs['widget'] = VerboseManyToManyRawIdWidget(db_field.rel)
            return db_field.formfield(**kwargs)
        return super(MyAdmin,self).formfield_for_dbfield(db_field,**kwargs)

Unfortunately, I've spend a bounty for nothing ;-)

UPDATE: I've created a django snippet for this : http://djangosnippets.org/snippets/2108/

luc