【发布时间】:2014-05-09 17:48:22
【问题描述】:
对于这个超级基本的问题,我很抱歉,但我很难使用 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})
结果.html
...
<p>The temp is {{ weather }} Fahrenheit today.</p>
我加载页面时的结果是“今天的温度是华氏度”。再次感谢!!
【问题讨论】:
-
Django 只是 Python。如果您已经拥有大量 Python 函数,那么您可能已经了解 Python 范围规则、导入等。只需遵循相同的规则,并在需要它们的地方导入函数,然后在视图中调用它们。
标签: python html django templates tags