flask+wtforms 发起 post 的时候无报错,又没写入数据库是什么原因?

2017-07-14 08:46:53 +08:00
 xvx
昨天试过可以 post 成功的,后面不知道做了什么改动,今天又不行了。大佬能否指教下。
'''Python
#post.html 文件:
<form
method="post"
action="{{ url_for('content.post', **request.args) }}"
role="form"
>
<legend>说点什么吧!</legend>
{{ form.csrf_token }}
<div>
{{ form.title(placeholder="标题",
type="text",
autofocus="true",
spellcheck="false") }}
</div>
<div>
{{ form.tags(placeholder="标签 /话题",
type="text") }}
</div>
<select name="category">
<option value="">选择分类</option>
{% for o in form.category.choices %}
{%- if o[2] == None -%}
<option value="{{ o[0] }}">{{ o[1] }}</option>
{% else %}
<option value="{{ o[0] }}">--{{ o[1] }}</option>
{%- endif %}
{% endfor %}
</select>
<div>
{{ form.content(placeholder="内容",
type="text") }}
</div>
<button type="submit">发布</button>
</form>

form 文件:

# POST 表单
class PostForm(FlaskForm):
title = StringField(
'title',
validators=[
DataRequired()
])
tags = StringField(
'tags'
)
category = SelectField(
'category',
coerce=int
)
content = TextAreaField(
'content',
validators=[
DataRequired()
])

#路由:
@bp.route('/post', methods=['GET', 'POST'])
def post():
''' 发帖 '''
if g.user.is_authenticated:
form = PostForm()
# 分类处理
form.category.choices = [(obj.id, obj.name, obj.parent) for obj in Category.query.order_by('id')]
if form.validate_on_submit():
# 标签处理
tag_list = form.tags.data.split(',')
tags = []
for l in tag_list:
name = Lable.query.filter_by(name=l).first()
if name is None:
tags.append(Lable(name=l))
else:
tags.append(name.decode('utf-8'))
# 分类处理
category = Category.query.filter_by(id=form.category.data).first()
posts = PostContent(p_title=form.title.data,
p_lable=tags,
p_content=form.content.data,
p_category_name=category,
is_posted=True,
p_author=g.user.id
)
db.session.add(posts)
db.session.commit()
db.session.flush()
# return redirect('/')
else:
abort(404)
return render_template('/content/post.html', form=form)
'''
2167 次点击
所在节点    Flask
6 条回复
xvx
2017-07-14 09:09:32 +08:00
默认没有缩进,补上截图。
![Markdown]( http://i1.buimg.com/1949/c86ff5524e2a61e7.png)
xvx
2017-07-14 09:34:10 +08:00
据我的猜测应该是 form.validate_on_submit()后面没有执行到,不理解为什么没有执行。
030
2017-07-14 09:36:09 +08:00
这种路由入口打个断点,数据库操作前打个断点就能找到问题了
xvx
2017-07-14 09:38:01 +08:00
添加代码验证,果然是这样:
if not form.validate_on_submit():
return '提交失败!'
HypoChen
2017-07-14 09:41:31 +08:00
form.errors 里有啥
xvx
2017-07-14 09:50:57 +08:00
@HypoChen
我加了这个代码进去:
if not form.validate_on_submit():
return form.errors
返回这个错误:
builtins.TypeError
TypeError: 'dict' object is not callable

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/375221

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX