How do display JSON in Django template? Block.io API - json

I am testing the api from block.io https://block.io/api/simple/python
{
"status" : "success",
"data" : {
"network" : "BTCTEST",
"available_balance" : "0.0",
"pending_received_balance" : "0.0",
"balances" : [
{
"user_id" : 0,
"label" : "default",
"address" : "2NCjjB8iVKu9jnYpNcYKxxRYP9w6eWXZAq4",
"available_balance" : "0.00000000",
"pending_received_balance" : "0.00000000"
}
]
}
}
I would like to display for example only the wallet address of the user in question so that he can make a deposit.
My views.py
from django.shortcuts import render
from block_io import BlockIo
version = 2 # API version
block_io = BlockIo('28a8-ba34-8b81-137d', '1111111', version)
def index(request):
balance = block_io.get_address_balance(labels='shibe1')
context = {'balance': balance}
return render(request, 'home.html', context)
home.html
<h1>Block.io API</h1>
{{ balance }}
<h1>I want display example this data</h1>
<h1>Label: default</h1>
<h1>Available balance: 0.00000000</h1>
<h1>Pending received balance: 0.00000000</h1>
<h1>Address: 2NCjjB8iVKu9jnYpNcYKxxRYP9w6eWXZAq4</h1>
When I do this all the data is displayed but example I only want to address
Image displayed data
{'status': 'success', 'data': {'network': 'BTCTEST', 'available_balance': '0.0', 'pending_received_balance': '0.0', 'balances': [{'user_id': 1, 'label': 'shibe1', 'address': '2NADUMWksxJZRKPSNXya8R2LYQY2fGa5mNY', 'available_balance': '0.00000000', 'pending_received_balance': '0.00000000'}]}}
How can I refer only to the data that I want?

You can perform all sorts of lookups on variables in Django Template language using just the . operator. Also your data has a list so you would need to loop over it:
<h1>Block.io API</h1>
<h1>I want display example this data</h1>
{% for bal in balance.data.balances %}
<h1>Label: {{ bal.label }}</h1>
<h1>Available balance: {{ bal.available_balance }}</h1>
<h1>Pending received balance: {{ bal.pending_received_balance }}</h1>
<h1>Address: {{ bal.address }}</h1>
{% endfor %}

Please refer to below file changes :
My views.py
from django.shortcuts import render
from block_io import BlockIo
version = 2 # API version
block_io = BlockIo('28a8-ba34-8b81-137d', '1111111', version)
def index(request):
balance = block_io.get_address_balance(labels='shibe1')
context = {'all_balance': balance['data']['balances']}
return render(request, 'home.html', context)
home.html
<h1>Block.io API</h1>
{% for balance in all_balance %}
<h1>Label: {{ balance.label }}</h1>
<h1>Available balance: {{ balance.available_balance }}</h1>
<h1>Pending received balance: {{ balance.pending_received_balance }}</h1>
<h1>Address: {{ balance.address }}</h1>
{% endfor %}

Related

How can I fetch a value from a JSON dictionary?

I am trying to grab the value green from the below JSON data dictionary.
The API endpoint located at http://localhost:9200/api/status give the below data:
{
"name":"prod01",
"uuid":"3430c40-e786-4325-bc48-e0a096956000",
"version":{
"number":"7.17.0",
"build_hash":"60a9838d21b6420bbdb5a4d07099111b74c68ceb",
"build_number":46534,
"build_snapshot":false
},
"status":{
"overall":{
"since":"2023-02-13T22:47:05.381Z",
"state":"green",
"title":"Green",
"nickname":"Looking good",
"icon":"success",
"uiColor":"secondary"
},
"statuses":[
{
"id":"core:elasticsearch#7.17.0",
"message":"Elasticsearch is available",
"since":"2023-02-13T22:47:05.381Z",
"state":"green",
"icon":"success",
"uiColor":"secondary"
},
{
"id":"core:savedObjects#7.17.0",
"message":"SavedObjects service has completed migrations and is available",
"since":"2023-02-13T22:47:05.381Z",
"state":"green",
"icon":"success",
"uiColor":"secondary"
}
]
}
}
And the test.sls file doing the job is:
{% set json_data = salt.cp.get_url('http://localhost:9200/api/status', dest=None) | load_json %}
{% for key, value in json_data.items() %}
{% if value['state'] == 'green' %}
{{ key }}: {{ value }} (found)
{% else %}
{{ key }}: {{ value }}
{% endif %}
{% endfor %}
Executing it, I get the error:
Rendering SLS 'base:svr.salt.dev.test' failed: Jinja variable 'str object' has no attribute 'state'
You are looping on all the key-value pairs of the object json_data, with json_data.items(), so, you do not have a my_dictionary['state'] anymore, what you have is a key which will be state and its value will be green.
This said, your {"state": "green"} is not in the root of your dictionary, so you will never find any key-value pair matching what you need.
What you can do, though is:
{% if load_json.status.overall.state == 'green' -%}
state: {{ load_json.status.overall.nickname }}
{% endif %}
Which would yield:
state: Looking good

