Klawens
Klawens

Reputation: 107

sqlalchemy.exc.InvalidRequestError: Object '<User at 0x10d437eb8>' is already attached to session '2' (this is '3')

I'm making a page to reset password, every time I register a new account and sign in, when I try to reset the password, the sqlalchemy.exc.InvalidRequestError: Object '<User at 0x10d437eb8>' is already attached to session '2' (this is '3')show up, it seems every time I modify a row that already exists in database, this error comes out.

Here's my code:

Register view:

def register():
    form = RegisterForm()
    if form.validate_on_submit():
        data = form.data
        user = User(
            name=data["name"],
            email=data["email"],
            pwd=generate_password_hash(data["pwd"]),
            avatar="user-blue.png",
            uuid=uuid.uuid4().hex
        )
        db.session.add(user)
        db.session.commit()
        return redirect(url_for("home.login"))
    return render_template("home/register.html", form=form)

Reset password view:

def pwd_reset():
    form = PwdForm()
    if form.validate_on_submit():
        data = form.data
        user = User.query.filter_by(name=session["user"]).first()
        from werkzeug.security import generate_password_hash
        user.pwd = generate_password_hash(data["new_pwd"])
        db.session.add(user) # problem here
        db.session.commit()
        return redirect(url_for("home.success"))
    return render_template("home/pwd_reset.html", form=form)

As far as I can see, I can't use the db.session.add on an existing row? How to fix this

Upvotes: 2

Views: 3362

Answers (1)

Lycos IUT
Lycos IUT

Reputation: 158

You do not need to add the user to the db session.

Just modify the intended fields and commit the session :

def pwd_reset():
    form = PwdForm()
    if form.validate_on_submit():
        data = form.data
        user = User.query.filter_by(name=session["user"]).first()
        from werkzeug.security import generate_password_hash
        user.pwd = generate_password_hash(data["new_pwd"])
        db.session.commit()
        return redirect(url_for("home.success"))
    return render_template("home/pwd_reset.html", form=form)

Upvotes: 3

Related Questions