我正在尝试编辑智能手机详细信息,并且所有输入字段都有 dataRequired() 验证。但是,图像的输入文件默认为空。当我尝试编辑其他字段(例如品牌)时,还必须输入图像的输入文件才能成功编辑。如何让输入文件在提交表单后自动检索数据库中的image_URL?
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 %}
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) Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您的问题看起来有点类似于这个问题,所以我将在这里借用该答案中的一些元素。
您已经通过
smartphones列表获取当前的智能手机,因此您正在编辑的手机的当前image_URL应该类似于:我的方法是在
editSmartphone路由上编辑手机时检查form.image_URL.data是否为空。您可以在调用数据库更新语句之前编写一些逻辑来检查这一点:您可以在上面看到我们将此检查的结果存储在
image_URL中。然后,您只需在数据库更新语句中将form.image_URL.data替换为image_URL即可:conn.execute('UPDATE Smartphone SET ... image_URL = ? ...',(..., image_URL, ...))此外,在
editSmartphoneForm内部,请确保删除image_URL上的DataRequired()验证器。希望这对您有所帮助,或者至少让您走上正轨!