Sample edit route in Flask

Example of editing an existing entry in Flask
mail@pastecode.io avatar
unknown
python
a year ago
731 B
4
Indexable
Never
@posts.route('/post/<int:post_id>/update', methods=['GET', 'POST'])
@login_required
def update_post(post_id):
    post_req = Post.query.get_or_404(post_id)
    if post_req.author != current_user:
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        post_req.title = form.title.data
        post_req.content = form.content.data
        db.session.commit()
        flash('Your post has been updated', 'success')
        return redirect(url_for('posts.show_post', post_id=post_req.id))
    elif request.method == 'GET':
        form.title.data = post_req.title
        form.content.data = post_req.content
    return render_template('new_post.html', title='Update Post', form=form, legend='Update Post')