我检查了文档和堆栈,但仍然无法实现。我想要html中的按钮来获取输入数据并将其作为城市注入到views.py中,并在我对城市变量进行硬编码时制作其余的代码。而且不应该在新的网址上创建。感谢帮助! html:
<form method="POST "action="{% url 'weather' %}">
{% csrf_token %}
<input type="text" name="city" id="city"><br>
<button type="submit" class="btn btn-info">Get my weather</button>
</form>
views.py:
def scrape_weather(request):
if request.method == 'POST':
old_weather = Weather.objects.all()
old_weather.delete()
api_adress = "http://api.openweathermap.org/data/2.5/weather?q="
api_key = "&appid=3a99cf24b53d85f4afad6cafe99d3a34"
city = request.POST.get("city")
url = api_adress + city + api_key
json_data = requests.get(url).json()
new_weather = json_data['weather'][0]['main']
degree_kelvin = int(json_data['main']['temp'])
degree = degree_kelvin-273
pressure = json_data['main']['pressure']
new_weather = Weather()
new_weather.degree = degree
new_weather.pressure = pressure
new_weather.weather = new_weather
new_weather.save()
return render(request, "news/home.html")
urls.py:
path('weather/', scrape_weather, name='weather'),