-
Notifications
You must be signed in to change notification settings - Fork 1
Update Post
we will allow the author of a post to update its content. To do so, we will add new route for updating a post
blog/routes.py
.
@app.route("/post/new", methods=["GET", "POST"])
@login_required
def new_post():
form = PostForm()
if form.validate_on_submit():
post = Post(title=form.title.data, content=form.content.data, user_id=current_user.id)
db.session.add(post)
db.session.commit()
flash('You post has been created', 'success')
return redirect("/")
return render_template('create_post.html', title_name='New Post', form=form, legend="New Post")
.
@app.route("/post/<int:post_id>/update", methods=["GET", "POSt"])
@login_required
def update_post(post_id):
post = Post.query.get_or_404(post_id)
form = PostForm()
form.title.data = post.title
form.content.data = post.content
return render_template('create_post.html', form=form, legend="Update Post")
we will use PostForm for updating user post as well since creating and updating a post requires same fields (title and content). We will use our existing create.html for updating as well since the only difference will be the name of the form. For creating new post, the name should be "New Post" and similarly for updating a post, the name of the form should be Update Post. We will the pass "legend" variable in create and update route so that we can create.html for both creating and updating posts.
lets update our create.html to replace legend with variable so that corresponding name will be displayed for update and create.
.
.
<legend class="border-bottom mb-4">{{ legend }}</legend>
.
.
Now, we will update our post update logic in update routes
blog/routes.py
from flask import url_for, abort
.
@app.route("/post/<int:post_id>/update", methods=["GET", "POST"])
@login_required
def update_post(post_id):
post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
form = PostForm()
if form.validate_on_submit():
post.title = form.title.data
post.content = form.content.data
db.session.commit()
flash("Your post was updated", "success")
return redirect(url_for('post', post_id=post.id))
form.title.data = post.title
form.content.data = post.content
return render_template('create_post.html', title_name="Update Post", form=form, legend="Update Post")
here, we are validating if the author and the current are same before allowing user to update the post. If the current user is not the author of the post , we will abort the request using abort method provided by flask.
Implementation can be found over this commit