Lev Slinsen
Lev Slinsen

Reputation: 448

Pass a function result to html in Django

While learning Django, I can't figure out one simple thing. May be very obvious to any Django devs. I've read the docs and it seem to have to work. Here's my code:

#views.py

from django.shortcuts import render

def home(request):
    return render(request, 'radio/index.html', {'title': 'Radio'})

def function_name():
    return 'Hello, World!'
#index.html

<div>
    <h1>{{ function_name }}</h1>
</div>

Yet the result is:

<div>
    <h1></h1>
</div>

I must be missing something fundamental but can't find out what it is.

Upvotes: 1

Views: 1358

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You need to pass a reference to the function in the context of your render(..) call, like:

#views.py

from django.shortcuts import render

def home(request):
    return render(
        request,
        'radio/index.html',
        {'title': 'Radio', 'function_name': function_name}
    )

def function_name():
    return 'Hello, World!'

Since otherwise, it is not in the context of the template, and hence you can not render it accordingly.

Upvotes: 1

Related Questions