2017-02-14 58 views
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) 

回答

0

使用ModelChoiceField應該讓你做到這一點,這是默認的行爲。您可以配置標籤。

https://docs.djangoproject.com/en/1.10/ref/forms/fields/#modelchoicefield

例子:

class AddCostPriceForm(forms.ModelForm): 
    auto_part = forms.ModelChoiceField(queryset=AutoPart.objects.all()) 
    class Meta: 
     model = Product 
     fields = ['auto_part', 'cost_price'] 
+0

能否請你舉個例子? – MiniGunnR

+0

我更新了我的答案。 –

相關問題