Your First View & Template
Views are the heart of Django — they receive web requests and return web responses. A view can return HTML, JSON, a redirect, or an error. Templates are HTML files with Django template tags that let you inject dynamic data. Let's build your first view and template.
20 min•By Priygop Team•Updated 2026
Views & Templates
- A view is a Python function that takes a request and returns a response
- HttpResponse — Return raw HTML or text directly
- render() — Render an HTML template with context data
- Templates live in a 'templates/' directory inside each app
- Context — A dictionary of data passed to the template
- Template tags: {{ variable }}, {% if %}, {% for %}, {% url %}
- Always use render() over HttpResponse for real pages
First View & Template
First View & Template
# blog/views.py — Your first view
# from django.shortcuts import render
# from django.http import HttpResponse
# Simple view returning text
# def home(request):
# return HttpResponse("<h1>Hello, Django!</h1>")
# Better: View with a template
# def home(request):
# context = {
# 'title': 'My Blog',
# 'posts': ['First Post', 'Second Post', 'Third Post'],
# }
# return render(request, 'blog/home.html', context)
# blog/templates/blog/home.html
# <!DOCTYPE html>
# <html>
# <head><title>{{ title }}</title></head>
# <body>
# <h1>{{ title }}</h1>
# <ul>
# {% for post in posts %}
# <li>{{ post }}</li>
# {% endfor %}
# </ul>
# </body>
# </html>
# blog/urls.py
# from django.urls import path
# from . import views
# urlpatterns = [
# path('', views.home, name='home'),
# ]Try It Yourself
Try It YourselfPython
Python Editor
✓ ValidTab = 2 spaces
Python|26 lines|705 chars|✓ Valid syntax
UTF-8
Tip
Tip
Create a base.html with {% block %} tags and extend it in all other templates. This eliminates HTML duplication across pages.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Putting business logic in templates with complex {% if %} chains. Use model methods or template tags for computed values.
Practice Task
Note
(1) Create base.html with header/footer blocks. (2) Extend it in home.html. (3) Use {% for %} to loop over a list.
Quick Quiz
Key Takeaways
- Views are the heart of Django — they receive web requests and return web responses.
- A view is a Python function that takes a request and returns a response
- HttpResponse — Return raw HTML or text directly
- render() — Render an HTML template with context data