【问题标题】:Use the more descriptive name in Django choices在 Django 选项中使用更具描述性的名称
【发布时间】:2020-12-28 13:02:48
【问题描述】:

我正在创建一个电子商务应用程序,但遇到了一个问题,我似乎无法让 Django 显示元组中的第二项。比如我的models.py...

class ProductItem(models.Model):
    OPTIONS = [
        ("RED","Red"),
        ("DBL","Dark Blue"),
        ("LBL","Light Blue"),
        ("DGR","Dark Green"),
        ("LGR","Light Green"),
        ("PNK","Pink"),
        ("GRY","Gray"),
        ("BLK","Black"),
        ("BRO","Brown"),
        ("WHT","White"),
        ("MAR","Marroon"),
        ("ORG","Orange"),
        ("BEG","Beige"),
        ("GLD","Gold"),
        ("SLV","Silver"),
        ("MLT", "MultiColour")
    ]
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    colour = models.CharField(choices=OPTIONS, default="BLK", max_length=20)
    quantity_available = models.PositiveIntegerField()

    def __str__(self):
        return f"{self.product} -> ({self.colour})"

在我看来.py...

def product_detail(request, id):
    products = Product.objects.filter(id=id).first()
    context={
        "product": products, 
        "options": ProductItem.objects.filter(product=products)
    }
    return render(request, "store/product_detail.html", context)

最后在我的模板中...

<select id="style">
   {% for option in options %}
        <option value="{{option.colour}}">{{option.colour]}}</option>
   {% endfor %}
</select>

在这种情况下,我们假设应该出现深蓝色。 我希望值是 DBL,正如我在 CHOICES 中提到的那样,并希望为用户显示 Dark Blue。 但在这种情况下,只显示DBL,这是我不想要的。 关于如何解决这个问题的任何想法?

谢谢!

【问题讨论】:

    标签: python django django-models django-views django-templates


    【解决方案1】:

    您可以使用get_<i>fieldname</i>_display() method [Django-doc]。所以对于colour 字段,即get_colour_display()

    <select id="style">
        {% for option in options %}
            <option value="{{ option.colour }}">{{ option.get_colour_display }}</option>
        {% endfor %}
    </select>

    【讨论】:

      猜你喜欢
      • 2012-03-01
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 2010-12-01
      相关资源
      最近更新 更多