如何在url_for语句中添加/?

时间:2019-12-22 13:42:16

标签: python html flask

我想说:转到additemtocart / 1

<a href="{{url_for('additemtocart/1')}}">add to cart</a>

但是我得到的只是一条错误消息:

  

werkzeug.routing.BuildError:

无法为端点'additemtocart/1'构建url。您是说“ additemtocart”吗?

python代码:

carts = []

def addtocart(item):
    carts.append({'name': checkusername(), 'items': item})
    print(carts)

@app.route('/additemtocart/<id>')
def additemtocart(id):
    if checklogin() == True:
        try:
            title = db.get_select_product(int(id))[5]
            addtocart(title)
            print(title + ' has been added to your shopping cart')
            return redirect(url_for('cart'))
        except:
            return 'item does not exist'
    else:
        return redirect(url_for('login'))```

1 个答案:

答案 0 :(得分:1)

更改

<a href="{{url_for('additemtocart/1')}}">add to cart</a>

<a href="{{url_for('additemtocart', ID=1)}}">add to cart</a>

这样,您将通过函数/端点传递可变/非静态组件