How can I change display of visible value in django form?

Question:

I have Django model from external python library:

class Item(models.Model):
  name = models.CharField(...)
  serial = models.CharField(...)

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

I can’t change this model, but I want to display on my form widget with value as
"Item Name (Item Serial)"

My form is very simple:

# forms.py
class InventoryForm(forms.ModelForm):

    class Meta:
        model = Inventory
        fields = ('title', 'item',)
# models.py

class Inventory(models.Model):
  title = models.CharField(...)
  item = models.ForeignKey(to='Item'...)
...

Can I change display of visible value?

Asked By: Roman Sokolov

||

Answers:

ModelChoiceField, the form field used for selecting a model, supports overriding label_from_instance (see the linked docs).

So, subclass a choice field with that…

class ItemChoiceField(forms.ModelChoiceField):
   def label_from_instance(self, obj):
        return f"{obj.name} ({obj.serial})"

… and hook it up to your form:

# forms.py
class InventoryForm(forms.ModelForm):
    item = ItemChoiceField(queryset=Item.objects.all())

    class Meta:
        model = Inventory
        fields = ('title', 'item',)
Answered By: AKX
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.