如何在Django模板中显示函数的输出数据?

问题描述 投票:0回答:1

index 函数从 'n url 检索字符串并将所需的输出打印到终端。如何设置我的视图,以便它在我的索引 html 页面上显示数据?

这是一个天气应用程序,需要从 URL 检索数据并将其显示在用户登录的页面上。我尝试过使用上下文,但我不确定如何将它与从 URL 返回的数据一起使用for 循环。

from django.shortcuts import render
import requests
import json


def index(request):
    url = "http://weather.news24.com/ajaxpro/Weather.Code.Ajax,Weather.ashx"

    headers = {'Content-Type': 'text/plain; charset=UTF-8',
           'Host': 'weather.news24.com',
           'Origin': 'http://weather.news24.com',
           'Referer': 'http://weather.news24.com/sa/capetown',
           'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) '
                         'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
           'X-AjaxPro-Method': 'GetForecast7Day'}

    payload = {"cityId": "77107"}

    r = requests.post(url, headers=headers, data=json.dumps(payload))
    weather_data = r.json()

    for forecast in weather_data['value']['Forecasts']:
        print(forecast['ShortWeekDay'] + ':', 'High: ' + forecast['HighTemp'] + 'C',
          'Low: ' + forecast['LowTemp'] + 'C',
          'Wind Speed: ' + forecast['WindSpeed'] + 'Km/h', 'Rainfall: ' + str(forecast['Rainfall']))

    return render(request, 'weather/index.html', )

预期结果将显示来自数据库或函数输出的数据。目前它只打印 URL 中的数据。我不知道从哪里开始。有什么想法吗?

python django-models django-templates django-views python-requests
1个回答
1
投票

您可以传递带有预测对象的整个列表,并在您的

weather/index.html
中迭代它。

def index(request):
    ....
    context = {
        'forecasts': weather_data['value']['Forecasts']
    }
    return render(request, 'weather/index.html', context)

由于

forecast
中的单个
weather_data['value']['Forecasts']
也是字典,因此您需要创建一个 模板过滤器 允许您通过 django 模板通过字典内的键访问字典值。我不知道为什么他们到目前为止还没有实施它,因为这是一个常见问题,但这就是您需要的:

@register.filter
def get_value(my_dict, key):
    return my_dict[key]

然后在

weather/index.html
里面你可以像这样访问它(我不知道它的结构,所以我会写一个伪):

{% for forecast in forecasts %}
    <h1>ShortWeekDay: {{forecast|get_value:"ShortWeekDay"}}</h1>
    <h2>High: {{forecast|get_value:"HighTemp"}}C</h2>
    <h2>Low: {{forecast|get_value:"LowTemp"}}C</h2>
    <h2>Wind Speed: {{forecast|get_value:"WindSpeed"}}Km/h</h2>
    <h2>Rainfall: {{forecast|get_value:"Rainfall"}}</h2>
{% endfor %}
© www.soinside.com 2019 - 2024. All rights reserved.