輸入檔檢索回資料庫image_URL記錄
P粉277305212
P粉277305212 2024-02-25 21:59:33
0
1
402

我正在嘗試編輯智慧型手機詳細信息,並且所有輸入欄位都有 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)
P粉277305212
P粉277305212

全部回覆(1)
P粉148434742

您的問題看起來有點類似於這個問題,所以我將在這裡借用該答案中的一些元素。

您已經透過 smartphones 清單取得目前的智慧型手機,因此您正在編輯的手機的目前 image_URL 應該類似於:

current_image_URL = smartphones[0][11]

我的方法是在 editSmartphone 路由上編輯手機時檢查 form.image_URL.data 是否為空。您可以在呼叫資料庫更新語句之前編寫一些邏輯來檢查這一點:

if form.image_URL.data == "":
   image_URL = current_image_URL
else:
   image_URL = 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() 驗證器。

希望這對您有所幫助,或至少讓您走上正軌!

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!