如何将变量从 Python API 传递到 Django 模板 [英] How to pass variable from Python API to Django template

查看:45
本文介绍了如何将变量从 Python API 传递到 Django 模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用这个 Python 运动数据 API Sportsipy.设置非常简单,我可以将数据保存到 var 并将其打印到终端,但是当我将它添加到上下文时,通过我的 Django 模板传递它,什么也没有显示.

我尝试在 HTML 端以几种不同的方式调用它,但我仍然无法弄清楚.

API 端点文档截图

在 Schedule 端点下https://sportsreference.readthedocs.io/en/stable/ncaab.html#module-sportsipy.ncaab.boxscore

 def games(request):"查看返回游戏页面"team_schedule = Schedule('PURDUE')打印(team_schedule)对于 team_schedule 中的游戏:away_total_rebounds = game.boxscore.away_total_rebounds打印(离开_总计_反弹)上下文 = {'team_schedule':team_schedule,'away_total_rebounds': away_total_rebounds,}返回渲染(请求,'games/games.html',上下文)

 {% for game in team_schedule %}<div><h4 class="white">{{ game.boxscore.away_total_rebounds }}</h4>

{% 结束为 %}

解决方案

我不确定这是否是正确答案,但您的 for 循环不应该包含 for 循环的元素吗?我想说的是在模板中不应该是这样的

{% for game in team_schedule %}<div><h4 class="white">{{ game.boxscore.away_total_rebounds }}</h4>

{% 结束为 %}

编辑:添加了阿卜杜勒的回答

I have been trying to work with this Python sports data api, Sportsipy. It’s pretty simple to set up and I can save data to a var and print it to the terminal but when I add it to context go to pass it through my Django template nothing shows up.

I tried calling it on the HTML side several different ways but I still haven't been able to figure it out.

Screenshot of API endpoint doc

Under the Schedule endpoint https://sportsreference.readthedocs.io/en/stable/ncaab.html#module-sportsipy.ncaab.boxscore

    def games(request):
    """ View to return games page """

    team_schedule = Schedule('PURDUE')
    print(team_schedule)

    for game in team_schedule:
        away_total_rebounds = game.boxscore.away_total_rebounds
        print(away_total_rebounds)

    context = {
        'team_schedule': team_schedule,
        'away_total_rebounds': away_total_rebounds,
    }

    return render(request, 'games/games.html', context)

    {% for game in team_schedule %}
         <div>
              <h4 class="white">{{ game.boxscore.away_total_rebounds }}</h4>
         </div>
    {% endfor %} 

解决方案

I'm not sure if it is the correct answer but shouldn't your for loop have elements of the for loop? What I'm trying to say is in the template shouldn't it be like

{% for game in team_schedule %}
         <div>
              <h4 class="white">{{ game.boxscore.away_total_rebounds }}</h4>
         </div>
    {% endfor %} 

EDIT: Abdul's answer added

这篇关于如何将变量从 Python API 传递到 Django 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
Python最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