Django: setting display ModelMultipleChoiceField

ModelMultipleChoiceField is displayed in the template - this is a list of flags with a Unicode representation of the corresponding objects. How to display ModelMultipleChoiceField in the form of a table with arbitrary fields in arbitrary columns? For instance:

[x] | obj.name | obj.field1

+2
source share
2 answers

The field class has a label_from_instance method that controls the presentation of the object. 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 this ...

+4
source

I returned the object itself in my configured MultipleModelChoiceField

from django.forms.models import ModelMultipleChoiceField

Class MyMultipleModelChoiceField (ModelMultipleChoiceField):

 def label_from_instance(self, obj): return obj 

I have in the template

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

Field1 and field2 are the fields of the object returned from label_from_instance. These programs display all selections in a table, where each line represents an object / record with a checkbox.

0
source

Source: https://habr.com/ru/post/944261/


All Articles