从API获取数据并在tempate上显示

时间:2018-05-09 11:26:00

标签: python django api

我正在尝试从stackoverflow API获取数据并将其显示在我模板中的html表中。

到目前为止,我已设法获取数据,但无法在模板中显示它们。我最终得到了最后一个。我知道我的循环是错误的,尝试了一堆东西,但似乎无法搞清楚。

到目前为止我的代码:

def get_questions(request):
    context = {}
    r = requests.get('https://api.stackexchange.com/2.2/questions?fromdate=1525737600&order=desc&sort=activity&tagged=python&site=stackoverflow').json()
    for item in r['items']:
        context['owner'] = item['owner']['display_name']
        context['title'] = item['title']
        #some other attrs here

    template = 'questions/questions_list.html'
    context['greeting'] = 'Hello'

    return render(request,template,context)

我的模板代码: 我还没做过什么花哨的事情。很简单。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>

    <title>Questions</title>
</head>
<body>
    {{ owner }} - {{ title }}
</body>
</html>

1 个答案:

答案 0 :(得分:4)

您需要将结果附加到列表和模板中列出的渲染。

<强>演示: views.py

def get_questions(request):
    context = {}
    r = requests.get('https://api.stackexchange.com/2.2/questions?fromdate=1525737600&order=desc&sort=activity&tagged=python&site=stackoverflow').json()
    dataList = []
    for item in r['items']:
        dataList.append({'owner': item['owner']['display_name'], 'title': item['title']})
        #some other attrs here

    template = 'questions/questions_list.html'
    context['greeting'] = 'Hello'
    context['data'] = dataList

    return render(request,template,context)

<强>模板 迭代您的结果并获取所有数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>

    <title>Questions</title>
</head>
<body>
    {% for i in data %}
        {{ i.owner }} - {{ i.title }}
    {% endfor %}
</body>
</html>