Cannot get API Json data to display on Django Template

I am trying to get data from a JSON, which was fetched from an API I created to display on my Django Template.
The API is just a simple API which store a post hit counts and its id, the json is formatted as below:
[
{
"object_pk": 3,
"hits": 15
},
{
"object_pk": 1,
"hits": 21
}
]
Here is my views.py file:
class BlogListView(ListView):
model = Post
template_name = "home.html"
class BlogDetailView(HitCountDetailView, DetailView):
model = Post
template_name = "post_detail.html"
count_hit = True
data = {
"hits": get_cloudapi_data(),
}
class ResumePageView(TemplateView):
template_name = "resume.html"
And my service.py file, which have the get_cloudapi_data() function:
def get_cloudapi_data():
url = "my-api-address"
r = requests.get(url)
hitcount = r.json()
return hitcount
Below is my HTML template, post_detail.html used for displaying this data:
{% extends "base.html" %}
{% load hitcount_tags %}
{% block content %}
<div class="post-entry">
<h2>{{ post.title }}</h2>
<p> {% get_hit_count for post %} views</p>
<p> {{ post.body }}</p>
{% for hit in hits %}
<p>{{ hit.object_pk }}</p>
<p>{{ hit.hits }}</p>
{% endfor %}
</div>
{% endblock content %}
It only shows the title, body and the hit count retrieve with the hitcount app not my API data
I have printed out the hitcount and the data if it would help
hitcount
[{'object_pk': 3, 'hits': 15}, {'object_pk': 1, 'hits': 21}]
data
{'hits': [{'object_pk': 3, 'hits': 15}, {'object_pk': 1, 'hits': 21}]}
I am new to working with an API with Django, so I am unsure where I went wrong.

Code not executing and displaying in Html (Flask)

#Flask Code
from flask import Flask, render_template
app = Flask(__name__)
posts = [
{
'author': 'User',
'title': 'Test',
'content': 'First post',
'date_posted': '2021, 4 ,13',
},
{
'author': 'User2',
'title': 'Flask is cool',
'content': 'Flask testing',
'date_posted': '2021, 4 ,14'
}
]
#app.route('/')
#app.route('/home')
def hello():
return render_template('home.html', posts=posts)
#ignore this
#app.route('/about')
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug=True)
#HTML Code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% for post in posts %}
<p>By {{ posts.author }} on {{ posts.date_posted }}</p>
<p>By {{ post.content }}</p>
{% endfor %}
</body>
</html>
the for loop is executing but the values in the dict. are not displaying, I am very new in flask
so I'm pretty sure I have to add in some extra code..? Any help is appreciated :D
Use your loop variable post inside your for loop instead of posts.
{% for post in posts %}
<p>By {{ post.author }} on {{ post.date_posted }}</p>
<p>By {{ post.content }}</p>
{% endfor %}

gulp-nunjucks-render and adding data from single file

How can I include data to gulp-nunjucks template from separate file?
//template/data/data.html
{% set
list = [
{
title: 'Item1'
},
{
title: 'Item2'
}
]
%}
This simple solution doesn't work.
{% include "data/json.html" %}
This should work if you use import instead of include, https://mozilla.github.io/nunjucks/templating.html#import
Try this (I used .njk extensions, but you can use .html, it won't matter):
//template/data/data.njk
{% set list = [
{
title: 'Item1'
},
{
title: 'Item2'
}] %}
And in the file where you want to use the {{ list }} variable:
//template/other-file.njk
{% from 'data/data.njk' import list %}
{{ list }}
Any top-level variables that are {% set %} or any macros that are defined are available via import.

Encoding JSON in a GitHub Pages generated file

I'm attempting to create a JSON feed on a GitHub Pages site, and I'm having issues with JSON because I'm not sure how I can properly encode it using Jekyll. Is there an extension or method I can use?
feed: http://iowacodecamp.github.io/sessions.json
source: https://github.com/IowaCodeCamp/iowacodecamp.github.io/blob/master/sessions.json
Note the double quotes in the data.
Your json doesn't validate because of the coma after the last session.
If you don't want a coma after the last session, use forloop liquid object around
{
"sessions": {
"session": [{% for session_hash in site.data.sessions %}{% assign session = session_hash[1] %}
{
"title": {{ session.title | jsonify }},
"description": {{ session.description | jsonify }},
"level": {{ session.level | jsonify }},
"author": {
"name": {{ session.speaker.name | jsonify }},
"slug": {{ session.speaker.slug | jsonify }}
}
}{% if forloop.last == false %}, {% endif %}{% endfor %}
]
}
}
Question : You have multiples sessions in your datas but they are all in the same session array. Do you really need this key ? Maybe you can just do :
{
"sessions": [{% for session in site.data.sessions %}
{{ session[1] | jsonify }}{% if forloop.last == false %}, {% endif %}{% endfor %}
]
}
Which also validates.
I found a list of filters in the documentation: http://jekyllrb.com/docs/templates/
Proper usage is:
{{ session.description | jsonify }}