passing data json using django templates to the front (html) - html

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

Related

django grpc json response to html template

need some help. Spent all day trying different permutations to no avail.
I am making a grpc call and formatting the response to a json. My goal is to pass the data onto my html template so I can format it how I want. The only thing I can get to work is to print the json on the page which is not what I want.
return JsonResponse(result, safe=False)
^ this prints json on page but I actually want to populate certain parts to a table.
I tried the following (not all at once obviously):
return HttpResponse(branch_list)
return HttpResponse(response, 'src/grpc.html', {'branch_list', branch_list})
return HttpResponse(response, 'src/grpc.html', {'branch_list',branch_list})
return render(request, 'src/grpc.html', {'branch_list': response})
return JsonResponse(result, safe=False)
return HttpResponse(json.dumps(branch_list), 'src/grpc.html', content_type="application/json")
This is my definition I am using in my views.py which works with the return statement
I pasted above:
...
def grpc(client_stub, payload_project_id=payload_project_id, grpc_stub_method=grpc_stub_method, metadata_okta_token_and_env=metadata_okta_token_and_env):
client_stub = BitcClient(server, port)
request = pb2.ListBranchesRequest(context=payload_project_id)
response = client_stub.get_grpc_stub(grpc_stub_method).ListBranches(request=request,
metadata=metadata_okta_token_and_env)
#print(response)
json_obj = MessageToJson(response)
result = json.loads(json_obj)
for data in result['branches']:
# print(data['branch'])
branch_list.append(data['branch'])
return <need help here>??????????
I would like to loop through branch_list in my html template and sprint the branch name and branch status in a table in grpc.html template:
{% if branch_list %}
<ul>
{% for branch in branch_list %}
<li>{{ branch.branch }}: {{ branch.status }}</li>
{% endfor %}
</ul>
{% else %}
<p>No branches were found.</p>
{% endif %}
my urls.py looks like this:
from django.urls import path
from . import views
urlpatterns = [
path('', views.grpc, name='grpc'),
]
help is greatly appreciated. thanks
So the correct return line needs to be: return render(request, 'src/grpc.html', result)

Recursively display file tree structure with Tornado template

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 %}

Django pass variable into template

Hi thank you for helping, I'm poor in coding.
To point: I'm doing a Django project that pass data form data-base to front-end; but right now i can't even pass anything views of Django into templates, I suspect i'm passing the wrong variable types; please do comment on your thought.
This is my code on views.py:
from django.shortcuts import render
def index (requset):
return render(requset,'myapp/index.html') # link to be able open frountend
def testdex(requset):
text = "hello world"
context ={'mytext' : text }
return render(requset,'myapp/inculdes.html', context)
so my variable will be pass into inculdes where extend to index page
This my codes on in inculdes.html:
{% exntends "myapp/index.html" %}
{% block includes %}
{{ mytext }}
{% endblock includes %}
this my code on index.html:
<body>
{% block includes %} {% endblock includes %}
</body>
Thanks again on giving me your time to help me and appreciate it if could write me some code because try fix this for whole week
You can try something like this:
views.py
from django.template.response import TemplateResponse
def testdex(request, template_name="myapp/includes.html"):
args = {}
text = "hello world"
args['mytext'] = text
return TemplateResponse(request, template_name, args)
includes.html
{% extends "myapp/index.html" %}
{% block includes %}
{{ mytext }}
{% endblock includes %}
And make sure you have set path for templates in settings.py
When you do {% block content %}{% endblock content %} you are telling Django that you want to be able to overwrite this section. Please note the word content can be anything to reflect what you want to overwrite.
When you do {{ variable }} you are telling Django that you want to pass a Context. In this example, variable I want to pass is called Title as the key and Portfolio as the value. Context is a dictionary that you pass in views.py like this:
def portfolio_home(request):
return render(request, 'portfolio/work.html', {'title': 'Portfolio'})
Let's say I want to pass a context (or a variable) into my base template. In this example, I want to pass title in the title tag of the head section of my base template.
In the html file for base.html, you need to have something like this:
<!DOCTYPE html>
<html lang="en">
{% load staticfiles %}
<head>
<title>{{ title }}</title>
...........
</head>
</html>
In the urls.py of my project and other apps that I want to pass a title into this, I should create the view like this:
def portfolio_home(request):
return render(request, 'portfolio/work.html', {'title': 'Portfolio'})
I found out why Django can't pass variables to HTML because;
I didn't have my apps url activated the function/model in views
I feel so embarrasses, for such simple mistakes.
All I need to do is add this code in my apps url
urlpatterns = [
path('', views.timedex, name='timedex'), #need add this
path('', views.index, name='index'),
]
Add {{block.super}} before {% endblock includes %}

Flask, jinja2 - Dynamically append templates one after another

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 %}

How to navigate json objects in django templating language

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 %}