So now that we’ve created a view and template for creating a new form, we can also make sure that we can edit and modify items. That’s what we will do here.
9. Editing items
9.1 Editing the app.py file.
To do this, we need to add a new route to the app.py file. It will have a view function that will receive the id of the post that we will be editing. This URL will be in the form of item_id/edit. We will use a variable to make sure that the item_id is correct.
We will add the edit() view function at the end of the file.
This is quite similar to the create() function.
@app.route(‘/<int:id>/edit’, methods=(‘GET’, ‘POST’))
def edit(id):
post = get_post(id)
if request.method == ‘POST’:
title = request.form[‘title’]
content = request.form[‘content’]
if not title:
flash(‘Title is required!’)
else:
conn = get_db_connection()
conn.execute(‘UPDATE posts SET title = ?, content = ?’
‘ WHERE id = ?’,
(title, content, id))
conn.commit()
conn.close()
return redirect(url_for(‘index’))
return render_template(‘edit.html’, post=post)
The post you edit is determined by the URL. Flask will pass the ID number to the edit() function via the ID argument.
9.2 Creating the edit template
Now we need to create the template that is called by the edit() function.
{% extends ‘base.html’ %}
{% block content %}
<h1>{% block title %} Edit “{{ post[‘item’] }}” {% endblock %}</h1>
<form method=”post”>
<div class=”form-group”>
<label for=“item”>Item</label>
<input type=”text” name=“item” placeholder=“Item name”
class=”form-control”
value=”{{ request.form[‘item’] or item[‘item’] }}”>
</input>
</div>
<div class=”form-group”>
<label for=“description”>Description</label>
<textarea name=“description” placeholder=“Description”
class=”form-control”>{{ request.form[‘description’] or post[‘description’] }}</textarea>
</div>
<div class=”form-group”>
<label for=“store”>Store</label>
<textarea name=“store” placeholder=“Store”
class=”form-control”>{{ request.form[‘store’] or post[‘store’] }}</textarea>
</div>
<div class=”form-group”>
<label for=“price”>Price</label>
<textarea name=“price” placeholder=“Price”
class=”form-control”>{{ request.form[‘price’] or post[‘price’] }}</textarea>
</div>
<div class=”form-group”>
<label for=“store”>Purchased</label>
<textarea name=“purchased” placeholder=“Purchased”
class=”form-control”>{{ request.form[‘purchased’] or post[‘purchased’] }}</textarea>
</div>
<div class=”form-group”>
<button type=”submit” class=”btn btn-primary”>Submit</button>
</div>
</form>
<hr>
{% endblock %}
9.3 Linking it all up
In index.html:
{% extends ‘base.html’ %}
{% block content %}
<h1>{% block title %} Welcome to FlaskBlog {% endblock %}</h1>
{% for post in posts %}
<a href=”{{ url_for(‘item’, item=item[‘id’]) }}”>
<h2>{{ item[‘item’] }}</h2>
</a>
<span class=”badge badge-primary”>{{ item[‘created’] }}</span>
<a href=”{{ url_for(‘edit’, id=item[‘id’]) }}”>
<span class=”badge badge-warning”>Edit</span>
</a>
<hr>
{% endfor %}
{% endblock %}