为了账号安全,请及时绑定邮箱和手机立即绑定

Django HTML 通过动态字典名称进行迭代

Django HTML 通过动态字典名称进行迭代

慕尼黑5688855 2023-12-19 16:53:03
我正在尝试创建一个网站,其中网站的一部分我使用 html 中的动态选项卡,其中每个选项卡将显示不同的数据。现在我想做的是在views.py 中为不同的选项卡创建不同的字典。到目前为止,我已经在views.py 文件中创建了以下内容。def display_rpt (request):    alltrasfData={}    sec = Section.objects.all()    for key in sec:        transactions = Transaction.objects.values('feast_year__title','feast_year','feast_group__title','section','section__short').filter(section_id=key.id).order_by('section','-feast_year','-feast_group__title').annotate(Total_income=Sum('income_amt'),Total_Expenditure=Sum('expenditure_amt'))        subtotal = Transaction.objects.values('section','feast_year','feast_year__title').filter(section_id=key.id).annotate(Total_income=Sum('income_amt'),Total_Expenditure=Sum('expenditure_amt'))        grandtotal = Transaction.objects.values('section').filter(section_id=key.id).annotate(Total_income=Sum('income_amt'),Total_Expenditure=Sum('expenditure_amt'))        alltrasfData[f'transactions_{key.id}']=transactions        alltrasfData[f'subtotal_{key.id}']=subtotal        alltrasfData[f'grandtotal_{key.id}'] = grandtotal    alltrasfData['sec']=sec    return render(request, 'homepage/reports.html',alltrasfData)只是为了让您了解 alltrasfData 中的一些字典是:“交易_1”、“交易_2”、“交易_3”Django html 中有没有一种方法可以使用动态字典名称迭代这些不同的字典。
查看完整描述

2 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

您可以使用 模板标记轻松地在模板中迭代 dictfor

{% for key, values in alltrasfData.items %}

    {% if 'transaction' in key %}

        {% for transaction in values %}

            <p>feast_year: {{transaction.feast_year}}</p>

            <p>...</p>

        {% endfor %}

    {% elif 'subtotal' in key %}

        # logic for subtotal goes here

        # ...

    {% else %}

         # logic for grandtotal goes here

        # ...

    {% endif %}

{% endfor %}


查看完整回答
反对 回复 2023-12-19
?
白衣染霜花

TA贡献1796条经验 获得超10个赞

我认为将 alltrasfData 存储在字典中context,将其传递给 render() 并在 HTML 中使用以下内容:< /span>

{% for key,value in alltrasfData %}
    print(key,value)
{% endfor %}


查看完整回答
反对 回复 2023-12-19
  • 2 回答
  • 0 关注
  • 54 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信