Skip to content

Post List

Manish Sah edited this page Oct 8, 2020 · 1 revision

Now that we have means to allow users to create posts in our database, we need to display those posts in our home page. we will remove the static content from home route and get the posts from our database. lets update our home route as follow:

blog/routes.py

@app.route("/")
def home():
    posts = Post.query.all()
    return render_template('home.html', posts=posts)

We will add relationship in our User model so that we can get the object of the user who created that post.

blog/models.py

.
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    
    posts = db.relationship('Post', backref='author')
.
.

here, posts is a relationship which is maintained by sqlalchemy. posts is not created in the table but is generated dynamically. The parameter 'backref' creates a relationship in Post model called 'author', so that post object has access to this attributes.

Now, we will update our home page so that username and profile image of the user is displayed in every post using above relationship.

templates/home.html

{% extends 'layout.html' %}
{% block content %}
{% for post in posts %}
<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><a class="article-title" href="#">{{ post.title }}</a></h2>
        <p class="article-content">{{ post.content }}</p>
    </div>
</article>
{% endfor %}
{% endblock content %}

we have used strftime method to get only the date from datetime filed 'date_posted'. strftime takes different patterns for different date formats. here, we have used %Y-%m-%d for year , month and date respectively.

we now have posts in our home page from actual users. we will sort the posts in descending order based on date_posted so that recent post is displayed on top.

we will update our home route as follows:

blog/routes.py

@app.route("/")
def home():
    posts = Post.query.order_by(Post.date_posted.desc()).all()
    return render_template('home.html', posts=posts)

Implementation can be found over this commit

Clone this wiki locally