无法将变量从视图发送到 html python



am 无法将我的视图中的temp_k变量发送到index.html。我已经从天气API发出请求并试图将其传递给我的html。 请建议我们应该如何将变量从视图发送到模板。

views.py

from django.template.loader import render_to_string
import requests
from django.shortcuts import render
from django.http import HttpResponse
def hello(request):
my_dict = {'insert_me': "From andu.py"}
return render(request, 'mywebapp/index.html', context=my_dict)
def temperature(request):
#zip=requests.form['zip']ss
r=requests.get('http://samples.openweathermap.org/data/2.5/weather?zip=94040,us&appid=b6907d289e10d714a6e88b30761fae22')
json_object=r.json()
my_dict1={'temp_k' :json_object['main']['temp']}
return render(request,'mywebapp/index.html', context=my_dict1)

index.html

<!DOCTYPE html>
{% load staticfiles%}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hey</title>
<link rel="stylesheet" href={% static "cs/style.css" %}/>
</head>
<body>
<h1>This is the Header</h1>
<img src="{% static "images/youownme.jpeg" %}" atl="Uh Oh">
<h2> Temperature:{{temp_k}}</h2>
</body>
</html>

我已经尝试过您的代码并且工作正常,因此您可能需要检查是否正在渲染正确的HTML文件 也许,我已经更改了您的代码以确保它正常工作并且它是

my_dict1={'temp_k' :json_object['wind']['speed']}

对不起,我还不能写评论!

像这样使用render

return render(request,'mywebapp/index.html',{'context':my_dict})

最新更新