This video is available to students only
Editing Data & CSRF Protection
Editing Data with Forms
You can use WTForms to prepopulate data for forms as well, which is handy when you are editing records. To prepoulate data in a form from a object, WTForms provides a method called process
where we can pass in raw form data and/or an object
@products.route('/<product_id>/edit', methods=['GET', 'POST'])
def edit(product_id):
product = Product.query.get_or_404(product_id)
form = ProductForm()
if form.validate_on_submit():
product.name = form.name.data
product.description = form.description.data
db.session.add(product)
db.session.commit()
elif not form.errors:
# We do this to make sure we're not overwriting a user's input
# if there was an error.
form.process(formdata=form.data, obj=product)
return render_template('products/edit.html', form=form, product=product)
A shortcut for the above logic, is to simply pass in the object when instantiating the form.
@products.route('/<product_id>/edit', methods=['GET', 'POST'])
def edit(product_id):
product = Product.query.get_or_404(product_id)
form = ProductForm(product)
if form.validate_on_submit():
product.name = form.name.data
product.description = form.description.data
db.session.add(product)
db.session.commit()
return render_template('products/edit.html', form=form, product=product)
The template for the edit form (yumroad/templates/products/edit.html
), looks very similar to the creation form, but uses the edit
route instead. It's useful to have a separate template since we may want to customize what fields we allow on the edit field.
{% block title %} Edit {{ product.name }} {% endblock %}
{% block content %}
<div class="container">
<form method="POST" action="{{ url_for('products.edit', product_id=product.id) }}"