首页 > 解决方案 > 如何在 django 中添加样式

问题描述

我想更改表格类中的行颜色,如果发生某些事情,如何放置 html 类。我使用引导程序。

模型.py

class Car(models.Model):
    name = models.CharField(max_length=20)
    color = models.CharField(max_length=20)

视图.py

from .models import Car

def index(request):
    cars = Car.objects.all()
    context = {
        'cars' = cars
    }
    return (request, 'index.html', context)

索引.html

<div class="table-responsive-md">
    <table class="table tableh-hover">
        <thead>
            <tr>
                <td>Name</td>
                <td>Color</td>
            </tr>
        </thead>
        <tbody>
            {% for car in cars %}
            <tr>
                <td>{{ car.name }}</td>
                <td {if car.color == red } style="background-color: red;"{% endif %}>{{car.color}}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>
<td {if car.color == red } style="background-color: red;"{% endif %}>{{car.color}}</td>

这条线是我想做的

我正在提高我的英语,请耐心等待 :D

标签: pythoncssdjangodjango-templatesdjango-staticfiles

解决方案


这里有两个错误:

  1. 一个模板标签,比如{% if … %}[Django-doc]用百分号 ( ) 包裹在大括号中{% … %},你错过了百分号 ( %);和
  2. 字符串文字被包裹在引号之间,所以'red', 而不是red.

因此,您可以通过以下方式实现:

<td {% if car.color == 'red' %}style="background-color: red;"{% endif %}>{{car.color}}</td>

推荐阅读