表单验证
@app.route('/', methods=['get', 'post'])
def index():
append_form = Append()
if request.method == 'POST':
if append_form.validate_on_submit():
author_name = append_form.au_info.data
book_name = append_form.bk_info.data
author = Author.query.filter_by(name=author_name).first()
if not author:
try:
author = Author(name=author_name)
db.session.add(author)
db.session.commit()
book = Book(name=book_name, author_id=author.id)
db.session.add(book)
db.session.commit()
except Exception as e:
db.session.rollback()
print e
flash("数据添加错误")
else:
book_names = [book.name for book in author.books]
if book_name in book_names:
flash('该作者已存在相同的书名')
else:
try:
book = Book(name=book_name, author_id=author.id)
db.session.add(book)
db.session.commit()
except Exception as e:
db.session.rollback()
print e
flash('数据添加错误')
else:
flash('数据输入有问题')
authors = Author.query.all()
books = Book.query.all()
return render_template('test2.html', authors=authors, books=books, append_form=append_form)
<h2>书籍列表</h2>
<ul>
{% for author in authors %}
<li>
{{ author.name }}
<ul>
{% for book in author.books %}
<li>{{ book.name }}
{% else %}
<li>无书籍</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}