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.
Related
I want to get m2m data in my template through the views but failing to do so. The thing is that I'm able to show the data of m2m field looping it from template itself but it does slow down the website.
My Team apps Model looks like this:
class Team(models.Model):
title = models.CharField(max_length=255)
team_country = CountryField(max_length=200, blank=True, null=True)
members = models.ManyToManyField(User, related_name='teams')
created_by = models.ForeignKey(User, related_name='created_teams', on_delete=models.CASCADE)
Now in my tournament app I'm trying to get "members" of the team.
My Tournamet Views look like this:
def tournament_page(request, slug):
page = 'tournament_page'
user = request.user
tournament = Tournament.objects.get(slug=slug)
players = tournament.participants.select_related('user')
all_players = Profile.objects.select_related('user')
side_tourneys_ongoing = Tournament.objects.filter(state='Ongoing')[:10]
side_tourneys_upcoming = Tournament.objects.filter(state='Upcoming')[:10]
side_tourneys_completed = Tournament.objects.filter(state='Completed')[:10]
teams = Team.objects.select_related('created_by')
context = {
'page': page,
'tournament': tournament,
'side_tourneys_ongoing': side_tourneys_ongoing,
'side_tourneys_upcoming': side_tourneys_upcoming,
'side_tourneys_completed': side_tourneys_completed,
'teams': teams,
'players':players,
'all_players':all_players
}
Now I'm able to show the teams with their members in the template using for loop inside the template itself as:
Html template
<div class="grid-x">
{% for team in teams %}
{% for player in players %}
{% if team.id == player.active_team_id and team.game == tournament.game %}
<div class="wf-card event-team">
<div> {{team.title}} </div>
<div class="event-team-players">
{% for member in team.members.all %}
{{ member.username }}
{% endfor %}
</div>
</div>
{% endif %}
{% endfor %}
{% endfor %}
</div>
What I want is to use this piece of code
{% for member in team.members.all %}
{{ member.username }}
{% endfor %}
in my views since it causes the website to slow down and idk why.
What I tried in my views is:
all_teams = Team.objects.all()
members = all_teams.members.all()
and
members = Team.objects.all().prefetch_related('members')
First one throws an error:
'QuerySet' object has no attribute 'members'
Second one shows lots of blank records
Tried almost everything with search but none of them helped except using the code that I provided directly in the template itself.
Edited based on comments below. You should be able to do this more simply by prefetching team members.
views.py
def tournament_page(request, slug):
page = 'tournament_page'
user = request.user
tournament = Tournament.objects.get(slug=slug)
all_players = Profile.objects.select_related('user')
side_tourneys_ongoing = Tournament.objects.filter(state='Ongoing')[:10]
side_tourneys_upcoming = Tournament.objects.filter(state='Upcoming')[:10]
side_tourneys_completed = Tournament.objects.filter(state='Completed')[:10]
teams = Team.objects.select_related('created_by').prefetch_related('members')
template.html
<div class="grid-x">
{% for team in teams %}
{% if team.game == tournament.game %}
<div class="wf-card event-team">
<div> {{team.title}} </div>
<div class="event-team-players">
{% for member in team.members.all %}
{{ member.username }}
{% endfor %}
</div>
</div>
{% endif %}
{% endfor %}
</div>
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 %}
I'm very new to HTML and web development so forgive me is this is an easy fix. QuickChart.io provides an image after calling the API. I've created a Django application that creates a custom URL to call QuickChart in my view file but struggling to have it appear when loading the page.
My HTML is the following:
{% block content %}
<img src=quickchart_url>
<p>{{ quickchart_url }}</p>
{% endblock %}
My view is the following:
from django.shortcuts import render
from quickchart import QuickChart
def about(request):
return render(request, 'stormglass_web_client/about.html', {'quickchart_url': qc_url})
qc = QuickChart()
qc.width = 500
qc.height = 300
qc.device_pixel_ratio = 2.0
qc.config = {
"type": "bar",
"data": {
"labels": ["Yes", "No"],
"datasets": [{
"label": "Yes or No",
"data": [1, 2]
}]
}
}
qc_url = (qc.get_url)
The site loads as follows:
I can copy and paste the URL in a browser and it displays as intended. Just trying to figure out how I can have this appear from HTML as an embedded image.
Silly mistake on my part. HTML should be:
{% block content %}
<img src= {{ quickchart_url }}>
<p>{{ quickchart_url }}</p>
{% endblock %}
I'm trying to loop through a nested json file with nunjucks, give each object type a specific layout and sort all based on date.
So in my case I have two collections events and videos. Both collections will have an array of events and videos.
My file is named /content.json and structured as followed:
{
media: {
events: [
{
content_id: "1",
content_type: "event",
date: "01-11-2019",
etc: "etc"
},
{
content_id: "2",
content_type: "event",
date: "01-08-2019",
etc: "etc"
}
],
videos: [
{
content_id: "3",
content_type: "video",
date: "01-12-2019",
etc: "etc"
},
{
content_id: "4",
content_type: "video",
date: "01-09-2019",
etc: "etc"
}
]
}
}
I have tried to get the different object assigned with an if/else statement and then use a for loop to cycle through the array, but that has failed, see below:
{% for item in content.media %}
{% if item == events %}
{% for item in content.media.events %}
{% include "components/event.njk" %}
{% endfor %}
{% elif item == video %}
{% for item in content.media.videos %}
{% include "components/video.njk" %}
{% endfor %}
{% endif %}
{% endfor %}
I never got to try and sort all the content by date, but I have found:
{% for item in items|sort(attribute='date')%}
Can anyone guide me in right direction?
Thanks in advance.
AENM
This code outputs separated feeds by type of elements (event or video).
{% for event in content.media.events | sort(attribute = 'date') %}
{% include "components/event.njk" %}
{% endfor %}
{% for video in content.media.videos | sort(attribute = 'date') %}
{% include "components/video.njk" %}
{% endfor %}
If you need to output a mixed feed, you should join arrays to one and run trought it (fortunately each elements already have the type):
{% for item in [].concat(content.media.events, content.media.videos) | sort(attribute = 'date') %}
{% include "components/" + item.content_type + ".njk" %}
{% endfor %}
Aikon,
I got it now!!
It was another typo, you switched the media and events. (did you try to keep me sharp?! :-))
But that's why the concat didn't work!!
So this is the final working result:
{% for item in [].concat(media.content.events, media.content.videos) | sort(attribute = 'date') %}
{% include "components/" + item.type + ".njk" %}
{% endfor %}
Only the date is not in the correct order, but I think that has to with my grid setup.
Thanks for helping me out......
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.