bspit
bspit

Reputation: 35

Django HTML iterate trough a dynamic dictionary name

I'm trying to create a website where part of the website I'm using dynamic tabs in html where each tab will show different data.

Now what I'm trying to do is that in the views.py I'm creating different dictionaries for the different tabs. So far I have created the below in the views.py file.

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)

Just to give you an idea some dictionaries that there are in the alltrasfData are:

'transactions_1','transactions_2','transactions_3'

Is there a way in Django html where I can iterate trough these different dictionaries with dynamic dictionary name.

Upvotes: 1

Views: 217

Answers (2)

Lokesh
Lokesh

Reputation: 23

I think store alltrasfData in a dictionary context, pass it to render() and use the following in HTML:

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

Upvotes: 1

narendra-choudhary
narendra-choudhary

Reputation: 4816

You can iterate over dict in templates quite easily using for template tag.

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

Upvotes: 1

Related Questions