在Django HTML中显示Python结果

0 投票
1 回答
609 浏览
提问于 2025-04-18 06:01

抱歉问了个超级基础的问题,但我在用Django把Python变量放到我的HTML文件里时遇到了很大的困难。

#views.py ??  

def my_fucntion(temp):
    F = temp*(9.0/5)+32
    print F
                
weather = my_function(20)

我该如何通过Django把这个添加到我的HTML文件里呢?

<!-- results.html -->
<p>The temp is {{ weather }} Fahrenheit today.</p>

我在跟着Django应用的教程,但找不到详细解释的地方。我需要把所有的函数放在views.py里吗?

我也试过渲染结果,但没有成功:

#views.py
def my_function(temp):
            F = temp*(9.0/5)+32
            print F
        
weather = my_function(20)

def weather(request):
    return render(request, "results.html", {"weather": weather})

我收到一个错误,提示'my_function'没有定义。

我再次强调,我对此非常陌生,所以如果能给我一个简单的逐步指导或者操作方法,那将非常有帮助。我在网上搜索了几天,快要抓狂了。我看过Django的文档,但很快就迷路了。

这看起来是个非常强大的工具,我只想知道如何让我的一些Python脚本在HTML中显示出来。

谢谢!!

编辑:

谢谢你的信息,但这对我来说还是不管用。当我打开HTML时,标签是空白的。这是我的代码:

convert_temp.py

def my_function(temp):
    F = temp*(9.0/5)+32
    return F

views.py

...
import convert_temp
...
def weather(request):
    temp = convert_temp.my_function(20)
    return render(request, "polls/results.html", {"weather": temp})

results.html

...
<p>The temp is {{ weather }} Fahrenheit today.</p>

当我加载页面时,结果是“今天的温度是华氏度。”再次感谢!!

相关问题:

1 个回答

2

你在天气函数里面应该有这一行 weather = my_function(20),而且如果你把这个函数叫做天气,那就不要再用天气这个名字了。另外,my_function 应该用 return 来返回结果,而不是用 print 来打印出来:

def my_function(temp):
    F = temp*(9.0/5)+32
    return F

def weather(request):
    temp = my_function(20)
    return render(request, "detail.html", {"weather": temp})

撰写回答