本节我们为Web程序添加编辑文章的功能。
一. 修改|-app/-main/views.py
@main.route('edit/<int:id>')
@login_required
def edit(id):
post = Post.query.get_or_404(id)
if current_user != post.author and not current_user.is_administrator():
abort(403)
form = PostForm()
if form.validate_on_submit():
post.body = form.body.data
db.session.add(post)
flash('Your post has been updated.')
return redirect(url_for('main.post', id=post.id))
form.body.data = post.body
return render_template('edit_post.html', form=form)
二. 修改|-app/templates/edit_post.html
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block page_content %}
{{ wtf.quick_form(form) }}
{% endblock %}
{% block scripts %}
{{ super() }}
{{ pagedown.include_pagedown() }}
{% endblock %}
三. 修改|-app/templates/_post.html
<ul class="posts">
{% for post in posts %}
<li class="post">
<div class="post-content">
#...
<div class="post-footer">
{% if current_user == post.author %}
<a href="{{ url_for('main.edit', id=post.id) }}"><span class="label label-primary">Edit</span></a>
{% elif current_user.is_administrator() %}
<a href="{{ url_for('main.edit', id=post.id) }}"><span class="label label-danger">Edit [Admin]</span></a>
{% endif %}
</div>
</div>
</li>
{% endfor %}
</ul>