2017-02-14 7 views
1

私は、ドロップダウンリスト({{ form.auto_part }})またはvalue、または番号({{ form.auto_part.value }})になる外部キーフィールドのIDとして表示される、外部キーフィールドを表示できるModelFormを持っています。しかし、私は__str__のforeignkeyフィールドの値を示したいと思います。どうやってやるの? ModelChoiceFieldを使用して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

あなたがこれを行うことができるようにする必要があり、それがデフォルトの動作です。ラベルを設定できます。

は、参照してください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

答えを更新しました。 –

関連する問題