This tutorial aims to help you understand how to render context data in templates using Django, a high-level Python web framework.
By the end of this tutorial, you will be able to:
Before starting, you should have a basic understanding of Python programming and Django. Familiarity with HTML is also beneficial.
In Django, a view is a Python function that receives a web request and returns a web response. This response can be an HTML content, a redirect, a 404 error, an XML document, an image or anything.
A template is a text file that defines the structure or layout of a file (like an HTML), with placeholders used to represent actual content.
A context is a dictionary mapping template variable names to Python objects.
This example illustrates how to pass a simple context (a string) to a template.
views.py:
from django.shortcuts import render
def home(request):
context = {'message': 'Hello, Django!'}
return render(request, 'home.html', context)
home.html:
<!DOCTYPE html>
<html>
<body>
<h1>{{ message }}</h1>
</body>
</html>
In the view function home
, we create a context dictionary with a single key-value pair. Then we pass this context to the home.html
template. In the HTML file, we use {{ message }}
to display the value of message
from the context.
This example demonstrates how to pass a list to a template.
views.py:
from django.shortcuts import render
def home(request):
context = {'fruits': ['Apple', 'Banana', 'Cherry']}
return render(request, 'home.html', context)
home.html:
<!DOCTYPE html>
<html>
<body>
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>
</body>
</html>
In the view function home
, we create a context dictionary with a key 'fruits' mapped to a list of fruit names. Then we pass this context to the home.html
template. In the HTML file, we use Django's template language to iterate over the fruits
list and display each fruit.
In this tutorial, you have learned the basics of context and template rendering in Django. The key points covered are:
To continue learning about Django, you can explore topics such as Django forms, Django models, and Django template filters.
Exercise 1: Create a view function that passes a dictionary of student names and grades to a template. Display the students' names and grades in a table in the template.
Exercise 2: Create a view function that passes a list of dictionaries to a template. Each dictionary should contain information about a book (title, author, year). Display this information in a list in the template.
Exercise 3: Modify the above exercise to allow the user to filter books by year.
Remember, the best way to learn programming is by doing. Keep practicing!