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

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.