Djang中的API整合

2024-09-29 23:33:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在我的项目中使用opendotaapi。目前,我在将API的内容显示到CBV时遇到问题。在

我的视图.py公司名称:

from django.views.generic import TemplateView

import requests
import json

# Create your views here.


class HeroList(TemplateView):
   template_name = 'dota/heroes.html'
   url = 'https://api.opendota.com/api/heroes'
   r = requests.get(url)
   r.text
   result = r.json()

我不知道如何在HTML中调用json。我尝试过在pythonidle中运行相同的代码,当我输入“result”并点击enter时,它给出了dict?在


Tags: 项目import视图apijsonurl内容result
2条回答

您需要做的是首先将json转储为字典格式。在

import json
from django.shortcuts import render

rdict = json.loads(r.json())

return render(request, template_name=<template name>, context=rdict)

所有这些都存在于你的功能中视图.py在

现在在这之后使用Django模板语言-https://docs.djangoproject.com/en/1.11/topics/templates/

您可以将字典中键中的数据呈现到模板中。在

如果你的意思是用html访问结果,那么下面是一个示例。在

选项={'key1':'val1','key2':'val2'}

模板如下:

<ul>
{% for key, value in choices.items %} 
  <li>{{key}} - {{value}}</li>
 {% endfor %}
</ul>

从这个答案how to access dictionary element in django template?

相关问题 更多 >

    热门问题