Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: customizing display of ModelMultipleChoiceField

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

like image 780
zer0stimulus Avatar asked Oct 23 '25 16:10

zer0stimulus


2 Answers

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...

like image 179
Bernhard Vallant Avatar answered Oct 25 '25 15:10

Bernhard Vallant


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.

like image 32
Yang Liu Avatar answered Oct 25 '25 15:10

Yang Liu