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?

2
  • Does this answer your question? Using JSON in django template Commented Dec 14, 2020 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}) Commented Dec 14, 2020 at 20:13

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.