Displaying Data in Django Templates


Introduction

In Django, displaying data in templates is a core part of building dynamic web applications. Django templates allow you to present data from your views to the user in a structured and visually appealing way. In this guide, we'll explore how to display data in Django templates.


Prerequisites

Before you begin, make sure you have the following prerequisites in place:

  • Django: You should have Django installed. If not, use
    pip install django
    to install it.
  • Django Project: You should have a Django project set up. If not, refer to the guide on creating your first Django project.
  • Django Views: Ensure you have defined views in your Django app. If not, refer to the guide on handling URL requests in Django.

Passing Data to Templates

In Django, you pass data from your views to templates using context. This allows you to make data available for rendering in the template.


Sample Code

In your view function in

views.py
, create a dictionary containing the data you want to display and pass it as context to the template:

from django.shortcuts import render
def my_view(request):
data = {'name': 'John', 'age': 30}
return render(request, 'my_template.html', {'data': data})

Accessing Data in Templates

In your Django template, you can access and display data using template tags and variables.


Sample Code

In your template (e.g.,

my_template.html
), you can access the data using double curly braces:

<h1>Hello, {{ data.name }}!</h1>
<p>You are {{ data.age }} years old.</p>

Conclusion

Displaying data in Django templates is an essential part of creating user-friendly web applications. By passing data from views to templates and using template tags, you can provide a dynamic and informative user experience.