How to render data in Django

Overview

In Django, render() is one of the most used functions that combines a template with a context dictionary and returns an HttpResponse object with the rendered text.

Syntax


render(request, template, {})

Arguments

It takes the following three arguments.

  1. request: This is everything we receive from the user via the Internet.

  2. template: This is the template file that will be rendered.

  3. context dictionary: This is a dictionary where we store data that can be used by the template.

Creating data

Let’s create a function in views.py that will render a template with some context.


from django.shortcuts import render

def about(request):
    template = "about.html"
    context = {
      fullName: "Shubham Kshariya",
      age: 22,
      destination: "Software Engineer"
    }
    return render(request, template , context)

Explanation

First, we need to import the render library from django.shortcuts.

After that, we create an about function where we define a template file and a context dictionary.

At the end of the function, we will invoke the render() function and pass the required parameters to it.

Rendering data

The render() function will return an HttpResponse including the about.html and context dictionary.

In order to render a dynamic variable in Django, it needs to be wrapped between {{ and }}.

Check out how to create the about.html to render data:


<html>
  <head>
    <title>User Information</title>
  </head>
  <body>
    <p>Name: {{ fullName }}</p>
    <p>Age: {{ age }}</p>
    <p>Designation: {{ designation }}</p>
  </body>
</html>

Explanation

The dynamic portion of the file is wrapped between {{ and }}.

We can also implement dictionary lookup, attribute lookup, and list-index lookups using a dot notation.

Adding comments

A comment can be also be added in the template like this.


{# single line comment #}

{% multiple line comment %}

Comments won’t be rendered in the output.

Free Resources