0

I need to use data as JSON from an API in Django View here is my JSON data;

[{'Count': 5491}]

I need to pass just value of the "Count" key to HTML and views.py is as below;

def serviceReport(request):
    data = mb.post('/api/card/423/query/json')
    context = {
        'count' : data['Count']
    }
    return render(request, 'service_report.html', context)

I get error like this;

Exception Type: TypeError Exception Value:
list indices must be integers or slices, not str

What I want is to pass value of count key to service_report.html and also I want to pass multiple JSON datas like data2, data3 as data on views.py how can I do it?

  • Does this answer your question? [Using JSON in django template](https://stackoverflow.com/questions/6286192/using-json-in-django-template) – l33tHax0r Dec 14 '20 at 19:02
  • Unfortunately this gives me the full JSON but I just need value of the Count key. Besides I can get same result without SafeString just with this; return render(request, 'service_report.html', {'data': data}) – Emre Gülas Dec 14 '20 at 20:13

2 Answers2

1

The json is returning a list that contains a dict.

[{'Count': 5491}] 

The brackets are the list so access that with data[0]

def serviceReport(request):
    data = mb.post('/api/card/423/query/json')
    context = {
        'count' : data[0]['Count']
    }
    return render(request, 'service_report.html', context)
Michael Lindsay
  • 1,290
  • 1
  • 8
  • 6
1

Views.py:

def serviceReport(request):
data = mb.post('/api/card/423/query/json')
context = {
    'data' : data
}
return render(request, 'service_report.html', context)

html template: In Django you can use {% %} to use Python code into html, so you can do something like this.

<div>
    {% for element in data %}
        <div>{{element.data}}</div>
    {% endfor %}
</div>

Also if you want to check what's on your data, you could just use {{data}} In anycase, i suggest you do a for in your views.py to append just the "Count" data into a list and then pass that list to the context.

fukurowl
  • 67
  • 7