Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog

目录

  • 目录
  • 前文列表
  • 实现 post() 视图函数
  • 在 post.html 中添加表单
  • 效果

前文列表

用 Flask 来写个轻博客 (1) — 创建项目
用 Flask 来写个轻博客 (2) — Hello World!
用 Flask 来写个轻博客 (3) — (M)VC_连接 MySQL 和 SQLAlchemy
用 Flask 来写个轻博客 (4) — (M)VC_创建数据模型和表
用 Flask 来写个轻博客 (5) — (M)VC_SQLAlchemy 的 CRUD 详解
用 Flask 来写个轻博客 (6) — (M)VC_models 的关系(one to many)
用 Flask 来写个轻博客 (7) — (M)VC_models 的关系(many to many)
用 Flask 来写个轻博客 (8) — (M)VC_Alembic 管理数据库结构的升级和降级
用 Flask 来写个轻博客 (9) — M(V)C_Jinja 语法基础快速概览
用 Flask 来写个轻博客 (10) — M(V)C_Jinja 常用过滤器与 Flask 特殊变量及方法
用 Flask 来写个轻博客 (11) — M(V)C_创建视图函数
用 Flask 来写个轻博客 (12) — M(V)C_编写和继承 Jinja 模板
用 Flask 来写个轻博客 (13) — M(V)C_WTForms 服务端表单检验
用 Flask 来写个轻博客 (14) — M(V)C_实现项目首页的模板

实现 post() 视图函数

  • views.py
    在原有的基础上对视图函数 post() 进行修改.
from uuid import uuid4
import datetimefrom forms import CommentForm@app.route('/post/<string:post_id>', methods=('GET', 'POST'))
def post(post_id):"""View function for post page"""# Form object: `Comment`form = CommentForm()# form.validate_on_submit() will be true and return the# data object to form instance from user enter,# when the HTTP request is POSTif form.validate_on_submit():new_comment = Comment(id=str(uuid4()),name=form.name.data)new_comment.text = form.text.datanew_comment.date = datetime.datetime.now()new_comment.post_id = post_iddb.session.add(new_comment)db.session.commit()post = Post.query.get_or_404(post_id)tags = post.tagscomments = post.comments.order_by(Comment.date.desc()).all()recent, top_tags = sidebar_data()return render_template('post.html',post=post,tags=tags,comments=comments,form=form,recent=recent,top_tags=top_tags)

NOTE: CommentForm 类是在 用 Flask 来写个轻博客 (13) — M(V)C_WTForms 服务端表单检验 中定义的, 需要将其导入到该模块中.

  • 需要在视图函数 post() 中添加接收 HTTP POST 请求, 路由方法 route() 默认只接收 HTTP GET 请求.

  • 在视图函数中创建一个 form 对象, 并以此来获取用户在输入框中输入的数据对象.

  • form.validata_on_submit() 方法会隐式的判断该 HTTP 请求是不是 POST, 若是, 则将请求中提交的表单数据对象传入上述的 form 对象并进行数据检验.

  • 若提交的表单数据对象通过了 form 对象的检验, 则 form.validata_on_submit() 返回为 True 并且将这些数据传给 form 对象, 成为其实例属性.

  • 之后我们就能够通过表单对象 form 来调用其实例属性, 并且赋值给 models 对象, 最后存入到数据库中.

  • 最后, 因为在 post.html 页面需要显示这些评论, 所以该模板文件也需要传入 form 对象含有的实例属性值, 那么我们直接在视图函数 post() 中 直接将 form 对象传入到 render_template() 就好了.

在 post.html 中添加表单

{% extends "base.html"%}
{% block title %}{{ post.name }}{% endblock %}<!-- Replace the BODY of template base.html -->
{% block body %}
<h3>{{ post.title }}</h3>
{{ post.publish_date }}:
{{ post.text }}<div class="col-lg-12"><h3>New Comment:</h3><!-- Set the form --><form method="POST" action="{{ url_for('post', post_id=post.id)}}">{{ form.hidden_tag() }}<div><!-- Field: `name` label -->{{ form.name.label }}{% if form.name.errors %}{% for e in form.name.errors %}<p class="help-block">{{ e }}</p>{% endfor %}{% endif %}{{ form.name(class_="form-control") }}</div><div class="form-group">{{ form.text.label }}{% if form.text.errors %}{% for e in form.text.errors %}<p class="help-block">{{ e }}</p>{% endfor %}{% endif %}{{ form.text(class_='form-control') }}</div><input class="btn btn-primary" type="submit" value="Add Comment"></form>
</div>
{% endblock %}
  • form.hidden_tag(): 提供了预防跨站请求伪造的机制, 常用于表单页面
  • field.errors: 列表类型, 用于显示验证失败后的提示信息
  • {{ form.name(class_="form-control") }}: 把字段本身作为方法调用, 会渲染作用于该字段的的 HTML 代码.
  • field.label: 为输入框生成对应的 label 标签的 HTML 代码.

效果

查看是否写入到了数据库:

mysql> select * from comments where name='jmilkfan';
+--------------------------------------+----------+------+---------------------+--------------------------------------+
| id                                   | name     | text | date                | post_id                              |
+--------------------------------------+----------+------+---------------------+--------------------------------------+
| 0cea03ec-76b4-4ba4-b781-6a0bf056078b | jmilkfan | HI   | 2016-11-25 17:21:05 | 35c8b4f3-c231-4b32-b139-f7647714b87e |
+--------------------------------------+----------+------+---------------------+--------------------------------------+
1 row in set (0.00 sec)

