skip to Main Content

I’m working on a Django project, and I’m having trouble getting a variable to render in my HTML template. I have a view that passes a dictionary containing some data to my template, and I want to display a specific value in the HTML.

Here’s a simplified version of my view:

def my_view(request):
    data = {'user_name': 'John Doe', 'age': 25}
    return render(request, 'my_template.html', {'data': data})






n my_template.html, I'm trying to display the user's name like this:

html

<!DOCTYPE html>
<html>
<head>
    <title>My Template</title>
</head>
<body>
    <h1>Welcome, {{ data.user_name }}!</h1>
</body>
</html>
However, when I load the page, the user's name doesn't render. It just shows "Welcome, !" without the actual name. What am I doing wrong? Any help would be appreciated!

yaml


---

In this example, the user is facing an issue with rendering a Django template variable (`data.user_name`) in their HTML. They provide relevant code snippets from both the view and the template, explain the problem they are encountering (the variable not rendering), and express a need for assistance. This type of question allows the Stack Overflow community to offer insights and suggestions for resolving the problem.

2

Answers



  1. Welcome, {{ user_name }}!

    **use this only**

    Login or Signup to reply.
  2. The problem is you’re using javascript syntax for a python dictionary. In other words the data.user_name inside angular brackets is in python and in python you can’t get value of a specific key by dot notation (buy you do in javascript) so data["user_name"] should work here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search