Passing values from python to html with django in views.py does not work

Viewed 46

Hello I am following a django tutorial and the tutorial (FreeCodeCamp btw, they deserve to be noticed more) showed how to make a simple word counter in django. Now the thing is: While rendering the html file he passes some data to it like this:

def counter(request):
    words = request.GET['text']
    numberOfWords = len(words.split())
    return render(request, 'counter.html', {'amount_of_words': int(numberOfWords)})

(I noticed that after publishing it seems like there is not the right spacing for functions, there actually is) Screenshot of the source code

For the youtuber it works really fine, but for me it seems there is no way to display the data. in the html file i put this:

the number of words is {{amount_of_words}}

Which is exactly the same thing the tutorial guy did. Even if I add proper html boilerplate it doesn't seem to work

from unicodedata import name
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index , name='index'),
    path('counter', views.counter, name="counter")
]

this is the urls.py file inside the app folder.

When loading counter it just shows "the message the number of words is " without display the value i pass from views.py

Even with a super simple example like this:

views.py:

def index(request):
    person_name = {
        'name': 'John',
    }
    return render(request, 'index.html', person_name)

index.html code:

<h1>ciao {{name}}</h1>

url when i load the page: http://127.0.0.1:8000/

I don't get why it would not work for me.

2 Answers
def counter(request):
    words = request.GET['text']
    numberOfWords = len(words.split())
    amount_of_words = int(numberOfWords)
    context = {
        'amount_of_words': amount_of_words,
    }
    return render(request, 'counter.html', context)
Related