商品未显示在购物车中

所以我试图在我添加的篮子中显示该项目,但没有显示任何内容。


@phones.route("/cartt")

def shopping_cart():

total_price = 0

if "cart" not in session:

    flash("There is nothing in your cart.")

    return render_template("phones/cart.html", display_cart = {}, total = 0)

else:

    items = [j for i in session["cart"] for j in i]

    dict_of_phones = {}

    phone_by_id = None


    for item in items:

        phone = get_phone_by_id(item)

        print(phone.id)

        total_price += phone.price

        dict_of_phones = phone

    return render_template('phones/cart.html', display_cart = dict_of_phones, total = total_price)

html:


   {% for phone in dict_of_phones %}

    <tr>

        <td>{{phone.model}}</td>

        <td>{{phone.year}}</td>

        <td>${{ "%.2f" % phone.price}}</td>

        <td>${{ "%.2f" % phone.price}}</td></tr>    

{% endfor %}


素胚勾勒不出你
浏览 136回答 2
2回答

白板的微信

您在模板中使用了错误的变量名称。它应该是 display_cart 而不是 dict_of_phones。见下文:{% for phone in display_cart %}&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <td>{{phone.model}}</td>&nbsp; &nbsp; &nbsp; &nbsp; <td>{{phone.year}}</td>&nbsp; &nbsp; &nbsp; &nbsp; <td>${{ "%.2f" % phone.price}}</td>&nbsp; &nbsp; &nbsp; &nbsp; <td>${{ "%.2f" % phone.price}}</td>&nbsp; &nbsp; </tr>&nbsp; &nbsp;&nbsp;{% endfor %}

森栏

我会将电话列表传递到您的模板中,而不是电话字典。此外,您dict_of_phones就是只设置到您的手机项目的最后一个值,因为你覆盖了每一次它的价值dict_of_phones = phone。所以dict_of_phones实际上只是items 中最后一个项目给出的单个电话项目:phone = get_phone_by_id(item)。也许你可以修改你的代码来创建一个电话列表?然后将此列表传递到您的jinja2模板中,大致如下:@phones.route("/cartt")def shopping_cart():total_price = 0if "cart" not in session:&nbsp; &nbsp; flash("There is nothing in your cart.")&nbsp; &nbsp; return render_template("phones/cart.html", display_cart = {}, total = 0)else:&nbsp; &nbsp; # Assuming items is correct, looks off&nbsp; &nbsp; items = [j for i in session["cart"] for j in i]&nbsp; &nbsp; phones = []&nbsp; &nbsp; for item in items:&nbsp; &nbsp; &nbsp; &nbsp; phone = get_phone_by_id(item)&nbsp; &nbsp; &nbsp; &nbsp; print(phone.id)&nbsp; &nbsp; &nbsp; &nbsp; # assuming phone has id,model,year, and price attributes&nbsp; &nbsp; &nbsp; &nbsp; phones.append[phone]&nbsp; &nbsp; &nbsp; &nbsp; # note total_price of your cart not currently being used in your template&nbsp; &nbsp; &nbsp; &nbsp; total_price += phone.price&nbsp; &nbsp; return render_template('phones/cart.html', display_cart=phones, total = total_price)然后在您的模板中,您可以执行以下操作:{% for phone in display_cart %}&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <td>{{phone.model}}</td>&nbsp; &nbsp; &nbsp; &nbsp; <td>{{phone.year}}</td>&nbsp; &nbsp; &nbsp; &nbsp; <td>${{ "%.2f" % phone.price}}</td>&nbsp; &nbsp; &nbsp; &nbsp; <td>${{ "%.2f" % phone.price}}</td>&nbsp; &nbsp; </tr>&nbsp; &nbsp;&nbsp;{% endfor %}希望这有帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python