在视图中操作数据库
Create
首先建立表单
class NewNoteForm(FlaskForm):
body = TextAreaField('Body', validators=[DataRequired()])
submit = SubmitField('Save')
然后创建视图函数
@app.route('/new', methods=['POST', 'GET'])
def new_note():
form = NewNoteForm()
if form.validate_on_submit(): # 当表单被提交且验证通过返回True
body = form.body.data # 获取表单body字段的内容
note = Note(body=body) # 创建实例note
db.session.add(note) # 添加到会话
db.session.commit() # 提交到数据库
flash('Your note is saved~') # 闪现提交成功的提示
return redirect(url_for('index')) #重定向回index
return render_template('new_note.html', form=form)
编写模板,渲染表单
<head>
{% from 'macros.html' import form_field %}
</head>
{% block content %}
<h2>New note</h2>
<form method="post">
{{ form.csrf_token }}
{{ form_field(form.body,rows=5,cols=50) }}
{{ form.submit }}
</form>
{% endblock %}
form_field是之前写的表单渲染宏,用来返回包含label标签、表单字段、错误消息列表的HTML表单字段代码。
{% macro form_field(field) %} {{ field.label }} {{ field(**kwargs) }} {% if field.errors %} {% for error in field.errors %} <small>{{ error }}</small><br> {% endfor %} {% endif %} {% endmacro %}
效果演示
Read
建立显示note的表单
class DeleteForm(FlaskForm): body = TextAreaField('body',validators=[DataRequired()])
编写视图函数
@app.route('/show_notes') def show_notes(): form = DeleteForm() notes = Note.query.all() return render_template('show_notes.html', notes=notes, form=form)
编写模板show_notes.html
<h1>Notes</h1> <a href="{{ url_for('new_note') }}">New Notes</a> <h4>{{ notes|length }} notes:</h4> {% for note in notes %} <div class="note"> <p>{{ note.body }}</p> </div> {% endfor %}
在index中添加指向show_notes页面的新<li>标签
<li><a href="{{ url_for('show_notes') }}">Show Notes</a></li>
效果图
Updata
编辑表单
class EditNoteForm(FlaskForm): body = TextAreaField('Body', validators=[DataRequired()]) submit = SubmitField('Update')
编写视图
@app.route('/edit/<int:note_id>', methods=['POST', 'GET']) def edit_note(note_id): form = EditNoteForm() note = Note.query.get(note_id) if form.validate_on_submit(): note.body = form.body.data db.session.commit() flash('Your note is updated.') return redirect(url_for('index')) form.body.data = note.body return render_template('edit_note.html', form=form)
修改show_notes模板,在note后添加edit按钮
<h1>Notes</h1> <a href="{{ url_for('new_note') }}">New Notes</a> <h4>{{ notes|length }} notes:</h4> {% for note in notes %} <div class="note"> <p>{{ note.body }}</p> <a class="btn" href="{{ url_for('edit_note',note_id=note.id) }}">Edit</a> </div> {% endfor %}
edit_note模板和添加新note的模板一样
<head> {% from 'macros.html' import form_field %} </head> {% block content %} <h2>New note</h2> <form method="post"> {{ form.csrf_token }} {{ form_field(form.body,rows=5,cols=50) }} {{ form.submit }} </form> {% endblock %}
效果图