【问题标题】:how to access items in a python dictionary by their name如何通过名称访问python字典中的项目
【发布时间】:2020-04-12 16:35:10
【问题描述】:

我正在使用下面的代码创建一个购物车

`

SESSION_COOKIE_AGE=300 
SESSION_EXPIRE_AT_BROWSER_CLOSE =True
@require_POST
def cart_add(request, product_id):
    product = get_object_or_404(Product, id=product_id)
    quantity = request.POST.get('quantity')
    product_id =str(product.id)
    request.session[product_id] ={"product_name":str(product.title),"price":str(product.price),"quantity":quantity}
    items =request.session.items()
    print(items) 
    return render(request, 'cart/display_cart.html', {"products":request.session})`

场景一 当我像这样将项目传递给我的视图时=> return render(request, 'cart/display_cart.html', {"products":items}) 并使用{% for item in products %}{{ item.product_name }} {% endfor %} 在模板中循环它没有显示。但是当我打印它=> print(items) 我在我的控制台中得到dict_items([('7', {'product_name': 'Tomatoe', 'price': '15.00', 'quantity': '3'})])。如何打印模板中的项目

场景 2 当我像这样通过 request.session => return render(request, 'cart/display_cart.html', {"products":request.session}) 我这样做了

 {% for key, value in products.items %}
         <li><a href="{{key}}">{{value}}</a></li>
        {% endfor %} 

在我的模板中,我得到 {'product_name':'西红柿','价格':'20.00','数量':'1'}。如何使用 product_name 而不是 key 在模板中显示项目?谢谢

【问题讨论】:

    标签: python django-templates django-views


    【解决方案1】:

    items 是一个嵌套的dict

    用途:

    {% for k, item in products.items %}
        {{ item.product_name }}
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-01
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2021-03-04
      相关资源
      最近更新 更多