3

I know this might be a very stupid question, but i'm new to django and try to solve this problem for several houres now. I want to pass a variable from a html form to the backend an then use the variable there to make an api request. Then i want to pass the result of the api-request back to the index.html page.

For example:

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)

And then show the temperature in the index.html

David
  • 41
  • 1
  • 9
  • your inputs must have a `name` attribute. After that you can look at this question: https://stackoverflow.com/questions/4706255/how-to-get-value-from-form-field-in-django-framework – Cfreak May 16 '18 at 21:18

1 Answers1

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 }}

Lemayzeur
  • 8,297
  • 3
  • 23
  • 50