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

Time:09-08

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?

CodePudding user response:

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',)
  • Related