I'm having an issue with Flask Login. Everytime i try to login, i have this error:
AttributeError: type object 'User' has no attribute 'get'
I dont know where this is coming from since i'm using the recommanded code in the flask documentation. Here is the code:
from flask import Flask, escape, request, render_template, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from flask_login import UserMixin, login_manager, login_user, login_required, logout_user, current_user, LoginManager
from flask_wtf import FlaskForm
from flask_wtf.form import FlaskForm
from flask_wtf.recaptcha import validators
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import InputRequired, Length, ValidationError
from flask_bcrypt import Bcrypt
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data_task.db'
db = SQLAlchemy(app)
app.config['SECRET_KEY'] = "HEXODECICUL"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
bcrypt = Bcrypt(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), nullable=False, unique=True)
password = db.Column(db.String(80), nullable=False)
class RegisterForm(FlaskForm):
username = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"})
password = PasswordField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Password"})
submit = SubmitField("Register")
def validate_username(self, username):
existing_usernames = User.query.filter_by(username=username.data).first()
if existing_usernames:
raise ValidationError("That username alreadu exists. Please choose a different one.")
class LoginForm(FlaskForm):
username = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"})
password = PasswordField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"})
submit = SubmitField("Login")
@app.route('/dash', methods=['GET', 'POST'])
@login_required
def dash():
return render_template("index.html")
@app.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user:
if bcrypt.check_password_hash(user.password, form.password.data):
login_user(user)
return redirect(url_for('dash'))
return render_template("login.html", form = form)
@app.route("/logout")
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
@app.route("/register", methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password.data)
new_user = User(username=form.username.data, password=hashed_password)
db.session.add(new_user)
db.session.commit()
return redirect(url_for('login'))
return render_template("register.html", form=form)
@app.route('/', methods=["GET", "POST"])
def accueil():
return "Home"
if __name__ == '__main__':
app.run(debug=True)
The error in flask:
AttributeError
AttributeError: type object 'User' has no attribute 'get'
Traceback (most recent call last)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 2091, in __call__
def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:
"""The WSGI server calls the Flask application object as the
WSGI application. This calls :meth:`wsgi_app`, which can be
wrapped to apply middleware.
"""
return self.wsgi_app(environ, start_response)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 2076, in wsgi_app
response = self.handle_exception(e)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 1518, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 1516, in full_dispatch_request
rv = self.dispatch_request()Open an interactive python shell in this frame
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/Users/christophechouinard/Feuille_encaisse/app.py", line 69, in login
return render_template("login.html", form = form)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/templating.py", line 146, in render_template
ctx.app.update_template_context(context)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask/app.py", line 756, in update_template_context
context.update(func())
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask_login/utils.py", line 379, in _user_context_processor
return dict(current_user=_get_user())
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask_login/utils.py", line 346, in _get_user
current_app.login_manager._load_user()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/flask_login/login_manager.py", line 318, in _load_user
user = self._user_callback(user_id)
File "/Users/christophechouinard/Feuille_encaisse/app.py", line 52, in load_user
password = PasswordField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"})
submit = SubmitField("Login")
@login_manager.user_loader
def load_user(user_id):
return User.get(user_id)
@app.route('/dash', methods=['GET', 'POST'])
@login_required
def dash():
return render_template("index.html")
AttributeError: type object 'User' has no attribute 'get'
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.
You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:
dump() shows all variables in the frame
dump(obj) dumps all that's known about the object
Brought to you by DON'T PANIC, your friendly Werkzeug powered traceback interpreter.
I know that this question has aleready been answered here: https://stackoverflow.com/questions/ask#:~:text=AttributeError%3A%20type%20object%20%27Message,pack()%20display.update()%20def%20... but I tried this and still got this error (and I dont understant so well the answers on this question...)
Thanks a lot !!