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)
P粉1484347422024-02-26 18:57:14
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 smartphones
list, so the current image_URL
for the phone you're editing should look like:
current_image_URL = smartphones[0][11]
My approach is to check if form.image_URL.data
is empty when editing the phone on the editSmartphone
route. You can write some logic to check this before calling the database update statement:
if form.image_URL.data == "": image_URL = current_image_URL else: image_URL = form.image_URL.data
You can see above that we store the results of this check in image_URL
. Then you just replace form.image_URL.data
with image_URL
in your database update statement:
conn.execute('UPDATE Smartphone SET ... image_URL = ? ...',(..., image_URL, ...))
Also, inside editSmartphoneForm
, make sure to remove the DataRequired()
validator on image_URL
.
Hope this helps, or at least gets you on the right track!