0

In view.py I am using the below for loop to get json data

tables = [] column = [] list = [] for row in result: d = collections.OrderedDict() schematab = row[0].encode('utf8') + '.' +row[1].encode('utf8') d = schematab tables.append(d) column = [] for row in tables: d1 = collections.OrderedDict() tabcol = row.split('.') query2 = 'call SP_Get_TABCOL_Names('+str(pid)+',"'+str(tabcol[1])+'")' cursor.execute(query2) result2 = cursor.fetchall() for i in result2: d2 = collections.OrderedDict() d2 = i[5] column.append(d2) d1[row] = column list.append(d1) column = [] ..... .... context = RequestContext(request,{'appuser':'admin','result':json.dumps(list)}) return HttpResponse(template.render(context), content_type="text/html") 

Result of the loop is data in this format

[ { "outlet_db.dim_outlet": ["area , ", "area_mask "], "outlet_db.dim_sales": ["sales1 , ", "sales2 "], "outlet_db.dim_product": ["produt1", "product2"] } ] 

Now in views.html im using the below loop

{% for key,value in result %} {{key}} {{value}} {% endfor %} 

This prints only the json keys, but values are empty. I need both keys and values.

1
  • Is that really your code? I don't see how you call json.dumps(), which converts results to a string, then loop through it in the template. Commented Nov 26, 2015 at 13:59

2 Answers 2

1

First, do not use the keyword list as a variable name. It is a reserved word in Python. Change it to some other name. Second, based on this line of code, you are passing a list into your context. You also need to remove the json.dumps method as this will load a stringified version of your list into your context variable.

context = RequestContext(request,{'appuser':'admin','result':json.dumps(list)}) 

This means that in your template code, you must iterate over your list first, before you iterate over your dictionary like so. I just added the <br> tags for readability.

{% for x in result %} {% for key,value in x.items %} {{key}}<br> {{value}}<br> {% endfor %} {% endfor %} 

If you want to stick with your current template code, you will have to pass a dictionary but use the .items method like so:

{% for key,value in result.items %} {{key}}<br> {{value}}<br> {% endfor %} 
Sign up to request clarification or add additional context in comments.

Comments

0

You can access the values in Djangos template language using dictionary.items

Try the following:

{% for key, value in result.items %} {{ key }} {{ value }} {% endfor %} 

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.