简体   繁体   中英

Why isn't my second Jinja for loop running?

Im trying to fetch users from my sql database with sqlite 3 and displaying the names in a form to pick 2 and set up a match. But when i pass the variables through only my first jinja for loop runs and it leaves the second multiple selection box empty.

I've tried it with passing the same variable for both loops and different variables one for each, and the second one still doesn't populate.

from flask import Flask
from flask import render_template
import sqlite3

con = con = sqlite3.connect('chess-test.db')
cur = con.cursor()

app = Flask(__name__)

@app.route('/')
def index():
    users = cur.execute('''SELECT * FROM chess ORDER BY hcp ''')
    return render_template("index.html", users=users)

@app.route('/game')
def game():
    names = cur.execute('''SELECT * FROM chess ORDER BY name ''')
    users = cur.execute('''SELECT * FROM chess ORDER BY name ''')
    return render_template("game.html", names1=names, users=users)

and my jinja template looks like this.

<body>
<div class="container">
    <div class="text-center">
        <div class="display-4">Hvem skal spille?</div>
    </div>

    <div class="form-group">
        <select multiple class="form-control">
            {% for item in names1 %}
            <option>{{ item[0] }}</option>
            {% endfor %}
        </select>

        <label for="exampleFormControlSelect2">mod</label>
        <select multiple class="form-control">
            {% for item in users %}
            <option>{{ item[0] }}</option>
            {% endfor %}
        </select>
    </div>
</div>

and here is the resulting page.

结果页面

Read the queryset before executing next query. Refer here

@app.route('/game')
def game():
    cur.execute('''SELECT * FROM chess ORDER BY name ''')
    names = cur.fetchall()
    cur.execute('''SELECT * FROM chess ORDER BY name ''')
    users = cur.fetchall()
    return render_template("game.html", names1=names, users=users)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM