【问题标题】:how to add a style in django如何在 django 中添加样式
【发布时间】:2021-06-08 19:54:57
【问题描述】:

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

models.py

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

views.py

from .models import Car

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

index.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

【问题讨论】:

  • {% if car.color == 'red' %}
  • 或者你也可以使用style="background-color: {{ car.color|default:'black' }};"
  • 没用...
  • @WillemVanOnsem 答案对我有用。 1.)您的 if 条件中缺少 '%' 。 2.) 红色应该用引号引起来( "red" )。

标签: python css django django-templates django-staticfiles


【解决方案1】:

这里有两个错误:

  1. 一个模板标签,如{% if … %} [Django-doc],用大括号括起来,带有百分比({% … %}),你错过了百分比(%);和
  2. 字符串字面量用引号括起来,所以'red',而不是red

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

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

【讨论】:

  • @Bodok:根据错误信息,这是另一个{% if ... %}条件。
  • 此外,请使用文本,而不是文本图像idownvotedbecau.se/imageofcode
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 2012-07-17
  • 2021-11-07
相关资源
最近更新 更多