0

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!!

EDIT:

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!!

1
  • Django is just Python. If you've got a load of Python functions already, you presumably already know about Python scoping rules, imports, etc. Just follow the same rules, and import the functions where you need them then call them in your views. Commented May 9, 2014 at 18:03

1 Answer 1

2

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})
Sign up to request clarification or add additional context in comments.

1 Comment

I got it thanks. My urlpatterns were not pointing to the right spot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.