【问题标题】:How to pass html form variable to python function with django如何使用 django 将 html 表单变量传递给 python 函数
【发布时间】:2018-10-27 01:07:08
【问题描述】:

我知道这可能是一个非常愚蠢的问题,但我是 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中显示温度

【问题讨论】:

标签: python html django


【解决方案1】:

使用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 }}访问

【讨论】:

    猜你喜欢
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    相关资源
    最近更新 更多