前提
Python 3.7.1
Django version 2.1.5
困っていること
・Djangoのtemplate/.htmlファイル内で、辞書オブジェクトをforループで回して、値を取得したいが、取得できない。
→辞書のforループで、キーを取得し、『 辞書['キー'] 』の形でキーに対する値を取得するコードを書いているが、
Could not parse the remainder: '['key']' from 'invoice['key']'というエラーが出てしまう。
試したこと
下記のように、htmlファイル上で、forループを回しましたが、エラーになります。
html
1 2 <body> 3 <h2>月別請求一覧</h2> 4 <table class="table"> 5 <thead> 6 <tr> 7 <td>顧客ID</td> 8 <td>顧客名</td> 9 <td>ジャンル</td> 10 <td>合計レッスン数</td> 11 <td>請求金額</td> 12 </tr> 13 </thead> 14 <tbody> 15 {% for invoice in invoice_list %} 16 {% for key in invoice.keys %} 17 <tr> 18 <td>{{ invoice['key'] }}</td> 19 </tr> 20 {% endfor %} 21 {% endfor %} 22 </tbody> 23 </table> 24 <a href="{% url 'index' %}">メニューに戻る</a> 25 </body> 26
以下、ビュー関数です。
views
1def invoice_index(request): 2 customers = Customer.objects.all() 3 genre_sum_template = {'英語': 0, 'ファイナンス': 0, 'プログラミング': 0} 4 invoice_list = [] 5 6 for customer in customers: 7 price_sum = 0 8 genre_sum = genre_sum_template.copy() 9 10 lessons = customer.lesson_set.all() 11 lesson_sum = lessons.count() 12 13 for lesson in lessons: 14 columns = {} 15 genre = lesson.genre 16 genre_sum[genre] += 1 17 18 price = lesson.price 19 price_sum += price 20 21 columns['id'] = customer.id 22 columns['name'] = customer.name 23 columns['genre'] = genre_sum 24 columns['lesson'] = lesson_sum 25 columns['price'] = price_sum 26 27 invoice_list.append(columns) 28 29 return render(request, 'exam/invoice_index.html', {'customers': customers, 'columns':columns, 'invoice_list':invoice_list})
実現したいこと
イメージとしては、下記のコードのような形で、キーに対する値を取得し、htmlファイルの<thead>の<td>に対応したデータを取得し、表示させたい(※下記コードはイメージです。)
html
1 <body> 2 <h2>月別請求一覧</h2> 3 <table class="table"> 4 <thead> 5 <tr> 6 <td>顧客ID</td> 7 <td>顧客名</td> 8 <td>ジャンル</td> 9 <td>合計レッスン数</td> 10 <td>請求金額</td> 11 </tr> 12 </thead> 13 <tbody> 14 {% for invoice in invoice_list %} 15 {% for key in invoice.keys %} 16 <tr> 17 <td>{{ invoice['key'] }}</td> 18 <td>{{ invoice['key'] }}</td> 19 <td>{{ invoice['key'] }}</td> 20 <td>{{ invoice['key'] }}</td> 21 <td>{{ invoice['key'] }}</td> 22 </tr> 23 {% endfor %} 24 {% endfor %} 25 </tbody> 26 </table> 27 <a href="{% url 'index' %}">メニューに戻る</a> 28 </body>
回答1件
あなたの回答
tips
プレビュー