post model and form - csemanish12/flask_blog GitHub Wiki
Post
we have been using dummy data for displaying posts in our homepage. lets make it dynamic. we will need a table to store the posts created by users. we will create post model as follows:
blog/models.py
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
date_posted = db.Column(db.DateTime(), nullable=False, default=datetime.now)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
here, user_id is the foreign key that will enable us to know the user who created this post.
At this point, we have only defined our model. We still need to create a table against this model in our database. We can do so as by opening our python terminal and entering these commands
from blog import db
from blog.models import Post
db.create_all()
This should successfully create a table named 'post' in our database.
Now that we have Post model, lets create Post form so that we can take input from user
blog/forms.py
.
from wtforms import TextAreaField
.
class PostForm(FlaskForm):
title = StringField('Title', validators=[DataRequired()])
content = TextAreaField('Content', validators=[DataRequired()])
submit = SubmitField('Post')
Implementation can be found over this commit