在Django中使用API以及如何显示数据 [英] Using APIs within Django and how to display the data
问题描述
我正在尝试测试如何在Django项目的视图中显示API信息。我知道您可能必须将一些已安装的API添加到INSTALLED APPS设置块中。
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.
此api是一个简单的地理区域应用程序。
This api is a simple geo one.
我是Django的新手,也是第一次使用api。我已经通过YouTube视频成功地按照自己的方式获取了我的应用。但是现在我自己一个人。我有许多不同的视图类来显示我的应用程序的不同之处。
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.
这是我可能会这样做的方式吗?然后在HTHL中调用{{base}}来显示它?
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']
})
我目前在我的应用程序中没有收到任何错误,但是没有显示country元素。
I am currently getting no errors within my app, but the country element isnt displaying.
我已经在一个简单的python文件中测试了以下内容
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'])
这将获得所需的结果。所以我想现在我的问题是...如何将其导入HTML?这样我就可以显示API的结果
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
推荐答案
您可以这样写:
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
这里,我有覆盖 get_context_data()
方法,该方法负责将上下文数据从视图发送到模板。
Here, I have overridden get_context_data()
method, which is responsible for sending context data from view to template.
在这里,我更改了您的api方法,以便它将从API返回 data ['disclaimer']
,并在 get_context_data
方法内部,已将其注入上下文中。这样就可以解决问题,以便您可以使用 {{base}}
看到模板中的数据。
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 }}
.
这篇关于在Django中使用API以及如何显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!