问题
I am trying to test how to display API information within a view on my Django project. I know you may have to add some installed APIs into the settings INSTALLED APPS block.
This api is a simple geo one.
I am new to Django and new to using APIs within it. I have managed to get my app the way I need it using Youtube videos. But now I am on my own. I have many different view classes to display differents of my app.
The view below is the view Id like to place the data on.
is this how I would potentially do it? Then call {{ base }} within the HTHL to display it?
class PostDetailView(DetailView):
model = Post
template_name = 'clients/post_detail.html'
def api_test(request):
# This is where the APIs are going to go.
requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
data = response.json()
return render(request, 'clients/post_detail.html', {
'base': data['disclaimer']
})
I am currently getting no errors within my app, but the country element isnt displaying.
I have tested the following in just a simple python file
import requests
import json
response = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
data = response.json()
print(data['disclaimer'])
which gets the desired result. So I guess now my issue is...how do i get this into the HTML? So i can display the results from the API
回答1:
You can write like this:
class PostDetailView(DetailView):
model = Post
template_name = 'clients/post_detail.html'
def call_geo_api(self):
# This is where the APIs are going to go.
response = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
data = response.json()
return data['disclaimer']
def get_context_data(self, *args, **kwargs):
context = super(PostDetailView, self).get_context_data(*args, **kwargs)
context['base'] = self.call_geo_api()
return context
Here, I have overridden get_context_data() method, which is responsible for sending context data from view to template.
Here I have changed your api method, so that it will return data['disclaimer']
from the API, and inside get_context_data
method, I have injected it inside context. That should do the trick, so that you will be able to see data in template with {{ base }}
.
来源:https://stackoverflow.com/questions/57173335/using-apis-within-django-and-how-to-display-the-data