Post Detail - csemanish12/flask_blog GitHub Wiki
We will create a detail page for post where we can show all the details associated with that post along with update and delete option if the logged in user is the owner of that post.
we need to add a new route to view a single post. lets update our routes.py as follows:
blog/routes.py
@app.route("/post/<int:post_id>")
@login_required
def post(post_id):
post = Post.query.get_or_404(post_id)
return render_template('post.html', post=post)here, int:post_id
- <> is used for representing a variable
- int is type of the variable
- post_id is the name of the variable (we can use any name of our choice)
This will allow user to view single post based on their id.
- localhost:5000/post/1 will show the post with id 1
- localhost:5000/post/2 will show the post with id 2 and so on.
Now, lets create post.html in templates. For starting point, we will copy home.html and remove the for loop. so our code will be as follows:
{% extends 'layout.html' %}
{% block content %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ url_for('static', filename='profile_pictures/' + post.author.image_file) }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="#">{{ post.author.username }}</a>
<small class="text-muted">{{ post.date_posted.strftime('%Y-%m-%d') }}</small>
</div>
<h2 class="article-title">{{ post.title }}</h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
{% endblock content %}we need to update the link in home page, so that when user clicks on any title of the post, the user will be able to view that particular post
templates/home.html
.
<h2><a class="article-title" href="{{ url_for('post', post_id=post.id) }}">{{ post.title }}</a></h2>
.
.Implementation can be found over this commit