I am trying to edit smartphone details and all input fields have dataRequired() validation. However, the input file for images is empty by default. When I try to edit other fields, such as brand, I also have to enter the input file for the image in order to edit successfully. How can I have the input file automatically retrieve the image_URL from the database after submitting the form?
Input file of image_URL
{% for smartphone in smartphones %}
<div class="form-floating mb-4 justify-content-between">
<img src="{{ url_for('static',filename = smartphone['image_URL']) }}" style="height: 250px;">
<input type="file" id="image_URL" name="image_URL" accept="image/*">
</div>
{% endfor %}
Backend in app.py
@app.route('/editSmartphone/<int:id>',methods = ['GET','POST'])
def editSmartphone(id):
smartphoneID = id
conn = get_db_connection()
smartphones = conn.execute('SELECT * FROM Smartphone WHERE id = ?',(smartphoneID,)).fetchall()
form = editSmartphoneForm(request.form)
if request.method == 'POST' and form.validate():
conn.execute('UPDATE Smartphone SET brand = ?,model = ?,processor = ?, ram = ?, colour = ?, battery = ?, lowprice = ?, highprice = ?, screenSize = ?, refreshRate = ?, description = ?, image_URL = ? WHERE id = ?',(form.brand.data, form.model.data, form.processor.data, form.ram.data, form.colour.data, form.battery.data, form.lowprice.data, form.highprice.data, form.screenSize.data, form.refreshRate.data, form.description.data, form.image_URL.data, smartphoneID))
conn.commit()
conn.close()
message = "Smartphone detail has been modified successfully"
flash(message,'edited')
return redirect('/manageSmartphone')
return render_template('editSmartphone.html',smartphones = smartphones, form = form)
Your question looks somewhat similar to this question, so I'll borrow some elements from that answer here.
You've got the current smartphone via the
smartphoneslist, so the currentimage_URLfor the phone you're editing should look like:My approach is to check if
form.image_URL.datais empty when editing the phone on theeditSmartphoneroute. You can write some logic to check this before calling the database update statement:You can see above that we store the results of this check in
image_URL. Then you just replaceform.image_URL.datawithimage_URLin your database update statement:conn.execute('UPDATE Smartphone SET ... image_URL = ? ...',(..., image_URL, ...))Also, inside
editSmartphoneForm, make sure to remove theDataRequired()validator onimage_URL.Hope this helps, or at least gets you on the right track!