How to send a variable from views.py to a Django template and access it in the template

  • In Django, template variables are used to pass data from views (backend) to templates (frontend) and render dynamic content. They allow you to display dynamic data and control the logic of your templates.
  • Here's an example code that demonstrates how to send a variable from views.py to a Django template and access it in the template:
  • In views.py

    from django.shortcuts import render

    def handleHome(request):
        context = {
            "website": "codewithgagan.com",
            "description": "Read text based technical tutorials"
        }
        return render(request, "index.html", context)

  • In the above code, we define a view function handleHome that sets a variable context to the python dict, and then renders the template index.html with the variable passed in as a context dictionary.
  • In index.html

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>

    <body>
        <h1>hello world</h1>
        <h2>Website's name: {{website}}</h2>
        <h2>Website's description: {{description}}</h2>
    </body>

    </html>

  • Now time to see output:

No comments:

Post a Comment