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
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With