[Fixed]-ModelChoiceField: displaying a list with attritbutes of the selected objects

1👍

Like mentioned in the documentation:

to_field_name

This optional argument is used to specify the field to use as the value of the choices in the field’s widget.

When you use last_name as to_field_name you will see it in the value attribute of option tag and not as the display:

<option value="obj1.last_name">Object1</option>

The documentation also mentions what you need to do in case you want to change the display of those options:

The __str__ (__unicode__ on Python 2) method of the model will be called to generate string representations of the objects for use in the field’s choices; to provide customized representations, subclass ModelChoiceField and override label_from_instance.

👤AKS

Leave a comment