簡體   English   中英

如何為每個 django model 選項分配不同的顏色

[英]How do I attribute different color for each of the django model choices

以下是我的models.py:

class Table(models.Model):
    choices = (
        ("BUY", "Buy"),
        ("HOLD", "Hold"),
        ("SELL", "Sell"),
    )

remarks = models.CharField(max_length=200, choices=choices, default="HOLD",  null=True)

有沒有辦法為每個選擇賦予不同的顏色? 例如,如果我選擇“購買”,它會在我的 html 頁面上顯示為藍色。

編輯:

這是我完整的models.py:

class Table(models.Model):
    choices = (
        ("BUY", "Buy"),
        ("HOLD", "Hold"),
        ("SELL", "Sell"),
    )

    name = models.CharField(max_length=200, null=True)
    date = models.DateTimeField(auto_now_add=False,  null=True, editable=True)
    buy_call = models.FloatField(null=True)
    target_price = models.FloatField(null=True)
    stop_loss = models.FloatField(null=True)
    remarks = models.CharField(max_length=200, choices=choices, default="HOLD",  null=True)
    sell_at = models.FloatField(null=True,blank=True)
    def __str__ (self):
        return self.name

這是我的views.py:

def table(request):
    table = Table.objects.all().order_by('-date')
    return render(request, 'scanner/table.html', {'table':table})

這是我的 html:

 <tbody>
{% for i in table %}
     <tr>
        <td>{{i.name}}</td>
        <td>{{i.date.date}}</td>
        <td>{{i.buy_call}}</td>
        <td>{{i.target_price}}</td>
        <td>{{i.stop_loss}}</td>
        <td><strong>{{i.remarks}}</strong></td>
        <td>{{i.sell_at}}</td>
     </tr>
{% endfor %}

謝謝!

首先,更新您的views.py,使其將您想要的colors 傳遞給模板。

def table(request):
    table = Table.objects.all().order_by('-date')
    buycolor = "green"
    holdcolor = "yellow"
    sellcolor = "red"
    return render(request, 'scanner/table.html', {
       'table':table,
       'buycolor':buycolor,
       'holdcolor':holdcolor,
       'sellcolor':sellcolor
       })

然后,在您的 Django 模板中,您可以添加以下邏輯:

{% if i.remarks == "BUY" %}
    <td style="color: {{buycolor}};"><strong>{{i.remarks}}</strong></td>
{% elif i.remarks == "HOLD" %}
    <td style="color: {{holdcolor}};"><strong>{{i.remarks}}</strong></td>
{% else %}
    <td style="color: {{sellcolor}};"><strong>{{i.remarks}}</strong></td>
{% endif %}

這會檢查i.remarks是什么,然后相應地設置顏色。

旁注:如果您想顯示 Buy、Sell、Hold 而不是 BUY、SELL、HOLD,請使用i.get_remarks_display()而不是i.remarks

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM