Rajesh
Rajesh

Reputation: 15

Couldn't iterate over a dictionary context variable in template, despite having all in place, as far as I know?

I'm trying to iterate over the keys of a dictionary passed as context variable in template. But it's just not happening. And when I put {{ key }} in template I get the value corresponding to that key but just couldn't iterate over.

logic.py

global table
table = {}

for i in range(9):
   for j in range(9):
       key = 'i'
       key = key + str(i) + str(j)
       table[key] = 1

view.py

from django.shortcuts import render
from .formss import SudokuForm, RealSudoku
from .logic import table
# Create your views here.

def sudokuf(request):
    title = "Sudoku Puzzle"

    if request.method == 'POST' :
       print(request.POST)
return render (request,"sudoku.html",table)

sudoku.html

<form method="POST" action=""> {% csrf_token %}

    {% for key,value in table.items %}
        {{ key }}:{{ values }}
    {% endfor %}

    {{ i04 }} # If I do this I get the value table['i04'] but not in the above  for loop

    <input type="submit" align="centre" value="Solve">

Upvotes: 0

Views: 82

Answers (2)

El&#39;endia Starman
El&#39;endia Starman

Reputation: 2244

It's probably that you have {{ values }} where you should have {{ value }}.

So instead of

{% for key,value in table.items %}
    {{ key }}:{{ values }}
{% endfor %}

try...

{% for key,value in table.items %}
    {{ key }}:{{ value }}
{% endfor %}

Upvotes: 1

rmunn
rmunn

Reputation: 36718

The third argument to render is a "context", a dictionary whose keys will be available to your HTML as names. You're passing your table object as the context, so its keys (like i04) are available as variables... but there is no key named table in your table, so the name table isn't available to your HTML.

Change this line in view.py:

return render (request,"sudoku.html",table)

to:

return render(request, "sudoku.html", {"table": table})

And you'll have the name table available in your HTML. (But not the name i04).

You could also do something like:

import logic
render(request, "sudoku.html", logic)

And that would make all the names defined in your logic module available to your HTML.

If there's anything that's not clear about this answer, leave a comment and let me know, and I'll try to explain further.

Upvotes: 2

Related Questions