Python 商品不显示在购物车中

Python 商品不显示在购物车中,python,flask,Python,Flask,因此,我试图在我添加的篮子中显示项目,但没有显示任何内容 @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: ite

因此,我试图在我添加的篮子中显示项目,但没有显示任何内容

@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 display_cart %}
    <tr>
        <td>{{phone.model}}</td>
        <td>{{phone.year}}</td>
        <td>${{ "%.2f" % phone.price}}</td>
        <td>${{ "%.2f" % phone.price}}</td>
    </tr>    
{% endfor %}
我会将电话列表传递到您的模板中,而不是电话字典。此外,您的dict_of_phones仅设置为手机项目的最后一个值,因为您每次都使用dict_of_phones=phone覆盖其值。所以dict_of_phones实际上只是items中最后一项给出的单个phone项:phone=get_phone_by_iditem。也许你可以修改你的代码来创建一个电话列表?然后将此列表传递到您的jinja2模板中,大致如下:

@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:
    # Assuming items is correct, looks off
    items = [j for i in session["cart"] for j in i]
    phones = []

    for item in items:
        phone = get_phone_by_id(item)
        print(phone.id)
        # assuming phone has id,model,year, and price attributes
        phones.append[phone]
        # note total_price of your cart not currently being used in your template
        total_price += phone.price
    return render_template('phones/cart.html', display_cart=phones, total = total_price)
然后,在模板中,您可以按照以下方式进行操作:

{% for phone in display_cart %}
    <tr>
        <td>{{phone.model}}</td>
        <td>{{phone.year}}</td>
        <td>${{ "%.2f" % phone.price}}</td>
        <td>${{ "%.2f" % phone.price}}</td>
    </tr>    
{% endfor %}

希望这有帮助

当我更改变量名时,我得到了一个错误:TypeError:“Phone”对象不是iterablet这是因为您需要使dict_of_Phone成为您需要在购物车中显示的任何内容的列表。这些手机中的每一个都需要有你在模板中使用的属性,比如phone.model、phone.year等。将某个东西命名为dict\u of\u phone并不意味着它是dict,你必须在将它传递到模板之前将它变成dict。此外,在模板中访问dict的方式是不正确的。它应该是phone['model']或phone['year']
{% for phone in display_cart %}
    <tr>
        <td>{{phone.model}}</td>
        <td>{{phone.year}}</td>
        <td>${{ "%.2f" % phone.price}}</td>
        <td>${{ "%.2f" % phone.price}}</td>
    </tr>    
{% endfor %}