If I pass in a json object from my view i.e. return render(request, 'development/index.html', {'data': data}), where data is {a:{"colA":12,"colB":13"},b:{"ColA":1","colB":2"}}, how can I populate a select in index.html with all the values in ColA?
You should be populating selects with options using django forms, not in template.
But if you absolutely have to do it in template then you can loop through dict like this:
{% for item in data.iteritems %}
{{ item.colA }}
{% endfor %}
Related
I want to display the file tree inside a particular folder (RESULTS) on my html page. I am using python Tornado. I used the answer to this question to get me most of the way, and modified to try and work with Tornado.
With the code below, the top directory is displayed as the header, and the folders inside the top directory are displayed, but the template doesn't loop through the items in the subtrees.
Here is the render call:
def get(self):
logging.info("Loading Results tree...")
self.render("results.html", tree=make_results_tree('RESULTS'))
Here is the make_results_tree function:
def make_results_tree(path):
tree = dict(name=path, children=[])
lst = os.listdir(path)
if (path == 'RESULTS' and len(lst) == 1):
tree['children'].append(dict(name="No results recorded for today"))
else:
for name in lst:
fn = os.path.join(path, name)
if os.path.isdir(fn):
tree['children'].append(make_results_tree(fn))
elif (name != '.gitkeep'):
tree['children'].append(dict(name=name))
return tree
I have verified that the python code above all works as intended, thus the issue is in the template code below (results.html), likely in the if or loop block:
<div class="center">
<h2>{{ tree['name'] }}</h2>
<ul>
{% for item in tree['children'] %}
<li>{{ item['name'] }}
{% if locals().get('item["children"]', False) %}
<ul>{{ loop(item['children']) }}</ul>
{% end %}</li>
{% end %}
</ul>
</div>
Why does the template code not loop through multiple levels of the tree?
loop() is a feature of Jinja2; there is no equivalent in Tornado templates. Instead of anonymous recursion, split the file into two files so that the inner file can call itself recursively.
Also, locals().get() only performs simple lookups, it can't resolve complex expressions like eval() can. You don't need locals here, just operate on item directly.
results.html:
<div class="center">
<h2>{{ tree['name'] }}</h2>
<ul>{% module Template('items.html', children=tree['children']) %}</ul>
</div>
items.html:
{% for item in children %}
<li>{{ item['name'] }}
{% if "children" in item %}
<ul>{% module Template('items.html', children=item['children']) %}</ul>
{% end %}</li>
{% end %}
I am getting an array arr passed to my Django template. I want to access individual elements of the array in the array (e.g. arr[0], arr[1]) etc. instead of looping through the whole array.
Is there a way to do that in a Django template?
Remember that the dot notation in a Django template is used for four different notations in Python. In a template, foo.bar can mean any of:
foo[bar] # dictionary lookup
foo.bar # attribute lookup
foo.bar() # method call
foo[bar] # list-index lookup
It tries them in this order until it finds a match. So foo.3 will get you your list index because your object isn't a dict with 3 as a key, doesn't have an attribute named 3, and doesn't have a method named 3.
arr.0
arr.1
etc.
You can access sequence elements with arr.0, arr.1 and so on. See The Django template system chapter of the django book for more information.
When you render a request to context some information, for example:
return render(request, 'path to template', {'username' :username, 'email' :email})
You can access to it on template, for variables
{% if username %}{{ username }}{% endif %}
for arrays
{% if username %}{{ username.1 }}{% endif %}
{% if username %}{{ username.2 }}{% endif %}
you can also name array objects in views.py and then use it as shown below:
{% if username %}{{ username.first }}{% endif %}
I am building a chatbot. There are few child templates like login.html, messages.html, transaction.html, etc. I want to append these templates in base.html dynamically. I am extending base.html in all these templates. My problem is only one template is rendered at a time. Is there any solution for appending these templates one after another? I have used {%include%} but it's a static approach. I need dynamic.
printer.py looks like -
#app.route('/respond', methods=['GET','POST'])
def respond_def():
message = request.form['message_input']
if message == "l":
return render_template('printer/login.html')
elif message == "t":
return render_template('printer/transactionID.html')
base.html looks like -
//some code here
<li>
{% block template %}{% endblock %}
</li>
//some code here
message.html looks like -
{% extends "base.html" %}
{% block template %}
<div> Message template called </div>
{% endblock %}
I resolved it.
I made a list of templates in printer.py and then appended those templates in base.html whenever user asked for it.
printer.py
dictionary = []
// append name of template in this whenever needed.
return render_template('printer/base.html', dictionary=dictionary)
base.html
{% for d in dicts %}
{% set template = 'printer/' + d + '.html' %}
// can add conditions for different templates
{% include template %}
{% endfor %}
I have a problem to send json data using django templates to the front (html).
This is the python code:
#api_view(['GET'])
#renderer_classes((JSONRenderer,))
def tasks_list_all(request):
i = inspect()
tasks_dic=i.registered_tasks()
for cle in tasks_dic.keys():
key=cle
tasks_old_v=tasks_dic.get(key)
tasks_new_v=[]
for tasks in tasks_old_v:
new_tasks=tasks.replace('infra_mngt.tasks.','')
tasks_new_v.append(new_tasks)
add_new=tasks_new_v[-1].replace('provisionning.celery.','')
tasks_new_v[-1]=add_new
tasks_new_v_new=json.dumps(tasks_new_v)
print "json.dumps(tasks_new_v)",tasks_new_v_new
#~ return render(request, os.path.join(settings.BASE_DIR, 'infra_mngt', 'templates', 'tasks_all.html'), context={'list':tasks_new_v})
#~ return render(request, os.path.join(settings.BASE_DIR, 'infra_mngt', 'templates', 'tasks_all.html'),{'list':tasks_new_v})
return render(request, os.path.join(settings.BASE_DIR, 'infra_mngt', 'templates', 'tasks_all.html'),{'list':tasks_new_v_new})
this is the code of the front (tasks_all.html):
<h1>Dynamic list tasks</h1>
{% for list in tasks_new_v_new %}
{{ list }}
{% endfor %}
But after execution, I don't get any elements of the list that I need, just the display of this html code:
<h1>Dynamic list tasks</h1>
you're passing the wrong context to the template (or you're using the wrong variable in the template)
try something like (in the view):
return render(request, your_template, {"tasks": tasks_new_v_new})
in the template:
{% for task in tasks %}
{{ task }}
{% endfor %}
notice I'm passing a variable called tasks to the template and in the template I'm looping that variable.
Hope this helps
I have a query result on my views and i drop to my template, on my template i want to display values of my table, so i use
{{myTable.0}} and {{myTable.1}}
and i have the result of my query, but i want to display this values with a variable like {{myTable.x}} where x =0 to use in a loop for.
But it doesn't work, so if you have any solution.
Seems like myTable is a list an you want to iterate through this list. If so then you can use the {% for %} template tag:
{% for val in myTable %}
{{ val }}
{% endfor %}