Flask中制作博客首页的分类功能(二)

在Flask中制作博客首页的分类功能(一)的基础上,继续下面的教程。

发布文章的时候会为文章添加一些标签(tag),这些tag需要和数据库中Category表的tag进行比较,如果已经存在该tag,那么需要将新发表文章的tag与已存在的表格进行对应,如果不存在则要新建一个category表。

首先在python shell中执行操作。

from sql_test import db, Post, Category
category = Category.query.filter_by(tag='Python').first()
category --> <Category 'Python'> # 查询到tag=‘Python’的表
category.count += 1
pp = Post(title='hello one', body='hello hello', category=category) #新建post表与原先的category对应
db.session.add(pp)
db.session.commit() 

没有问题之后在视图函数中增加该功能:

@main.route('/write', methods=['GET', 'POST'])
@login_required
def write():
    form = PostForm()
    category = Category.query.filter_by(tag=form.category.data).first()
    if form.validate_on_submit():
        if category:
            category.count += 1
            post = Post(title=form.title.data, body=form.body.data,
                        summary=form.summary.data, category=category)
        else:
            post = Post(title=form.title.data, body=form.body.data,
                        summary=form.summary.data, category=Category(form.category.data))
        db.session.add(post)
        flash('You have posted a blog')
        return redirect(url_for('main.post', title=post.title))
    return render_template('write.html', form=form)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值