0

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?

asked Aug 1, 2017 at 11:09
2
  • 2
    Please read docs before asking here. Commented Aug 1, 2017 at 11:21
  • 2
    All you need to know to fix this (both the view and template) is extensively documented indeed. And very simple to understand too. Commented Aug 1, 2017 at 11:24

4 Answers 4

3

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 %}
answered Aug 1, 2017 at 11:15
Sign up to request clarification or add additional context in comments.

Comments

1

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 %}
answered Aug 1, 2017 at 11:17

Comments

1

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})
answered Aug 1, 2017 at 11:18

1 Comment

What exactly is the error? I see the same code, with the only change an import that the OP probably left out to save space.
0

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 %}
answered Aug 1, 2017 at 13:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.