There seem to be a million questions (and answers) about this, but none of them are working for me.
I've got something like this:
test_dict = {'name':'Joe'}
return render_to_response('home.html',test_dict,context_instance=RequestContext(request))
In the template, I'm trying to do this:
{% for k,v in test_dict.items %}
Hello {{ v }} <br />
{% endfor %}
But no luck. On the other hand, this works:
Hello {{ name }}
(No for loop). I must be missing something really obvious?
EDIT
In response to the first answer, I've also tried this:
test_dict = {'name':'Joe'}
data = {'test_dict':test_dict}
return render_to_response('home.html',data,context_instance=RequestContext(request))
And in the template:
{% block content %}
{% for k, v in data.items %}
Hello {{ v }} <br />
{% endfor %}
{% endblock %}
Still nothing showing up.
To do what you want, you would want something like
data = {'test_dict':test_dict}
return render_to_response('home.html',data,context_instance=RequestContext(request))
From the docs
A dictionary of values to add to the template context.
So in your example, test_dict is injected into the template context. Think of it working like this:
template = Template()
for k, v in dictionary.items():
template[k] = v
So test_dict is not injected into the template's context, but the keys and values of test_dict are.
When:
test_dict = {'name':'Joe'}
data = {'test_dict':test_dict}
return render_to_response('home.html',data,context_instance=RequestContext(request))
Use:
{% for k, v in test_dict.items %}
Related
I have two lists like:
DevInDB = ['Dev1','Dev2','Dev3']
and
DevInMesh = [['Dev1',0,0],['Dev2',1,1]]
I want to know if, for any DevInDB string, there is the same string in DevInMesh.
I wrote this code that works (in python)
for dev in DevInDB:
if any(dev in DevMesh for DevMesh in DevInMesh ):
print(dev)
else:
print('no')
I try to ust this code in a HTML file using jinja, but the 'any' function doesn't work. How can I do it?
You need to compute this before sending it to jinja.
Ex:
DevInDB = ['Dev1','Dev2','Dev3']
DevInMesh = [['Dev1',0,0],['Dev2',1,1]]
DevInMesh = {k for k, *_ in DevInMesh}
DevInDB = [(i, i in DevInMesh) for i in DevInDB]
print(DevInDB)
I've done it this way:
{% for DevDB in DevInDB %}
{% set ns = namespace(foo=false) %}
{% for DevMesh in DevInMesh %}
{% if DevMesh [0] == DevDB %}
{% set ns.foo = True %}
{% endif %}
{% endfor %}
and later on:
{% if ns.foo %}
{% else %}
{% endif %}
You can replace the any expression with the simple list comprehension where non-empty list will be True:
[1 for DevMesh in DevInMesh if dev in DevMesh]
Or better is to remove the computational part from template because a template is the view part that works on presentation level of the context, such that all pre-computed expressions should be stored in the context and only printed in the template.
I'm new to Django, and trying to pass api results (dictionaries within a list) to a template using context.
I have tried doing this
{% if apiList != "Error..." %}
{% for i in apiList %}
{% for key, value in i %}
{{ key }} {{ value }}<br>
{% endfor %}
{% endfor %}
{% endif %}
but I get the error
Need 2 values to unpack in for loop; got 4.
When I do the same code but take out the value, so it just searches for the keys, it works fine and prints out all the keys on a new line. I've also tried the following code:
{% for key, value in apiList.items %}
{{ key }} : {{ value }}
{% endfor %}
but this does not seem to work either, it does not give an error, but nothing shows on the screen.
Any idea how to solve this problem? Here is my code in the views.py
try:
apiList = json.loads(api_request.content)
except Exception as e:
apiList = "Error..."
return render(request, 'financials.html', {'apiList': apiList})
else:
return render(request, 'financials.html', {})
Thanks!
EDIT: Here is an example of the data in apiList:
[
{
date: "2020-09-26",
symbol: "AAPL",
fillingDate: "2020-10-30",
acceptedDate: "2020-10-29 18:06:25",
period: "FY",
revenue: 274515000000,
costOfRevenue: 169559000000,
grossProfit: 104956000000,
grossProfitRatio: 0.382332477278109,
researchAndDevelopmentExpenses: 18752000000,
generalAndAdministrativeExpenses: 19916000000,
sellingAndMarketingExpenses: 0,
otherExpenses: 803000000,
operatingExpenses: 38668000000,
costAndExpenses: 208227000000,
interestExpense: 0,
depreciationAndAmortization: 11056000000,
ebitda: 77344000000,
ebitdaratio: 0.281747809773601,
operatingIncome: 66288000000,
operatingIncomeRatio: 0.241473143544069,
totalOtherIncomeExpensesNet: 803000000,
incomeBeforeTax: 67091000000,
incomeBeforeTaxRatio: 0.244398302460703,
incomeTaxExpense: 9680000000,
netIncome: 57411000000,
netIncomeRatio: 0.209136112780722,
eps: 3.31,
epsdiluted: 3.28,
weightedAverageShsOut: 17352119000,
weightedAverageShsOutDil: 17528214000,
link: "https://www.sec.gov/Archives/edgar/data/320193/000032019320000096/0000320193-20-000096-index.htm",
finalLink: "https://www.sec.gov/Archives/edgar/data/320193/000032019320000096/aapl-20200926.htm"
},
try this (i think this can help you to loop through key, value )
{% for key, value in apiList.iteritems() %}
This loop format in html is only printing the key but not value,I want to print both key and value in html page.
views.py
def predict(request):
if request.method == "POST":
dict = {'Name': John, 'Age': 40}
return render(request,'standalone.html',{'content':dict})
else:
return render(request,'test_homepage.html')
satandalone.html
{% for c in content %}
{{c}}
{% endfor %}
You use .items() to obtain an iterable of 2-tuples.
def predict(request):
if request.method == "POST":
data = {'Name': 'John', 'Age': 40}
return render(request,'standalone.html',{'content': data.items()})
else:
return render(request,'test_homepage.html')
In the template, you can then render this with:
{% for k, v in content %}
{{ k }}: {{ v }}
{% endfor %}
Note: Please do not name a variable dict, it overrides the reference to the dict
class. Use for example data.
Try this in your template satandalone.html:
{% for c in content %}
{{ c.name }}
{{ c.age }}
{% endfor %}
Try this. It might help you.
{% for key, value in content.items %}
{{ key }}: {{ value }}
{% endfor %}
I have a dict in python that is something like the following:
d = {'key1': .98, 'key2': 'some_str',
#...
}
In this dictionary some keys will be mapped to float and others will be mapped to str
In my HTML I am doing something like the following:
html_dict = {
{% for k, v in my_dict.items %}
{{ k }}: "{{ v }}",
{% endfor %}
};
However this approach wraps the floats in quotes as well, which is what I don't want. But if I don't know wrap them in quotes the HTML doesn't understand that they are are string values. I would ideally like something like the following:
html_dict = {
{% for k, v in my_dict.items %}
{% if check_v_is_str %}
{{ k }}: "{{ v }}",
{% else %}
{{ k }}: {{ v }},
{% endif %}
{% endfor %}
};
Don't do this. You are manually trying to replicate a JS data structure, when there already exists a well-defined structure that both Python and JS know about, namely JSON. Use that instead. Convert the dict to JSON in your view, and pass it to the template where it can be output directly.
You could define a filter called "check_v_type" to call in your template as follows:
{% if v|check_v_type == 'str' %}
But I don't think that makes for good logic. Generally, you want to avoid function calls in your templates. Instead, in your view, you could create a dictionary of tuples of the form:
d = {'key1': (.98, False), 'key2': ('some_str', True), #...}
You could then use the boolean in each tuple to decide how to format the value in your HTML.
I have a dict:
>>> some_dict
{1: ['String1', 'String2', 'String3','String4' ],
2: ['String1_2', 'String2_2', 'String3_2', 'String4_2' ],}
In my template i want to iterate over this dict and display values in html. So i sent this dict from view:
return render_to_response('tournament.html',
{.....
'some_dict' : some_dict,
'some_dict_range' : range(4),
.....
})
In tournament.html i trying to iterate over some_dict. I want to get output that should looks like:
'String1', 'String2', 'String3','String4'
{% for iter1 in some_dict_range%}
{{some_dict.0.iter1}}<br>{% endfor %}
And as result, i get nothing.
But when i trying to get same result without iterator:
some_dict.0.0, some_dict.0.1, etc. i get what i need ('String1', 'String2', 'String3','String4').
And when i trying to view values of "iter1" i get the right digits:
{% for iter1 in some_dict_range%}
{{iter1}}<br> {% endfor %}
0, 1, 2 ...
Why this doesn't work this way? And if i wrong in design of this, how it should looks like? I mean - what the right way to iterate over this dict and display values in html-template?
Shouldn't:
{{some_dict.0.iter1}}<br>{% endfor %}
Be:
{{some_dict.iter1.0}}<br>{% endfor %}
^^^^^^^
Else you're trying to access some_dict[0] which isn't present...
To avoid passing in the range (as I assume you're wanting to output the dict in key order), you can use the following:
{% for k, v in some_dict.items|sort %}
Position {{ k }} has a first value of {{ v.0 }} and has:<br>
{{ v|join:"<br/>" }}
{% for item in v %}
{{ item }}
{% endfor %}
{% endfor %}