Python 如何在Django模板中显示下拉字段?

Python 如何在Django模板中显示下拉字段?,python,django,forms,templates,Python,Django,Forms,Templates,我有一个ModelForm,我可以显示一个foreignkey字段,它是一个下拉列表({{form.auto\u part}}),或者值或作为数字出现的foreignkey字段的ID({form.auto\u part.value})。但是我想显示foreignkey字段的\uuu str\uu值。我该怎么做 forms.py class AddCostPriceForm(forms.ModelForm): class Meta: model = Product

我有一个ModelForm,我可以显示一个foreignkey字段,它是一个下拉列表(
{{form.auto\u part}}
),或者
值或作为数字出现的foreignkey字段的ID(
{form.auto\u part.value}
)。但是我想显示foreignkey字段的
\uuu str\uu
值。我该怎么做

forms.py

class AddCostPriceForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['auto_part', 'cost_price']
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)
型号.py

class AddCostPriceForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['auto_part', 'cost_price']
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)

使用ModelChoiceField应该允许您这样做,这是默认行为。您可以配置标签

例如:

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

使用ModelChoiceField应该允许您这样做,这是默认行为。您可以配置标签

例如:

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

你能举个例子吗?