簡體   English   中英

操作python django字典內容

[英]Manipulate python django dictionary content

我正在使用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>

它會在網絡應用的卡片上顯示該部分,但該部分為空白

您正在嘗試調用city_weather.row,但已將row定義為一個函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM