【问题标题】:How to display a dropdown field __str__ in Django templates?如何在 Django 模板中显示下拉字段 __str__?
【发布时间】:2017-07-02 07:19:57
【问题描述】:

我有一个 ModelForm,我可以在其中显示作为下拉列表 ({{ form.auto_part }}) 或 value 的外键字段或作为数字 ({{ form.auto_part.value }}) 的外键字段的 ID .但我想显示外键字段的__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)

【问题讨论】:

    标签: python django forms templates


    【解决方案1】:

    使用 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']
    

    【讨论】:

    • 你能举个例子吗?
    猜你喜欢
    • 2020-05-15
    • 1970-01-01
    • 2020-10-31
    • 2020-12-23
    • 2020-12-10
    • 2013-05-31
    • 2021-12-11
    • 2020-11-08
    • 1970-01-01
    相关资源
    最近更新 更多