Flask入门小项目 - 搭建极简博客(5)添加写文章功能

目录:

完整程序点这

零、效果

登录后即可进入Post页面,写完提交后到主页看可以看到新写的文章

一、修改app.py中的post函数

@app.route('/post', methods=['GET', 'POST'])
@login_required
def post():
    error = None
    if request.method == 'POST':
        title = request.form.get('title')
        text = request.form.get('text')
        if len(title) == 0:
            error = 'please input title'
        elif len(text) == 0:
            error = 'please input text'
        else:
            article = Article(title=title, text=text)
            db.session.add(article)
            db.session.commit()
            flash('New article has been successfully posted')
            return redirect(url_for('post'))

    return render_template('post.html', error=error)

二、post.html

post.html

{% extends "base.html" %}

{% block body %}
    <h2>Post</h2>
    {% if error %}
          <p class=error><strong>Error:</strong> {{ error }}
    {% endif %}

    <form action="{{ url_for('post') }}" method=post class=add-entry>
      <dl>
        <dt>Title:
        <dd><input type=text size=30 name=title>
        <dt>Text:
        <dd><textarea rows=5 cols=40 name=text></textarea>
        <dd><input type=submit value=Post>
      </dl>
    </form>

{% endblock %}

posted on 2020-04-11 16:22  HolaWorld  阅读(480)  评论(0编辑  收藏  举报

导航