簡體   English   中英

如何修復錯誤:werkzeug.routing.BuildError:無法為值為 ['id'] 的端點“delete”構建 url。 你的意思是“索引”嗎?

[英]How to fix error: werkzeug.routing.BuildError: Could not build url for endpoint 'delete' with values ['id']. Did you mean 'index' instead?

我試圖在 HTML 中有一個按鈕,當我單擊它時會刪除數據庫中的一行。 這是一個燒瓶應用程序。 這是 HTML:

<div class="container-fluid text-center" id="products">
    {% for product in productList %}
    <div class='userProduct'>
        <a href="{{ product.productURL }}" target="_blank">{{ product.title|truncate(30) }}</a>
        <h4 class="currentPrice">${{ product.currentPrice }}</h4>
        <h5 class="budget">Budget: {{ product.userBudget }}</h5>
        <form action="{{ url_for('delete', id=product.id) }}">
            <button class="btn btn-sm btn-primary" type="submit">Remove from Wishlist</button>
        </form>
    </div>
    {% endfor %}
</div>

這是python文件中的路由

@app.route('/delete/<id>')
@login_required
def delete(id):
    remove_product = Product.query.filter_by(id=int(id)).first()
    db.session.delete(remove_product)
    db.session.commit()
    return redirect(url_for('dashboard'))

我對 url_for 做的有什么問題嗎? 我想將按鈕中的 id 傳遞給 python 文件,以便我可以確定要從數據庫中刪除哪個條目。

您可能將 ID 作為整數傳遞,而您的路線需要一個字符串。 改用這個:

@app.route('/delete/<int:id>')

我剛剛遇到了同樣的錯誤,就我而言,它是由數據庫中的某些值為 None 引起的。 所以也許檢查 product.id 是否有缺失值。

為了解決這個問題,我需要一個額外的行,對你來說看起來像這樣:

@app.route('/delete/<id>') # current line
@app.route('/delete', defaults={'id': None}) # added line which handles None

在 delete(id) 中,您必須處理 id 為 None 的情況:

if id is None:
    ... # what should happen if id is None

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM