[Django]-How to pass html form variable to python function with django

6👍

Use name attribute to send value to views : name='city' via form

<form action="#" method="post">
   {% csrf_token %}
   <input type="text" class="form-control" id="city" placeholder="" value=""
          name='city'>
   <input type="submit" value="Submit">
</form>

You will need a view to send it back to template

  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)

In template, it’s accessible via {{ temperature }}

Leave a comment