【发布时间】:2017-07-08 03:40:26
【问题描述】:
我需要用户输入来保存到数据库,然后在应用程序上显示。 如果用户的输入为空,我需要显示一条错误消息。
我遇到了显示错误消息的问题。 当用户输入为空白时,将空白帖子保存到数据库中,然后显示没有内容而不是显示错误消息。
我正在使用 Python、Jinja2、Flask、HTML
谢谢!!
if request.method == 'POST':
blog_title = str(request.form['title'])
blog_body = str(request.form['body'])
title_error = ''
body_error = ''
if len(blog_title) == 0:
title_error = 'Please give your blog a title'
return title_error
if len(blog_body) == 0:
body_error = "Please give your blog some content"
return body_error
else:
new_blog = Blog(blog_title, blog_body)
db.session.add(new_blog)
db.session.commit()
blog_id = new_blog.id
return redirect(url_for('blogs', id=blog_id))
else:
return render_template('/newpost_form.html')
【问题讨论】:
-
你返回的是一个空字符串 (
title_error),不是吗? -
@patrick 他重新定义了
return之前的字符串。不过,老实说,他真的根本不需要将其定义为''。 -
@pstatix 我认为你是对的,也是第一个 if 应该跟一个“elif”,对吧?
-
@patrick 也是如此
-
@DamianLattenero 你是说
if request.method吗?不可以直接去else。但是,如果您在谈论if len(blog_title)后跟if len(blog_body),是的,第二个if应该是elif。拥有两个if语句意味着程序将同时检查它们(理论上,return是一个独特的替代方案)。