Sample use of form

Sample of using Flask in Python to facilitate transfer of data to/ from the model and the form/ template
 avatar
unknown
python
2 years ago
1.2 kB
4
Indexable
@users.route('/account', methods=['GET', 'POST'])
@login_required
def account():
    form = UpdateAccountForm()
    if form.validate_on_submit():
        if form.picture.data:
            old_picture_file = current_user.image_file
            picture_file = save_picture(form.picture.data)
            current_user.image_file = picture_file
            if old_picture_file != 'default.jpg':
                old_picture_path = os.path.join(current_app.root_path, 'static/profile_pics', old_picture_file)
                os.remove(old_picture_path)
        current_user.username: str = form.username.data
        current_user.email = form.email.data
        # current_user.image_file = form.picture.data
        db.session.commit()
        flash('Your information has been updated', 'success')
        return redirect(url_for('users.account'))
    elif request.method == 'GET':
        form.username.data = current_user.username
        form.email.data = current_user.email
    image_file = url_for('static', filename='profile_pics/' + current_user.image_file)
    return render_template('account.html', title='Account', image_file=image_file, form=form)
Editor is loading...