提交和显示博客文章 

文章模型

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

博客文章表单

app/main/forms.py

class PostForm(FlaskForm):
    body = TextAreaField(u'说说',validators=[Required()])
    submit = SubmitField(u'发表')

处理博客文章的首页路由

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():
        post = Post(body=form.body.data,author=current_user._get_current_object())
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('.index'))
    posts = Post.query.order_by(Post.timestamp.desc()).all()
    return render_template('index.html',form=form,posts=posts)

显示博客文章的首页模板

{% extends "base.html" %}
{% import 'bootstrap/wtf.html'as wtf %}

{% block title %}Flasky{% endblock %}

{% block page_content %}
    <div class="page-header">
    <h1>欢迎 {% 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>
    <br/>
    <br/>
    <br/>
    <ul class="posts" style="list-style: none">
{% for post in posts %}
    <li class="post">
        <div class="post-thumbnail">
            <a href="{{ url_for('.user',username=post.author.username) }}">
               <img class="img-rounded profile-thumbnail" src="{{ post.author.gravatar(size=40) }}" style="float: left">
            </a>
        </div>
        <div class="post-date" style="float: right">{{ moment(post.timestamp).fromNow() }}</div>
        <div class="post-author">
            <a href="{{ url_for('.user',username=post.author.username) }}" style="padding-left: 20px">
               {{ post.author.username }}
            </a>
        </div>
        <div class="post-body" style="padding-left: 60px;padding-bottom: 30px" >{{ post.body }}</div>
    </li>
    {% endfor %}
    </ul>
{% endblock %}
View Code

相关文章: