webminal.org
webminal.org

Reputation: 47196

python-flask db.session.commit() is not working

The problem is when user tries 'forgot password' option. It creates new reset_key for verification, but the new key is not getting updated into DB.

@app.route('/login/forgot/', methods=['GET', 'POST'])
def forgot():
   form = ResetLoginForm(request.form)
   #There's no session yet. User just pointing to /login/forgot url.

   if request.method == 'POST' and form.validate():
      user = User.query.filter_by(email=form.email.data).first()

   if not user:
     flash('The username or email incorrect')
     return render_template('forgot.html', form=form)

   reset_key = generate_key() ## this creates a new key, but how update  this key into db?
   #tried something like 
   user.reset_key = reset_key 
   db.session.add(user)
   db.session.commit()
   #this is not working. Is it due to session is not started or something?

Thanks for any help or hint.

Upvotes: 4

Views: 13170

Answers (2)

Evgene
Evgene

Reputation: 596

user = db.session.query(User).first() solved problem.

Upvotes: 0

gkiwi
gkiwi

Reputation: 610

This is because User.query.filter_by(email=form.email.data).first() will return a sqlalchemy.orm.query.Query object. As its doc says:

Query is the source of all SELECT statements generated by the ORM, both those formulated by end-user query operations as well as by high level internal operations such as related collection loading. It features a generative interface whereby successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.

So you just get a copied object, so your change will not work;

You can use like this: user = db.session.query(User).filter_by(email==form.email.data).first() and then you can change user attrs

Upvotes: 12

Related Questions