sqlite 输入文件检索回数据库image_URL记录

4jb9z9bj  于 2022-12-13  发布在  SQLite
关注(0)|答案(1)|浏览(106)

我正在编辑一个智能手机的详细信息,所有输入字段都有dataRequired()验证。但是,图片的输入文件默认为空。当我试图编辑其他字段(如品牌)时,图片的输入文件也必须输入才能成功编辑。我如何让输入文件在提交表单后自动检索数据库中的image_URL?

图像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 %}

www.example.com中的后端 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)

ifmq2ha2

ifmq2ha21#

您的问题看起来有点类似于this question,因此我将在这里借用该答案中的一些元素。
您已经通过smartphones列表获得了当前的智能手机,因此您正在编辑的手机的当前image_URL应该如下所示:

current_image_URL = smartphones[0][11]

我的方法是在编辑editSmartphone路由上的电话时检查form.image_URL.data是否为空。在调用DB update语句之前,可以编写一些逻辑来检查这一点:

if form.image_URL.data == "":
   image_URL = current_image_URL
else:
   image_URL = form.image_URL.data

从上面可以看到,我们将检查结果存储在image_URL中。然后,只需在DB update语句中将form.image_URL.data替换为image_URL即可:

conn.execute('UPDATE Smartphone SET ... image_URL = ? ...',(..., image_URL, ...))

此外,在editSmartphoneForm内部,确保删除image_URL上的DataRequired()验证器。
希望这对你有帮助,或者至少让你走上正轨!

相关问题