Reputation: 348
I need to create in a html django template a form with a select dinamically created: I read values from a txt file and I store it in a dict, when I call the render to response I pass this dict but when I try to print its values in the template it doesn't print anything. This is my views:
def home(request):
i=0
d = {}
with open("static/my_file.txt") as f:
for line in f:
key=i
val = line.rstrip()
d[int(key)] = val
i=i+1
return render_to_response('home.html', var=d)
and this is the print in the html template:
{% for val in var %}
{{ val.value }}
{% endfor %}
Can help me?
Upvotes: 0
Views: 3295
Reputation: 1129
If you want to pass just the variable or all variable available (local variable) in the view.py to your template just pass locals() in your case should be:
view.py:
def home(request):
i=0
d = {}
with open("static/my_file.txt") as f:
for line in f:
key=i
val = line.rstrip()
d[int(key)] = val
i=i+1
return render('home.html', locals())
template:
{% for key,value in d.items %}
{{ value }}
{% endfor %}
Upvotes: 0
Reputation: 27503
you have error in view, you need to pass context as dictionary from django.shortcuts import render
def home(request):
i=0
d = {}
with open("static/my_file.txt") as f:
for line in f:
key=i
val = line.rstrip()
d[int(key)] = val
i=i+1
return render(request,'home.html', {'var':d})
Upvotes: 1
Reputation: 1502
Try this instead of the above jinja file.
If you need just values of var
, and if var
is dictionary, then this below code would work for you.
{% for val in var.values() %}
{{ val }}
{% endfor %}
Upvotes: 1
Reputation: 8435
The Django documentation for for
-loops in templates shows that the syntax for dicts is slightly different. Try:
{% for key, value in var.items %}
{{ value }}
{% endfor %}
Upvotes: 3