Heim  >  Fragen und Antworten  >  Hauptteil

Die Eingabedatei ruft den image_URL-Datensatz zurück in die Datenbank ab

Ich versuche, Smartphone-Details zu bearbeiten und alle Eingabefelder verfügen über eine dataRequired()-Validierung. Allerdings ist die Eingabedatei für Bilder standardmäßig leer. Wenn ich versuche, andere Felder zu bearbeiten, beispielsweise die Marke, muss ich auch die Eingabedatei für das Bild eingeben, um die Bearbeitung erfolgreich durchführen zu können. Wie kann ich dafür sorgen, dass die Eingabedatei nach dem Absenden des Formulars automatisch die Bild-URL aus der Datenbank abruft?

Eingabedatei für

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粉277305212P粉277305212236 Tage vor398

Antworte allen(1)Ich werde antworten

  • P粉148434742

    P粉1484347422024-02-26 18:57:14

    您的问题看起来有点类似于这个问题,所以我将在这里借用该答案中的一些元素。

    您已经通过 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() 验证器。

    希望这对您有所帮助,或者至少让您走上正轨!

    Antwort
    0
  • StornierenAntwort