Jayme McColgan
Jayme McColgan

Reputation: 25

Change color is table cell based of columns in database

so in my never-ending quest of learning to code python, I have a table of IP addresses being built from Jinja2. I'm trying to figure out a way to take this table and change the color of the cell if it's an IP address that's in my Postgres database. I'm using Flask and flask_sqlalchemy in this project.

    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>

Upvotes: 1

Views: 279

Answers (1)

GAEfan
GAEfan

Reputation: 11360

Try:

In 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)

Then, in 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>

Upvotes: 1

Related Questions