【问题标题】:Manipulate python django dictionary content操作 python django 字典内容
【发布时间】:2020-01-02 23:32:50
【问题描述】:

我正在使用 Django 开发一个简单的天气应用程序。我能够显示城市名称、温度、风速、状况描述以及添加/删除城市。添加城市后,Web 应用程序会显示带有该城市名称和上述所有天气信息的卡片。

作为一名赛艇运动员,我想在城市卡片中添加“safeToRow”部分。该部分将从 python 字典中获取城市的温度和风,并将其分配给两个变量。然后通过一些简单的 if 和 else if 条件运行这些变量,以确定行是否安全,最后返回 safeToRow 的最终值。

Views.py

def index(request):
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=APIKEY'


    if request.method == 'POST':
        form = CityForm(request.POST)
        form.save()

    form = CityForm()

    cities = City.objects.all()

    weather_data = []

    safeToRow = ""


    for city in cities:

        r = requests.get(url.format(city)).json()

        city_weather = {
            'city' : city.name,
            'temperature' : r['main']['temp'],
            'wind' : r['wind']['speed'],
            'description' : r['weather'][0]['description'],
            'icon' : r['weather'][0]['icon'],
        }

        weather_data.append(city_weather)


        temp = r['main']['temp']
        wind = r['wind']['speed']


        def row(temp, wind, safeToRow):
            if temp < 32:
                return safeToRow == "No"
            elif temp > 40 and wind < 15:
                return safeToRow == "No"
            elif temp < 40 and wind > 15:
                return safeToRow == "Yes"



    context = {'weather_data' : weather_data, 'form' : form, "safeToRow" : safeToRow}
    return render(request, 'weather/weather.html', context)

HTML 部分

<div class="media-content">
                                <div class="content">
                                    <p>
                                        <span class="title">{{ city_weather.city }}</span>
                                        <br> 
                                        <span class="subtitle">{{ city_weather.temperature }}</span>
                                        <br> 
                                        <span class="subtitle">{{ city_weather.row }}</span>
                                        <br> 
                                        <span class="subtitle">{{ city_weather.wind }}</span>
                                        <br> {{ city_weather.description }}
                                    </p>
                                </div>
                            </div>

它在网络应用程序上制作卡片上的部分,但该部分是空白的

【问题讨论】:

  • 你有一个row() 函数但从未使用过。
  • 在您的context 中,您将天气存储在.weather_data 下,但在模板中访问{{ city_weather.whatever }}。模板中的weather_data 有循环吗?

标签: python html json django


【解决方案1】:

您正在尝试调用 city_weather.row,但您已将 row 定义为函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 2015-02-27
    相关资源
    最近更新 更多