我需要用户输入才能保存到数据库,然后在应用上显示。 如果用户的输入留空,我需要显示错误消息。
我在显示错误消息时遇到了麻烦。 当用户输入为空白时,空白帖子将保存到数据库中,然后显示没有内容而不显示错误消息。
我正在使用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')
答案 0 :(得分:1)
我会考虑整合Flask-WTF。我只这样做烧瓶形式。提供了许多验证工具,使其易于使用
<强> forms.py 强>
from flask_wtf import FlaskForm
from wtf.fields import StringField, TextAreaField, SubmitField
from wtf.validators import DataRequired
class NewBlogForm(FlaskForm):
title = StringField('Title', validators=[DataRequired(message='one')])
body = TextAreaField('Body', validators=[DataRequired(message='two')])
submit = SubmitField('Save')
<强> routes.py 强>
from forms import NewBlogForm
@app.route('/newpost', methods=['GET', 'POST'])
def new_post():
form = NewBlogForm()
if form.validate_on_submit():
blog = Blog(form.title.data, form.body.data)
db.session.add(blog)
db.session.commit() # should have try block to catch any errors
return redirect(url_for('blogs', id=blog.id))
return render_template('newposts_form.html', form=form)
<强> newposts_form.html 强>
<form>
<ul>
{% for error in form.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{{ form.csrf_token }}
{{ form.title.label }}{{ form.title }}
{{ form.body.label }}{{ form.body }}
{{ form.submit }}
</form>
如果您使用Flask-Bootstrap,则他们支持wtf forms
并以非常干净的方式显示错误。
答案 1 :(得分:0)
您正在重新定义变量的值,请执行以下操作:
if request.method == 'POST':
blog_title = str(request.form['title'])
blog_body = str(request.form['body'])
if len(blog_title) == 0:
return 'Please give your blog a title'
elif len(blog_body) == 0:
return "Please give your blog some content"
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')