I'm trying to edit a smartphone detail and there is dataRequired() validation for all input field. However, the input file for image is default empty. When I'm trying to edit other field such as the brand, the input file for image must be also inputted in order to edit successfully. How can I let the input file retrieve back the image_URL in database automatically after submitting the form?
Input file for image_URL
{% for smartphone in smartphones %}
<div >
<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)
CodePudding user response:
Your question looks a bit similar to this question, so I'll borrow some elements from that answer here.
You're already getting the current smartphone via the smartphones
list, therefore the current image_URL
of the phone you're editing should be something like:
current_image_URL = smartphones[0][11]
My approach to this would be to check if the form.image_URL.data
is empty when editing a phone on your editSmartphone
route. You could write some logic to check this before you call your DB 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 are storing the outcome of this check in image_URL
. You can then simply replace form.image_URL.data
with image_URL
in your DB update statement:
conn.execute('UPDATE Smartphone SET ... image_URL = ? ...',(..., image_URL, ...))
Also, inside of the editSmartphoneForm
, make sure to remove the DataRequired()
validator on your image_URL
.
Hope this helps, or at least gets you on the right track!