django pass data from view to template

django pass data from view to template

In the last article we have seen how to configure the template settings in django. In this article we will talk about passing dynamic data to templates for rendering it. As we know django is a MVC framework. So, we separate business logic from presentational logic. We write business logic in views and we pass data to templates to present the data. The data that we pass from views to template is generally called as "context" data. Let's get started with an example.

Django views, context data and template

Let's write a simple view that takes user information such as first name, last name and address and renders it in the template.

views.py

from django.shortcuts import render

def user_data(request):
    context = {
        "first_name": "Anjaneyulu",
        "last_name": "Batta",
        "address": "Hyderabad, India"
    }
    template_name="user_template.html"
    return render(request, template_name, context)

user_template.html

<html>
<head>
    <title>User Information</title>
</head>
<body>
<p>First Name: {{first_name }}</p>
<p>Last Name: {{last_name }}</p>
<p>Address: {{address}}</p>
</body>
</html>

"render" is the most used function in django. It combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text. It takes three arguments "request", "template_name" and "context" dictionary.  In template we can access the context dict keys as names**or variables** and display them like "{{ <variable/name>}}". That's it folks just try out the above code and let me know if any comments.