Chapter 11. Blog Posts

This chapter is dedicated to the implementation of Flasky’s main feature, which is to allow users to read and write blog posts. Here you will learn a few new techniques for reuse of templates, pagination of long lists of items, and working with rich text.

Blog Post Submission and Display

To support blog posts, a new database model that represents them is necessary. This model is shown in Example 11-1.

Example 11-1. app/ Post model
class Post(db.Model):
    __tablename__ = 'posts'
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text)
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    author_id = db.Column(db.Integer, db.ForeignKey(''))

class User(UserMixin, db.Model):
    # ...
    posts = db.relationship('Post', backref='author', lazy='dynamic')

A blog post is is represented by a body, a timestamp, and a one-to-many relationship from the User model. The body field is defined with type db.Text so that there is no limitation on the length.

The form that will be shown in the main page of the application lets users write a blog post. This form is very simple; it contains just a text area where the blog post can be typed and a submit button. The form definition is shown in Example 11-2.

Example 11-2. app/main/ Blog post form
class PostForm(Form):
    body = TextAreaField("What's on your mind?", validators=[Required()])
    submit = SubmitField('Submit')

The index() view function handles the form and passes the list of old blog ...

Get Flask Web Development now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.