0

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.

1
  • 2
    Hi please fix the indentation of your home() route, i.e, is unames = Users.query.all() indented under the if request.form: block, or not? Commented Oct 21, 2019 at 2:42

1 Answer 1

1

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 %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.