更改颜色是基于数据库中列的表单元格

时间:2020-08-10 03:49:46

标签: python flask bootstrap-4 jinja2 flask-sqlalchemy

因此,在我学习编码python的永无止境的追求中,我有一张根据Jinja2构建的IP地址表。我正在尝试找出一种方法来获取此表并更改单元格的颜色(如果它是我的Postgres数据库中的IP地址)。我在这个项目中使用Flask和flask_sqlalchemy。

    class Gear(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(), nullable=False)
    netname = db.Column(db.String())
    ipaddress = db.Column(db.String())
    subnet = db.Column(db.String())

    def __repr__(self):
        return '<gear %r>' % self.id
<div class="container">
    <table class="table table-bordered table-hover">
        <thead>
            <tr>
                <th scope="col">2.0.0.X</th>
                <th scope="col">2.0.1.X</th>
                <th scope="col">200.0.0.X</th>
                <th scope="col">200.0.1.X</th>
                <th scope="col">192.168.0.X</th>
                <th scope="col">192.168.1.X</th>
                <th scope="col">10.0.0.X</th>
                <th scope="col">10.0.1.X</th>
            </tr>
        </thead>
        <tbody>
            {% for n in range(1, 255) %}
            <tr>
                <td>2.0.0.{{n}}</td>
                <td>2.0.1.{{n}}</td>
                <td>200.0.0.{{n}}</td>
                <td>200.0.1.{{n}}</td>
                <td>192.168.0.{{n}}</td>
                <td>192.168.1.{{n}}</td>
                <td>10.0.0.{{n}}</td>
                <td>10.0.1.{{n}}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

1 个答案:

答案 0 :(得分:1)

尝试:

views.py中:

@app.route('/our_ips')
def our_ips():
    #                  whatever query format you use
    our_ip_addresses = db.session.execute("select ipaddress from Gear") 
    # you want something like: 
    # our_ip_addresses = ['2.0.0.10', '2.0.0.50', '2.0.0.100']

    return render_template("our_ips.html", our_ips=our_ip_addresses)

然后,在our_ips.html中:

<table>
    {% for n in range(1, 255) %}
        <tr>
        {% if ("2.0.0." + n|string) in our_ips %}
            <td class="greenText">
                 2.0.0.{{n}}
            </td>
        {% else %}
            <td>
                2.0.0.{{n}}
            </td>
        {% endif %}
            
        </tr>
    {% endfor %}
</table>