How do i populate a dropdown menu from MySQL database in Flask using SQLAlchemy

Viewed 26

I'm trying to create a dropdown that gets its values from a MySQL database, here's the database code in the main.py file

db = SQLAlchemy()
DB_NAME = "base.db"

    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret'
    app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://root:pass123@localhost/base'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

here is the model

class Vehicle(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    reg = db.Column(db.String(45), unique=True, nullable=False)
    brand = db.Column(db.String(45), nullable=False)
    color = db.Column(db.String(45))

also below is the code in the html file

 <div class="dropdown" name= vehicle method="GET" action="/" align="center">
                <button class="btn btn-primary btn-lg dropdown-toggle" type="button" data-toggle="dropdown" >Vehicles
                <span class="caret"></span></button>
                <ul class="dropdown-menu" >
                    {% for row in vehicle %}
                        <li>
                            <option value="{{row[0]}}">{{row[1]}}</option>
                        </li>    
                            <li class="divider"></li>
                    {% endfor %}
                </ul>
            </div>

and here's the route (which i suspect is the source of the problem)

@app.route('/')
def main():
    cur = MySQL(db).connect.cursor()
    cur.execute("SELECT * FROM Vehicle ORDER BY id")
    vehicle = cur.fetchall()
    return render_template('/', vehicle = vehicle)

the dropdown button appears fine on the web page but when i click it a small empty space appears which makes me think that the problem is from the route file and the vehicle = cur.fetchall() is empty even though i have added values in the database

1 Answers

db is SQLAlchemy object, try using

vehicle = db.execute("SELECT * ...").fetchall()
Related