Reputation: 23666
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
Upvotes: 4
Views: 3559
Reputation: 95
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.
Upvotes: 4
Reputation: 50796
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...
Upvotes: 8