【问题标题】:How to display output data from function in Django template?如何在 Django 模板中显示函数的输出数据?
【发布时间】:2019-01-27 22:48:29
【问题描述】:

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

这适用于需要从 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】:

    您可以将整个列表与预测对象一起传递并在您的weather/index.html 中进行迭代。

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

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

    @register.filter
    def get_value(dict, key):
        return 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 %}
    

    【讨论】:

      猜你喜欢
      • 2016-05-06
      • 1970-01-01
      • 2012-03-18
      • 2021-11-02
      • 1970-01-01
      • 2014-11-12
      • 2016-12-24
      • 1970-01-01
      • 2011-07-10
      相关资源
      最近更新 更多