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)
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'm new with django and i'm trying to update fields in my view without redirecting, i'm trying to return a JSON file when a view function is called, but i can't seem to find how to do so withouth redirecting to some url.
I think it may have something to do with my urls.py: ... path('#', views.myFunction, name='myFunctionName').
I'm messing arround with the django tutorial that appears in djangoproject.com
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li
{% endfor %}
</ul>
Vote again?
doFunction
my view function goes like this:
def myfunction(request):
return JsonResponse({'ayy':'lmao'})
and the urls.py:
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
path(r'#', views.myfunction, name='myfunction'),
path('form', views.FormView.as_view(), name='form'),
So what is most likely happening here is the Django URLS is finding the index page and redirecting to that view. The # pound or number symbol usually indicates a redirect in page.
First, there's no AJAX in your code. doFunction will redirect to an entire new page.
Second, your path to myfunction in urls.py is not correct.
Here's an example of what you can do. I also suggest you to read this. I use JQuery but feel free to adapt with what you prefer.
urls.py:
#...
path('ajax/domyfunction/', views.myfunction, name='myfunction')
]
html template:
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize}}</li
{% endfor %}
</ul>
Vote again?
<button id="b_function">doFunction</button>
<script>
$("#b_function").click(function () {
$.ajax({
url: '{% url "polls:myfunction" %}',
dataType: 'json',
success: function (data) {
alert(data.ayy);
}
});
});
</script>
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 %}
I am parsing json in Django Views with following code:
def xyz(request):
url =" https://tools.vcommission.com/api/coupons.php?apikey=952d164efe86ca9ec33a1fdac8e6d0b6d4c02c92f44062bf8b646ad04ebf8cdc "
response = urllib.request.urlopen(url)
data1 = json.loads(response.read())
context = {"data1": data1}
template = 'coupons/store/myntra.html'
return render(request, template, context)
Now I am using this code in my template file
{% for item in data1 %}
{% if item.offer_id == "1022" %}
{{ item.coupon_title }} <br>
{% endif %}
{% endfor %}
All code is working fine but when I view my template html source code it is more than 10K lines.
It's taking more time to load.
Please suggest some ways.
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