You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中无法将views的temp_k变量传递至模板,求解决方案

解决Django视图到模板的变量传递问题

嘿,我来帮你搞定这个变量传递的问题!咱们一步步拆解来看:

核心问题分析

你现在的代码里有两个视图函数:hello和temperature。temperature视图确实把temp_k变量传到了模板,但如果你访问的是hello视图对应的URL,模板自然拿不到这个变量——因为hello只传了insert_me这一个变量。

解决方案一:确保访问正确的视图URL

首先检查你的urls.py配置,要把temperature视图映射到一个可访问的URL,比如:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.hello, name='hello'),
    # 新增这个URL映射,访问/temp/就会触发temperature视图
    path('temp/', views.temperature, name='temperature'),
]

配置好后,访问http://你的域名/temp/,模板里的{{temp_k}}就能正常显示从OpenWeatherMap获取的温度值了。

解决方案二:在同一个视图里传递所有需要的变量

如果你希望访问根URL时也能看到温度,可以把两个视图的逻辑合并,在hello视图里同时获取天气数据并传递变量:

from django.shortcuts import render
import requests

def hello(request):
    # 获取天气数据
    r = requests.get('http://samples.openweathermap.org/data/2.5/weather?zip=94040,us&appid=b6907d289e10d714a6e88b30761fae22')
    json_object = r.json()
    
    # 把所有需要的变量放到同一个字典里
    my_dict = {
        'insert_me': "From views.py",  # 这里你之前写错成andu.py了,修正一下
        'temp_k': json_object['main']['temp']
    }
    return render(request, 'mywebapp/index.html', context=my_dict)

这样访问根URL时,模板既能显示insert_me的内容,也能显示温度值。

小细节修正

另外,你的模板里<img>标签的atl是笔误,应该改成alt,这样图片加载失败时才能显示正确的替代文本。

内容的提问来源于stack exchange,提问作者Rajorshi Bhattacharjee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:24:24