Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display field other than __str__

I am trying to display the version field from the below model other than the default str which is field2_name:

Note: This SO link Displaying a specific field in a django form might be more than I need but I am not 100% sure. I tried to implement this but was not successful.

Also note that I tried the example at https://docs.djangoproject.com/en/1.10/ref/forms/fields/ but was not able to get it to work

Model (Generic names):

class CodeVersion(models.Model):
field1= models.ForeignKey(SomeOtherModel, on_delete=models.CASCADE)
field2_name = models.CharField(max_length=256)
field3_description = models.CharField(max_length=1000, blank=True)
version = models.PositiveIntegerField()

def __str__(self):
  return self.field2_name

Form:

class VersionsForm(forms.Form):

code_versions = forms.ModelChoiceField(queryset=CodeVersion.objects.none())

def __init__(self, SomeOtherModel_id):
   super(VersionsForm, self).__init__()
   self.fields['infocode_versions'].queryset = CodeVersion.objects.filter(SomeOtherModel_id=SomeOtherModel_id)

This works - it returns field2_name as it is supposed to.

How do I return version instead - what is the simplest way?

Any help or guidance is appreciated.

like image 233
beginAgain Avatar asked Dec 05 '25 06:12

beginAgain


1 Answers

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
like image 166
knbk Avatar answered Dec 07 '25 20:12

knbk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!