ERROR LOG:

(env)fanguiju@fanguiju:/opt/JmilkFan-s-Blog$ python manage.py server
/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.script is deprecated, use flask_script instead..format(x=modname), ExtDeprecationWarning
/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.migrate is deprecated, use flask_migrate instead..format(x=modname), ExtDeprecationWarning
/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.sqlalchemy is deprecated, use flask_sqlalchemy instead..format(x=modname), ExtDeprecationWarning
/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True to suppress this warning.warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True to suppress this warning.')
Traceback (most recent call last):File "manage.py", line 35, in <module>manager.run()File "/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask_script/__init__.py", line 412, in runresult = self.handle(sys.argv[0], sys.argv[1:])File "/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask_script/__init__.py", line 383, in handleres = handle(*args, **config)File "/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask_script/commands.py", line 425, in __call__**self.server_options)File "/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/flask/app.py", line 843, in runrun_simple(host, port, self, **options)File "/opt/JmilkFan-s-Blog/env/local/lib/python2.7/site-packages/werkzeug/serving.py", line 677, in run_simples.bind((hostname, port))File "/usr/lib/python2.7/socket.py", line 224, in methreturn getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use

TSG: 在该运行的环境中, Server() 默认的 IP 或 PORT 被占用了. 所以在 manage.py 中手动的设定其 IP 或 PORT.

manager.add_command("server", Server(host='127.0.0.1', port=8089))

用 Flask 来写个轻博客 (15) — M(V)C_实现博文页面评论表单相关推荐

  1. 用 Flask 来写个轻博客 (14) — M(V)C_实现项目首页的模板

    Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 实现所需要的视图函数 实现 home.html 模板 代码分析 实现效 ...

  2. 用 Flask 来写个轻博客 (12) — M(V)C_编写和继承 Jinja 模板

    Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 扩展阅读 使用 Bootstrap 编写 Jinja 模板文件 继承一 ...

  3. 用 Flask 来写个轻博客 (11) — M(V)C_创建视图函数

    Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 视图函数 在 views.py 文件中定义视图函数 定义右侧边栏的视图 ...

  4. 用 Flask 来写个轻博客 (13) — M(V)C_WTForms 服务端表单检验

    Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 WTForms WTF 的基础使用 常用的字段类型 fields.Da ...

  5. 用 Flask 来写个轻博客 (10) — M(V)C_Jinja 常用过滤器与 Flask 特殊变量及方法

    Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 Jinja 中常用的过滤器 default float int len ...

  6. 用 Flask 来写个轻博客 (9) — M(V)C_Jinja 语法基础快速概览

    Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 扩展阅读 Jinja 变量名 注释 控制语句 if 语句 循环 过滤器 ...

  7. 用 Flask 来写个轻博客 (37) — 在 Github 上为第一阶段的版本打 Tag

    Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 第一阶段结语 打 Tag 前文列表 用 Flask 来写个轻博客 (1 ...

  8. 用 Flask 来写个轻博客 (36) — 使用 Flask-RESTful 来构建 RESTful API 之五

    Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 PUT 请求 DELETE 请求 测试 对一条已经存在的 posts ...

  9. 用 Flask 来写个轻博客 (35) — 使用 Flask-RESTful 来构建 RESTful API 之四

    Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 POST 请求 身份认证 测试 前文列表 用 Flask 来写个轻博客 ...

最新文章

  1. Python逻辑运算符 and ,or not 的理解
  2. 使用dom4j解析XML例子
  3. Conficker蠕虫新动作 P2P更新5月份关闭
  4. 数据结构 排序 java_Java数据结构之排序---希尔排序
  5. 深入理解 Kotlin coroutine (二)
  6. 自动化测试框架:自动化测试呼唤开发
  7. VIM中常用的替换模式总结
  8. ipad和iphone切图_如何在iPhone,iPad和Mac上签名PDF
  9. 5条Java记录规则
  10. 8086标志操作指令
  11. VB 全局Hook鼠标消息
  12. 服务器安装centos 6.2过程
  13. Flash Builder4.7破解方法
  14. java poi 合并单元格 边框显示不全
  15. Sicily 1094 Cude解题报告
  16. charles 请求出现乱码_解决Charles抓取https报文乱码问题
  17. 机器学习:局部加权线性回归(Locally Weighted Linear Regression)
  18. Linux7清空回收站,centos rm回收站
  19. 牛X公司的开会方式,明天开始参照执行
  20. 国产化Linux操作系统有哪些?

热门文章

  1. python迅雷远程下载页面_【教程】Chrome浏览器添加迅雷下载支持
  2. find 命令_linux中find命令的使用
  3. 计算机二级vf知识点总结,2015年计算机二级考试《VFP》复习重点:第四章
  4. 帝国理工学院(IC)研究人员设计了一种可以解决瘫痪的脑机设备
  5. Python读取保存在hdf5文件中的脑电数据
  6. Python-EEG工具库MNE中文教程(5)-机器学习算法随机森林判断睡眠类型
  7. 古典人像秒变3D,视角还能随意切,华为上交联手出品
  8. 特斯拉车主「作死」成真:炫耀「主驾无人」,自动驾驶导致车毁人亡
  9. 苹果发布全球首款5nm芯片A14!性能提升40%,新iPad Air率先搭载
  10. 微软复活20年前生产力工具PowerToys,填补Wind10缺失功能,开源且免费