Skip to Content
Flask Web Development, 2nd Edition
book

Flask Web Development, 2nd Edition

by Miguel Grinberg
March 2018
Intermediate to advanced
312 pages
7h 22m
English
O'Reilly Media, Inc.
Book available
Content preview from Flask Web Development, 2nd Edition

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/models.py: 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('users.id'))

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

A blog post 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/forms.py: blog post form
class PostForm(FlaskForm):
    body = TextAreaField("What's on your mind?", validators=[DataRequired()])
    submit = SubmitField('Submit')

The index() view function handles the form and passes ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Flask Web Development - Second Edition

Mastering Flask Web Development - Second Edition

Daniel Gaspar, Jack Stouffer

Publisher Resources

ISBN: 9781491991725Errata Page