flask和sqlalchemy db.session.commit()在更新时工作不正常

kqqjbcuj  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(537)

正在尝试更新用户名,但它在数据库中没有更新,即使当前的\u user.username已更新。我正在使用mysql、sqlalchemy和flask。

@app.route('/account', methods = ['GET', 'POST'])
@login_required
def account():

form = UpdateAccountForm()

if form.validate_on_submit():
    current_user.username = form.username.data
    db.session.commit()
    flash(f"Updated Account information, welcome {form.username.data}, {current_user.username},",  'success')
    return redirect(url_for('account'))
elif request.method == 'GET':
    form.username.data = current_user.username

return render_template('account.html', title='Account', form=form)

class UpdateAccountForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(min=4, max=20)])
    submit = SubmitField('Update')

def validate_username(self, username):
    if username.data != current_user.username:
        user = db.session.query(models.User).filter_by(username=username.data).first()
        if user:
            raise ValidationError('That username is taken. Please choose another.')
        return user
2mbi3lxu

2mbi3lxu1#

我也遇到了同样的问题,我搜索了很多,然后我得到了这个语法,然后我意识到我忘了在account.html上添加这个

<form action="{{ url_for('contact') }}" method=post>
{{ form.hidden_tag() }}

相关问题