I have created a python (2.7) dictionary with the following structure:
cntr_rgns = {'country_1':[region1, region2, region3], 'country_2':[region1, region2] ..}
I pass it to my contextdioctionary as:
ctx['regions'] = cntr_rgns
What I want is to display the values in my template.
In my template view I did that:
{% if regions %}
{% for region in regions.items %}
<option value={{ region }}>{{ region }}</option>
{% endfor %}
{% endif %}
But I again get the unicode values:
(u'Canada',[u'somethong',u'something else',u..])
How can I get back an iteratable JSON or something?
If you want JSON, you need to actually create some JSON.
ctx['regions'] = json.dumps(cntr_rgns)
Related
I am passing a string value to select tag in html form and its working properly. But when I load the page again or run the script again, the previously passed values are not shown in drop down list.
In html form, I am passing value like this:
<option value="{{x}}">{{x}}</option>
In python:
x = "Example"
return render_template('example.html', x=x)
can anyone please let me know how to save this value so that it is available for selection in drop down list.
Thanks in advance!
You could set a list, append new option values in it and then pass the list to your html template. Something like this;
# app.py
optionsList = []
optionsList.append('Example')
optionsList.append('Example2')
return render_template('example.html', options=optionsList)
# example.html
{% if options %}
<select name="foo" id="foo">
{% for option in options %}
<option value="{{ option }}">{{ option }}</option>
{% endfor %}
</select>
{% endif %}
My context dictionary for my Django template is something like the following:
{'key1':'1',
'key2':'2',
'key3':'3',
'key4':{'key5':{'key6':'6', 'key7':'7', 'key8':'8'}}}
I would like to iterate through the dictionary and print something like:
some label = 6
some label = 7
some label = 8
How can I achieve this in my Django template?
What's wrong with this ?
<ul>
{% for key, value in key4.key5.items %}
<li>{{ key }} : {{ value }}</li>
{% endfor %}
</ul>
NB: you didn't ask for looping over all keys in the context, just about accessing key4['key5'] content. if this wasn't wath you were asking for pleasit eadit your question to make it clearer ;-)
I am guessing you want to use a for loop in the django template to do this you must first pass the dictionary to the template in the views file like so make sure you add square brackets around the dictionary like this:
data = [{'key1':'1',
'key2':'2',
'key3':'3',
'key4':{'key5':{'key6':'6', 'key7':'7', 'key8':'8'}}
}]
return render(request,'name of template',{'data':data})
then in the html template:
{% for i in data%}
<p>{{i.key1}}</p>
<p>{{i.key2}}</p>
<p>{{i.key3}}</p>
<p>{{i.key4.key5.key6}}</p>
{% endfor %}
Now when you do the for loop you can access all the iteams in key4 like i have above when I put {{i.key4.key5.key6}}
Here is the docs for the for loop in django templates https://docs.djangoproject.com/en/3.0/ref/templates/builtins/
I am assuming thats what you want to do.
This has worked for me:
{% for key, value in context.items %}
{% ifequal key "key4" %}
{% for k, v in value.items %}
some label = {{ v.key6 }}
some label = {{ v.key7 }}
some label = {{ v.key8 }}
{% endfor %}
{% endif %}
{% endfor %}
If you want to print only what you have mentioned in question then it is possible but if we don't know the exact structure of dictionary then it is possible in django views not in django template.
You can't print value which is also a dictionary one by one in django template,
But you can do this in django view.
Check this post click here and do some changes in views.
I have a context dictionary entry objectives that maps objective query objects to a list of tests that belong to that objective. Example code:
objectives = Objective.objects.filter(requirement=requirement)
context_dict["requirements"][requirement] = objectives
for objective in objectives:
tests = Test.objects.filter(objective=objective)
context_dict["objectives"][objective] = tests
In my django html template, I iterate over objectives and display them. I then want to iterate over the tests that belong to these objectives. When I do this:
{% for test in {{ objectives|get_item:objective }} %}
I get a TemplateSyntaxError: 'for' statements should use the format 'for x in y':
In the application/templatetags directory, I have:
from django.template.defaulttags import register
...
#register.filter
def get_item(dictionary, key):
return dictionary.get(key)
If instead I make {{ objectives|get_item:objective }} a JS variable, I see that it does indeed produce a list, which I should be able to iterate over. Of course, I can't mix JS variables and the django template tags, so this is only for debugging:
var tests = {{ objectives|get_item:objective }}
var tests = [<Test: AT399_8_1>, <Test: AT399_8_2>, <Test: AT399_8_3>, <Test: AT399_8_4>, <Test: AT399_8_5> '...(remaining elements truncated)...']
How do I iterate over this list in the django template tag?
You cannot user {{...}} inside the {%...%}
What you can try is changing your filter to an assignment tag and using that value in the loop
#register.assignment_tag
def get_item(dictionary, key):
return dictionary.get(key)
And then in your template use it as
{% get_item objectives objective as tests %}
{% for test in test %}
....
{% endfor %}
Instead of all this if your models are proper with foreign keys I would do something like
{% for objective in requirement.objective_set.all %}
{% for test in objective.test_set.all %}
....
{% endfor %}
{% endfor %}
In my context I would pass only the requirement
You already have an answer, but note that dropping the {{ }} tags and keeping everything else the same would have worked fine.
{% for test in objectives|get_item:objective %}
**This is Right Answer for Using Django if else and for loop **
Note :- We Have to Put Key in " " string (Double quotes) some time produce an error so That is good way bcz i faced that problem whwn i Learned
{% if 'numbers'|length > 0 %}
{% for i in numbers %}
{% if i > 20 %}
{{i}}
{% endif %}
{% endfor %}
{% else %}
Empty
{% endif %}
I have a for loop in a Django template, which prints out a list of books, which works well. The issue comes when I try to mark one of the items in the list as selected, based on a value passed in from the views.py file:
<select name="b">
<option value="1">Book</option>
{% for book in books %}
<option {% if book.id == selected_book %} selected {% endif %} value="{{ book.id }}">{{ book.t }}</option>
{% endfor %}
</select>
The "books" variable is a list, passed in from the views.py file. I can access these variables fine outside of the loop, but if I try to include a seperate variable inside the loop ("selected_book"), I have issues.
The above code does nothing, and if I try to wrap the variable in double brackets
{{ selected_book }}
I get the following error:
TemplateSyntaxError
Could not parse the remainder: '{{' from '{{'
The variable is being passed into the template, because I can get it to print to the page. I only get an error when I try to use it in the for loop.
If I write "{% if book.id == 2 %}" that works fine.
make sure that selected_book is an integer not a string, otherwise the code is fine
I am trying to use the last.fm API, and the artist search returns the following dictionary with an image:
{u'#text': u'http://userserve-ak.last.fm/serve/34/79694767.png', u'size': u'small'}
However, in my django template, I can't seem to access the value in "#text".
I'm guessing it has to do with the '#' in the name:
My code:
{% for artist in results %}
<li>
{{artist.name}}
{{artist.image.0.#text}}
</li>
{% endfor %}
try this, # shouldnot be the problem:
{% for key, value in results.items %}
{{key}} - {{value}}
{% endfor %}