商品未显示在购物车中

时间:2019-02-22 14:52:53

标签: 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:
    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 %}

2 个答案:

答案 0 :(得分:1)

您在模板中使用了错误的变量名。应该是display_cart而不是dict_of_phones。见下文:

{% 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 %}

答案 1 :(得分:0)

我会将电话的 列表传递到您的模板中 ,而不是电话词典。另外,您的dict_of_phones仅设置为电话项的最后一个值,因为您每次都用dict_of_phones = phone覆盖其值。因此dict_of_phones实际上只是项中最后一项给出的单个电话项phone = get_phone_by_id(item)。也许您可以修改代码以创建电话列表?然后将此列表传递到您的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 %}

希望有帮助!