Reputation: 43
I'm sorry for the super basic question but I am having the hardest time placing Python variables in my HTML file using Django.
#views.py ??
def my_fucntion(temp):
F = temp*(9.0/5)+32
print F
weather = my_function(20)
How do I add this to my HTML file via Django?
<!-- results.html -->
<p>The temp is {{ weather }} Fahrenheit today.</p>
I am following the Django app tutorial but I cannot find where they explain this in detail. Do I need to put all my functions in views.py?
I've also tried rendering the result with no luck:
#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})
I get an error for saying 'my_function' is not defined.
Again, I am very new at this so a simple step-by-step or how-to would be mega helpful. I've been searching the net for a few days and I'm pulling my hair out. I read the Django docs but get lost pretty quickly.
This seems like a very powerful tool and I just want to know how to get some of my Python scripts to display in HTML.
Thanks!!
Thanks for the info but this still isn't working for me. The tag is coming up blank when I pull the HTML up. Here is my code:
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>
The result when I load up the page is "The temp is Fahrenheit today." Thanks again!!
Upvotes: 0
Views: 622
Reputation: 18242
weather = my_function(20)
should be in your weather function and shouldn't be named weather if that's what you are using as a function name, also my_function should return
instead of 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})
Upvotes: 2