简体   繁体   中英

How do I fix username is not defined in my Flask app?

I am making a Flask Chatting website and currently, I am making a database for users but I keep getting username is not defined CODE

...
#Create db model
class Users(db.Model):
    username = db.Column(db.String(80), primary_key=True, unique=True, nullable=False)
    email = db.Column(db.String(80), primary_key=True, unique=True, nullable=False)
    password = db.Column(db.String(80), nullable=False)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

    def __init__(self, username, email, password):
        self.username = username
        self.email = email
        self.password = password

...
@app.route('/signup', methods=["GET", "POST"])
def signup():
    title = "Signup"

    if request.method == "POST":
        user_name = request.form['Name']
        user_password = request.form['Password']
        user_email = request.form['Email']
        new_user = Users(username=user_name, email=user_email, password=user_password)

        try:
            db.session.add(new_user)
            db.session.commit()
            return redirect('/')
        except:
            return "There was an error"

    else:
        return render_template("signup.html", title=title)
...

I am a beginner Flask developer so I would really appreciate it if you would reply fast Thanks in advance

You can try using __repr__ .

class User(db.Model):
    # ...

    def __repr__(self):
        return f'{self.username} {self.email} {self.password}'

To test, you can run flask shell in your terminal:

# flask shell starts the python interpreter in the context of your application
(venv)$ flask shell

>>> from app.models import User
>>> users = User.query.all() # retrieve all users in db
>>> print(users)

# Output
[test_name test@email.com test_password]

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