我知道这可能是一个非常愚蠢的问题,但我是django的新手,现在尝试解决这个问题。 我想将一个变量从html表单传递给后端,然后使用那里的变量来发出api请求。 然后我想将api-request的结果传递回index.html页面。
例如:
的index.html
<form action="#" method="post">
{% csrf_token %}
<input type="text" class="form-control" id="city" placeholder="" value="">
<input type="submit" value="Submit">
</form>
forms.py
import requests
api_address='http://api.openweathermap.org/data/2.5/weather?
appid=KEY&q='
city = FORM-VARIABLE
url = api_address + city
json_data = requests.get(url).json()
kelvin = json_data['main']['temp']
temperature = round(kelvin - 273.15,0)
然后在index.html中显示温度
答案 0 :(得分:2)
使用name
属性通过表单
name='city'
<form action="#" method="post">
{% csrf_token %}
<input type="text" class="form-control" id="city" placeholder="" value=""
name='city'>
<input type="submit" value="Submit">
</form>
您需要一个视图才能将其发送回模板
def myView(request):
context = {}
if request.method == 'POST':
city = request.POST.get('city')
api_address='http://api.openweathermap.org/data/2.5/weather? appid=KEY&q='
url = api_address + city
json_data = requests.get(url).json()
kelvin = json_data['main']['temp']
context['temperature'] = round(kelvin - 273.15,0)
render(request,'template_name.html',context)
在模板中,可以通过{{ temperature }}