In Django, Views and Templates work together to display data to users.
- View → Handles logic and processes requests
- Template → Displays data using HTML
Together, they connect the backend with the frontend.
What is a View?
A View is a Python function or class that receives a request and returns a response.
It contains business logic.
Example of a simple function-based view:
from django.http import HttpResponsedef home(request):
return HttpResponse("Welcome to My Website")
This view returns simple text in the browser.
Rendering a Template from a View
Instead of returning plain text, we usually render an HTML template.
Example:
from django.shortcuts import renderdef home(request):
return render(request, "home.html")
Here, Django looks for a template file named home.html.
What is a Template?
A Template is an HTML file that displays dynamic data.
Templates are usually stored inside a folder named templates.
Example structure:
blog/
│
├── templates/
│ └── home.html
Basic Template Example
home.html
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome to My Website</h1>
</body>
</html>
Passing Data from View to Template
Views can send data to templates using a context dictionary.
Example:
def home(request):
context = {
"name": "Ali",
"age": 25
}
return render(request, "home.html", context)
Now access it in template:
<h1>Welcome {{ name }}</h1>
<p>Age: {{ age }}</p>
Django uses double curly braces {{ }} to display variables.
Template Tags
Django templates support logic using template tags.
Example: Loop
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
Example: Condition
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}</p>
{% else %}
<p>Please login</p>
{% endif %}
Template tags use {% %}.
Connecting View to URL
In urls.py:
from django.urls import path
from . import viewsurlpatterns = [
path('', views.home, name='home'),
]
Now when a user visits the URL, the view runs and renders the template.
Flow of Views and Templates
- User visits URL
- urls.py maps URL to view
- View processes request
- View sends data to template
- Template renders HTML
- Browser displays result
Why Views and Templates Are Important
They help you:
Separate logic from design
Build dynamic websites
Display database data
Create user-friendly interfaces
Maintain clean project structure
Key Takeaway
Views handle logic and process requests, while Templates handle presentation.
Together, they allow Django to generate dynamic web pages and deliver content to users efficiently.