4

ModelMultipleChoiceField is displayed in a template is a list of checkboxes with unicode of representation of corresponding objects. How do I display ModelMultipleChoiceField in table form with arbitrary fields in arbitrary columns? For example:

[x] | obj.name | obj.field1

zer0stimulus
  • 22,306
  • 30
  • 110
  • 141

2 Answers2

7

The field class has a method label_from_instance that controls how the object is represented. You can overwrite it in your own field class:

from django.forms.models import ModelMultipleChoiceField

class MyMultipleModelChoiceField(ModelMultipleChoiceField):

    def label_from_instance(self, obj):
        return "%s | %s" % (obj.name, obj.field1)

You should also be able to output some html with that...

Slipstream
  • 13,455
  • 3
  • 59
  • 45
Bernhard Vallant
  • 49,468
  • 20
  • 120
  • 148
4

I returned obj itself in my customized MultipleModelChoiceField

from django.forms.models import ModelMultipleChoiceField

class MyMultipleModelChoiceField(ModelMultipleChoiceField):

def label_from_instance(self, obj):
    return obj

In my template I have

<table>
    {% for checkbox in form.MyField %}
        <tr>
        <td>
        {{ checkbox.tag }}
        </td>
        <td>
        {{ checkbox.choice_label.field1 }}
        </td>
        <td>
        {{ checkbox.choice_label.field2}}
        </td>
        </tr>
    {% endfor %}
</table>

The field1 and field2 are fields of the object returned from label_from_instance. These programs display all choices in a table where each row is an object/record with a checkbox.

Yang Liu
  • 85
  • 7