Django应用问题:无法仅展示用户fafa的采购记录
解决Django中仅展示用户“fafa”采购记录的问题
你的代码存在两个核心问题,导致展示的采购记录并非fafa的:
- 视图中硬编码取了第一个订单的采购记录,未按用户筛选;
- 模板中使用全局的
lignes变量,而非当前匹配订单的采购数据。
方案一:在视图层筛选fafa的订单
修改Views.py,提前过滤出用户为fafa的订单,再传入模板:
def app(request): data_dict = { "toto": "tata", "messages": [ {"mont": "ton", "fafa": "fki"} ], "commandes": [ { "numero": "h221g", "date": "14-07-22", "reference": "ref1", "name": "fafa", "purchases": [ {"article": "articlename", "designation": "laptop", "quantity": 2, "price": 133}, {"article": "article2", "designation": "Dell", "quantity": 3, "price": 144}, # 其他采购记录 ] }, # 其他订单 ] } # 筛选name为fafa的订单 fafa_commandes = [commande for commande in data_dict['commandes'] if commande.get('name') == 'fafa'] context = {'fafa_commandes': fafa_commandes} return render(request, 'test/test.html', context)
修改test.html,直接遍历筛选后的订单及其采购记录:
{% for commande in fafa_commandes %} <h3>订单编号:{{ commande.numero }}</h3> {% for ligne in commande.purchases %} <p> 商品编号:{{ ligne.article }}<br> 商品名称:{{ ligne.designation }}<br> 数量:{{ ligne.quantity }}<br> 价格:{{ ligne.price }} </p> {% endfor %} {% endfor %}
方案二:在模板层直接判断并遍历当前订单的采购记录
如果无需在视图层筛选,可简化视图代码,直接在模板中处理:
修改Views.py,仅传入所有订单数据:
def app(request): data_dict = { # 原字典内容保持不变 } context = {'commandes': data_dict['commandes']} return render(request, 'test/test.html', context)
修改test.html,遍历订单时直接使用当前订单的purchases:
{% for commande in commandes %} {% if commande.name == "fafa" %} <h3>订单编号:{{ commande.numero }}</h3> {% for ligne in commande.purchases %} <p> 商品编号:{{ ligne.article }}<br> 商品名称:{{ ligne.designation }}<br> 数量:{{ ligne.quantity }}<br> 价格:{{ ligne.price }} </p> {% endfor %} {% endif %} {% endfor %}
内容的提问来源于stack exchange,提问作者Khalifa
相关产品推荐
相关产品推荐

