Reputation: 17
The code runs fine in flask, until I add the code to return data using sqlalchemy from the database and display it using the corresponding tag in the html section. The error in pycharm is stating that:UnboundLocalError: local variable 'unames' referenced before assignment. I'm not sure that I can reference the tags as global? Am I missing something obvious?
This is a proof of concept to show that data from mysql can be returned and displayed using flask for a small project.
this is the app.py
import os
from flask import Flask
from flask import render_template
from flask import request
from flask_sqlalchemy import SQLAlchemy
project_dir = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://username:password@localhost:3306/database'
db = SQLAlchemy(app)
class Users(db.Model):
uname = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)
def __repr__(self):
return "<uname: {}>".format(self.uname)
@app.route("/", methods=["GET", "POST"])
def home():
if request.form:
users = Users(uname=request.form.get("uname"))
db.session.add(users)
db.session.commit()
unames = Users.query.all()
return render_template("home.html", unames=unames)
if __name__ == "__main__":
app.run(debug=True)'
This is the home.html code:
<h1>UserNames:</h1>
{% for uname in unames %}
<p>{{Users.uname}}</p>
{% endfor %}
Expected results should be displaying 2 usernames that are in the uname column from the Users table.
Upvotes: 0
Views: 291
Reputation: 2415
There is a mistake in the HTML
<p>{{Users.uname}}</p>
You are referencing to Users.uname
instead it should refer to the loop variable uname.uname
<h1>UserNames:</h1>
{% for user in unames %}
<p>{{user.uname}}</p>
{% endfor %}
Upvotes: 1