在視圖中操作數據庫
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 %}
效果圖