2014-05-09 17 views
0

對於超級基本問題,我很抱歉,但我最困難的時候是使用Django將Python變量放入我的HTML文件中。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}) 

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

當我加載了頁面的結果results.html是「今天溫度是華氏溫度。「再次感謝!!

+0

Django是的Python。如果您已經有了Python函數的加載,那麼您大概已經瞭解了Python範圍規則,導入等。只需遵循相同的規則,並在需要的地方導入函數,然後在您的視圖中調用它們。 –

回答

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}) 
+0

我得到了它的感謝。我的urlpatterns沒有指向正確的位置。 – Mike