1
我有一個ModelForm,可以顯示作爲下拉列表({{ form.auto_part }}
)或value
的外鍵字段或該外鍵字段的編號({{ form.auto_part.value }}
)。但我想顯示foreignkey字段的值__str__
。我怎樣才能做到這一點?如何在Django模板中顯示下拉字段__str__?
forms.py
class AddCostPriceForm(forms.ModelForm):
class Meta:
model = Product
fields = ['auto_part', 'cost_price']
models.py
class Product(Timestamped):
product_list = models.ForeignKey(List)
auto_part = models.ForeignKey(AutoPart)
quantity = models.SmallIntegerField()
unit = models.CharField(max_length=20, default='pcs')
cost_price = models.IntegerField(blank=True, null=True)
class AutoPart(Timestamped):
brand = models.ForeignKey(Brand)
auto_type = models.ForeignKey(AutoType)
part_no = models.CharField(max_length=50)
description = models.CharField(max_length=255)
def __str__(self):
return "{brand} {auto_type} - {part_no}".format(brand=self.brand, auto_type=self.auto_type, part_no=self.part_no)
能否請你舉個例子? – MiniGunnR
我更新了我的答案。 –