我正在为一个天气应用程序做一个练习项目,当点击当前天气中的按钮时,会显示接下来 7 天的天气预报bootstrap5 card
。使用 bootstrap collapse 一次显示每个城市的每日天气预报。我应该改变哪一部分,我还没有学过javascript。
未来7天的天气预报列表(city_weather_forecast
)放在当前城市天气状态(city_weather_data
)中,这样就可以使用当前城市的经纬度来获取每日预报信息。
views.py/ 为上下文提供模板的部分。
def index(request):
current_weather_url = "http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid={}"
forcast_weather_url = "https://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&units=metric&exclude=current,minutely,hourly&appid={}"
api_key = "3305a1cea0761d956da3c5f87c21b563"
message = ''
err_msg = ''
message_class = ''
form = CityForm()
if request.method == 'POST':
form = CityForm(request.POST)
if form.is_valid():
new_city = form.cleaned_data['name']
count_city_in_data = City.objects.filter(name=new_city).count()
if count_city_in_data == 0:
r = requests.get(current_weather_url.format(new_city, api_key)).json()
if r["cod"] == 200:
form.save()
return redirect('weather:home')
else:
err_msg = "The city name is not a proper name."
else:
err_msg = "The city is already in your list."
if err_msg:
message = err_msg
message_class = 'alert-danger'
else:
message = 'The city is added successfully.'
message_class = 'alert-success'
cities = City.objects.all().order_by('-created_date')
weather_data = []
for city in cities:
# Current weather status
current_r = requests.get(current_weather_url.format(city, api_key)).json()
# print("current_r : ", current_r["dt"])
# print(forcast_r["daily"][1]["dt"])
# print(len(forecast_r["daily"])) including today, total 8 days of weather forecasts.
# Forecast next 7 days.
city_weather_forecast = []
forecast_r = requests.get(forcast_weather_url.format(current_r["coord"]["lat"], current_r["coord"]["lon"], api_key)).json()
daily_weather_7days = forecast_r["daily"][1:] # excluding today.
for daily_weather in daily_weather_7days:
# Convert Timestapt to human readable time.
date = datetime.utcfromtimestamp(daily_weather["dt"]).strftime("%m/%d")
day = datetime.utcfromtimestamp(daily_weather["dt"]).strftime("%A")
city_weather_forcast_data = {
'date': date,
'day': day,
'icon': daily_weather["weather"][0]["icon"],
'min': daily_weather["temp"]["min"],
'max': daily_weather["temp"]["max"],
}
city_weather_forecast.append(city_weather_forcast_data)
# Include daily forecasts and current weather status and give this info to templates.
city_weather_data = {
'city': city.name,
'country': current_r["sys"]["country"],
'description': current_r["weather"][0]["description"],
'icon': current_r["weather"][0]["icon"],
'temp': current_r["main"]["temp"],
'lat': current_r["coord"]["lat"],
'lon': current_r["coord"]["lon"],
'forecasts': city_weather_forecast,
}
weather_data.append(city_weather_data)
context = {
'weather_data': weather_data,
'form': form,
'message': message,
'message_class': message_class,
}
return render(request, 'weather/index.html', context)
模板
{% if weather_data %}
<div class="delete-all">
<div class="delete-all-button">
<a href="{% url 'weather:delete_all_city' %}"><button class="btn btn-danger"><i class="delete-element glyphicon glyphicon-trash"></i> Delete All</button></a>
</div>
</div>
{% for city in weather_data %}
<div class="container-weather-card">
<div class="card card-bg">
<div class="card-body">
<img class="card-img" src="http://openweathermap.org/img/wn/{{ city.icon }}.png" alt="image">
<h2 class="card-title">{{city.city}}, <span class="card-subtitle">{{ city.country }}</span></h2>
<h4 class="card-temp">{{ city.temp }} °C</h4>
<p class="card-text">{{ city.description }}</p>
<button class="btn btn-position btn-outline-danger"><i class="delete-element glyphicon glyphicon-trash"></i><a class="delete-element" href="{% url 'weather:delete_city' city.city %}"> Delete</a></button>
<button class="btn btn-outline-primary btn-forecast" data-bs-toggle="collapse" href="#weather-7days" role="button" aria-expanded="false" aria-controls="weather-7days"><span>Next 7days</span></button>
</div>
</div>
</div>
{% for city_forecast in city.forecasts %}
<div class="collapse" id="weather-7days">
<div class="container-weather-forecast card">
<div class="card-body">
<div class="row">
<div class="col-md card-section">
<p>{{ city_forecast.date }}</p>
<p>{{ city_forecast.day}}</p>
</div>
<div class="col-md">
<img class="forcast-img" src="http://openweathermap.org/img/wn/{{ city_forecast.icon }}.png" alt="image">
</div>
<div class="col-md card-section">
<p>Low {{ city_forecast.min }} °C</p>
<p>High {{ city_forecast.max }} °C</p>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% endfor %}
{% endif %}