提交和显示博客文章

app/models.py 文章模型

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')    

app/main/form.py 博客文章表单

class PostForm(FlaskForm):
    body = TextAreaField('你在想什么?',validators=[DataRequired()])
    submit = SubmitField('提交')

app/main/views.py  处理博客文章的首页路由 把以前发布的文章列表传给魔板

# 使用蓝本自定义路由
@main.route('/', methods=['get', 'post'])
def index():
  form = PostForm()
    # 检查用户是否有写文章的权限并检查是否可以通过验证
    if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit():
        # current_user._get_current_object() 新文章对象,内含真正的用户对象
        post = Post(body = form.body.data,author=current_user._get_current_object())
        db.session.add(post)
        return redirect(url_for('.index'))
    posts = Post.query.order_by(Post.timestamp.desc()).all()
    return render_template('index.html',form=form,posts=posts)

index.html 显示博客文章首页模板

{% block page_content %}
    <div class="page-header">
        <h1>Hello,
        {% if current_user.is_authenticated %}{{ current_user.username }}{% else %}访客{% endif %}!</h1>
    </div>
    <div>
        {% if current_user.can(Permission.WRITE_ARTICLES) %} # 如果没有对应权限,则不会显示文章列表
        {{ wtf.quick_form(form) }}
        {% endif %}
    </div>
    {% include '_posts.html' %} # 引导局部模板

styles.css

.profile-thumbnail {
    position: absolute;
}
.profile-header {
    min-height: 260px;
    margin-left: 280px;
}
ul.posts {
    list-style-type: none;
    padding: 0px;
    margin: 16px 0px 0px 0px;
    border-top: 1px solid #e0e0e0;
}
ul.posts li.post {
    padding: 8px;
    border-bottom: 1px solid #e0e0e0;
}
ul.posts li.post:hover {
    background-color: #f0f0f0;
}
div.post-date {
    float: right;
}
div.post-author {
    font-weight: bold;
}
div.post-thumbnail {
    position: absolute;
}
div.post-content {
    margin-left: 48px;
    min-height: 48px;
}
View Code

相关文章: