[Django]-Display field other than __str__

7👍

From the ModelChoiceField docs:

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. This method will receive a model object, and should return a string suitable for representing it. For example:

from django.forms import ModelChoiceField

class MyModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "My Object #%i" % obj.id
👤knbk

3👍

If I got your question correctly you could change object string representation

def __str__(self):
  return str(self.version)

You could then inherit ModelChoiceField and override label_from_instance method

or even monkey patch it like this

self.fields['field_name'].label_from_instance = self.label_from_instance

@staticmethod
def label_from_instance(self):
    return str(self.value)

1👍

The simplest way in this case that I struggled myself:

under your line of code

self.fields['infocode_versions'].queryset = CodeVersion.objects.filter(SomeOtherModel_id=SomeOtherModel_id)

insert this:

self.fields["infocode_versions"].label_from_instance = lambda obj: "%s" % obj.version

0👍

In one line :

self.fields['code_versions'].label_from_instance = lambda obj: f"{obj.version}"

Complete example

class VersionsForm(forms.Form):

    code_versions = forms.ModelChoiceField(queryset=CodeVersion.objects.none())
    
    def __init__(self, SomeOtherModel_id):
       super().__init__()
       self.fields['code_versions'].queryset = CodeVersion.objects.filter(SomeOtherModel_id=SomeOtherModel_id)
       self.fields['code_versions'].label_from_instance = lambda obj: f"{obj.version}"

Leave a comment