如何为每个Django型号选择赋予不同的颜色

2024-10-16 20:48:41 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是my 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页面上,比如说蓝色

编辑:

以下是我的完整模型.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

以下是我的观点.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 %}

谢谢


Tags: pytruedatemodelstablenulllengthmax
1条回答
网友
1楼 · 发布于 2024-10-16 20:48:41

首先,更新views.py,使其将所需的颜色传递给模板

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是什么,然后相应地设置颜色

旁注:如果要显示买入、卖出、持有而不是买入、卖出、持有,请使用i.get_remarks_display()而不是i.remarks

相关问题 更多 >