I have dictionary in my django template. When i simply output it using {{ x.servicestate }} it will print its contents into html:
[{'efefefef': 'blad'}, {'efef': 'blad'}, {'eerer': 'blad'}, {'aaa': 'blad'}, {'b': 'blad'}, {'ererer': 'blad'}]
But when i use this to iterate:
{% for key,value in x.service_state %}
{{ key }}<br>{{ value }}
{% endfor %}
It will only output its keys:
efefefef
efef
eerer
aaa
b
ererer
What am i doing wrong?
You want iterate the dict, so you need to handle it. Try doing this:
For this list:
[{'efefefef': 'blad'}, {'efef': 'blad'}, {'eerer': 'blad'}, {'aaa': 'blad'}, {'b': 'blad'}, {'ererer': 'blad'}]
Let's call it blah
{% for b in blah %}
{% for k, v in b.items %}
{{ k }}, {{ v }} <br>
{% endfor %}
{% endfor %}
Related
I have such object:
data[ 'aaa' ] = ['1', 'something1']
data[ 'bbb' ] = ['2', 'something2']
And want to display it (using loop ) in template :
{% for row in data %}
<span>{{ row }}</span>>
{% for d in data.row %}
{{ d.0 }} || {{ d.1 }}
{% endfor %}
{% endfor %}
But i see only values within the span tag ( even though array is not empty )
Can you tell me what I am doing wrong ?
Thanks in advance,
The way you're trying to iterate over each row doesn't make sense - either you iterate, or you fetch by index, but doing both will not work. Try this instead:
{% for row in data %}
{{ d.0 }} || {{ d.1 }}
{% endfor %}
I have a tuple, such that
{{VISIBILITY_CHOICES.1.1}}
Outputs "hello".
I have model "task" with a attribute "visibility_status", and in a loop, say all the iterations of task.visibility_status outputs 1
{{task.visibility_status}}
Outputs 1.
How do I use this task.visibility_status inside the lookup of the tuple? Something like VISIBILITY_CHOICES[task.visibility_status][1] in a different language.
I'm very new to django... Thanks a lot.
edit:
The code I was running:
{% for task in tasks %}
<div class="post">
<h1>{{ task.subject }}</h1>
<div class="date">
<p>Due: {{ task.due_date }}</p>
<p>Assigned to: {{task.assigned_to}}</p>
</div>
<p>{{ task.text_area|linebreaks }}</p>
{% with args=""|add:task.visibility_status|add:",1" %}
<p>Visibility Status: {{VISIBILITY_CHOICES|get_index:args}}({{ task.visibility_status }})</p>
{% endwith %}
<p>Case Status: {{ task.case_status }}</p>
<div class="date">
<p>Created: {{ task.created_date }} by {{ task.author }}</p>
</div>
</div>
{% endfor %}
Although the builtin name tuple may not have any syntactic meaning in a template, I'll use my_tuple in its place in the code below.
I've used with to create a context that builds the args for indexing my_tuple (i.e task.visibility_status and 1): :
{% with x=task.visibility_status|stringformat:"s" %}
{% with args=x|add:",1" %}
{{ my_tuple|get_index:args }}
{% endwith %}
{% endwith %}
And in the custom template filter, I've splitted and recreated the arguments and used indexing in plain python to return the item at the index:
from django import template
register = template.Library()
#register.filter
def get_index(my_tuple, args):
arg1, arg2 = args.split(',') # split on the comma separator
try:
i = int(arg1)
j = int(arg2)
return my_tuple[i][j] # same as my_tuple[task.status][1]
except:
return None
I've read this, and I have an array like that:
context[u'erreurs'] = {
'aa': {'titres': [], 'liste': [], 'urls': []},
'bb': {'titres': [], 'liste': [], 'urls': []},
'...': {'titres': [], 'liste': [], 'urls': []}
}
If there's an error, 'titres', 'liste' and 'urls' become array of strings, filled with adequates values.
In my template, if erreur is set I do this:
{% for idx, tab in erreurs.items %}
<ul>
{% for e in tab.liste %}
{% if user.is_authenticated %}
<li>{{ e }}</li>
{% else %}
<li>{{ e }}</li>
{% endif %}
{% endfor %}
</ul>
{% endfor %}
I would like to use the current index to use the value that is in another array, here: tab.urls. It doesn't work and gives me the error:
Could not parse the remainder: '[forloop.counter0]' from 'tab.urls[forloop.counter0]'
How to solve this?
Unfortunately, Django's templates don't support such syntax. You should put together a custom template filter:
# yourapp/templatetags/yourapp_tags.py:
from django import template
register = template.Library()
#register.filter
def at_index(array, index):
return array[index]
and use it like:
{% load yourapp_tags %}
{{ tab.urls|at_index:forloop.counter0 }}
You need to make an actual model that represents the data then the task becomes trivial
class YourModel(object):
titre = ''
liste = ''
url = ''
context[u'erreurs'] = {
'aa': [], # List of model
}
{% for idx, tab in erreurs.items %}
<ul>
{% for model in tab %}
{{ model.titre }}
{{ model.liste }}
{{ model.url }}
{% endfor %}
</ul>
{% endfor %}
Can something like this be done in django?
{% for item in lst %}
{{ something_{{ item }} }}
{% endfor %}
Args passed to render would be for example:
{"lst": range(3), "something_0": "aaa", "something_1": "aaa", "something_2": "aaa"}
No. Structure your data as a list of dicts.
[
{'something': 'aaa', 'something_else': 'bbb', ...},
{'something': 'ccc', 'something_else': 'ddd', ...},
...
]
and now:
{% for item in lst %}
{{ item.something }}
{{ item.something_else }}
{% endfor %}
I'm not sure the most efficient way to iterate over my nested dictionaries to print a matrix of the total and good values for every fruit for each date. Take for instance the two lists and dictionary below:
fruits = ['apples','oranges','bananas']
harvest_dates = ['2011-07-23','2011-07-22','2011-07-21']
harvest_data = {
'apples': {
'2011-07-23': {
'total': 100,
'good': 80},
'2011-07-22': {
'total': 97,
'good': 92},
'2011-07-21': {
'total': 90,
'good': 85}
},
'oranges': {
'2011-07-23': {
'total': 86,
'good': 82},
'2011-07-22': {
'total': 90,
'good': 75},
'2011-07-21': {
'total': 92,
'good': 92}
},
'bananas': {
'2011-07-23': {
'total': 10,
'good': 9},
'2011-07-22': {
'total': 12,
'good': 11},
'2011-07-21': {
'total': 9,
'good': 9}
}
}
I can easily do this in python:
for fruit in fruits:
for day in harvest_dates:
print "harvest: %s" % harvest_data[fruit][day]['total']
print "good crop: %s" % harvest_data[fruit][day]['good']
But I don't know how to access this data in django templates. I had been trying something such as:
{% for fruit in fruits %}
...
{% for day in harvest_dates %}
...
{{ harvest_data.fruit.day.total }}
{{ harvest_data.fruit.day.good }}
...
{% endfor %}
{% endfor %}
But it's simply not working.
{% for fruit in fruits %}
{{ harvest_data.fruit }} <--- this does not exist
{{ harvest_data[fruit] }} <--- this does not work
{% endfor %}
I'm a complete amateur and I'm probably going about this all wrong, but I've Google'd quite a bit and it's not clear to me what the best approach to getting the data I want is.
Since you're familiar with python, the following is logically how you would want to iterate through your dictionary in a Django template:
for key,value in harvest_data.items():
... print key
... for key2,value2 in value.items():
... print key2
... for key3,value3 in value2.items():
... print "%s:%s"%(key3,value3)
In your template, this translates as follows:
{% for key, value in harvest_data.items %}
{{ key }} <br>
{% for key2,value2 in value.items %}
{{ key2 }} <br>
{% for key3, value3 in value2.items %}
{{ key3 }}:{{ value3 }} <br>
{% endfor %}
{% endfor %}
{% endfor %}
The Django docs actually briefly include an example of how to iterate through dictionaries when describing how the for template tag works:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
as rolling stone says thats the way to iterate over dictionaries in templates, i would only change the key, value keywords for different keywords in every iteration like this:
{% for key, value in harvest_data.items %}
{{ key }} <br>
{% for key2,value2 in value.items %}
{{ key2 }} <br>
{% for key3, value3 in value2.items %}
{{ key3 }}:{{ value3 }} <br>
{% endfor %}
{% endfor %}
{% endfor %}
just for the sake of clarity :)
And if you want to line up your values i would suggest you use another data structure where you can sort by date, for example a something like this:
{ 'oranges' : [(date1, value1), (date2,value2)] ...}
Try to do the least possible operations in your templates, so dont do a sort or nested if's if you dont have to
Really old question, but I will add my 1.5c.
This is a good use case of the regroup tag (https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#regroup) and a bit of data refactoring:
Have your data as a simple list of data points:
harvest_data = [
{'fruits': 'apples', 'date': '2011-07-23', 'total': 100, 'good': 80},
# ...
]
In your template, group by the chosen dimension(s):
{% regroup harvest_data by fruits as data_by_fruits %}
{% for data in data_by_fruits %}
<h1>{{ data.grouper }}</h1> # 'apples'
{% regroup data.list by date as data_by_fruits_date %}
{% for data_1 in data_by_fruits_date %}
<h2>{{ data_1.grouper }}</h2> # '2011-07-23'
{% for datapoint in data_1.list %}
total: {{ datapoint.total }} <br/>
good: {{ datapoint.good }} <br/>
{% endfor %}
{% endfor %}
{% endfor %}