Joyal Mathew
Joyal Mathew

Reputation: 624

Unable to use python variables in html | Django

I am using django to create a web app. I have run into a problem when trying to use variables from python in html. The variable does not show up. The app has a lot of messy code so I have recreated the problem including only relevant files.

views.py:

from django.shortcuts import render


# Create your views here.
def home(request):
    return render(request, 'main/index.html')

def hello(request):
  if request.method == 'POST':
    fname = request.POST.get('fname', None)
  else:
    fname = "there"
  return render(request, 'main/hello.html')

index.html:

{% extends "base.html" %} {% block content %}
<form action="hello" method="POST">
  {% csrf_token %}
    <input name="fname" placeholder="First Name">
    <input type="submit" value="Submit">
</form>
{% endblock content %}

hello.html

{% extends "base.html" %} {% block content %}
<p>Hello {{fname}}</p>
{% endblock content %}

base.html:

{% load staticfiles %}
<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link rel="stylesheet" href="{% static "css/style.css" %}">
</head>
<body>
    {% block content %}{% endblock content %}
</body>
</html>

Here is what the "hello" page looks like(only part of the screen):
html output(says hello but not "name")

I want it to be able to output the users input.

Upvotes: 0

Views: 1401

Answers (2)

Robin Zigmond
Robin Zigmond

Reputation: 18249

You can only reference a variable in a template if you include it in the "context" that is passed to the template. This is a dictionary linking variable names to the Python values they represent. The usual way to pass this to the template is as the third argument of the render method. So in your views.py, you should alter the final line to:

return render(request, 'main/hello.html', {"fname": fname})

Upvotes: 3

Rocky Li
Rocky Li

Reputation: 5958

In order for fname to show up you'll need to pass that into the render function. You're not doing that in def hello

You need to correctly return the argument into the render function like this:

def hello(request):

    ...

    context = {'fname': fname}
    return render(request, 'pops/index.html', context)

Upvotes: 2

Related Questions