๐ Django Tutorial – Module 3
Topic: URL Routing & Views
๐ฏ Learning Objectives
- Understand Django URL routing
- Create function-based views
- Map URLs to views
- Test URLs in browser
๐น What is a View?
A view is a Python function that receives a request and returns a response (HTML, text, JSON, etc.).
๐น Step 1: Create a View
# blog/views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello Django!")
๐น Step 2: Create App-Level URLs
# blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
๐น Step 3: Include App URLs in Project
# mysite/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
๐น Step 4: Run Server
python manage.py runserver
๐ Output
Open browser and visit:
http://127.0.0.1:8000/
๐งช Student Practice
- Create another view
about() - Map it to
/about - Display your name and department
❓ Viva / Exam Questions
- What is URL routing in Django?
- What is the role of
urls.py? - Difference between view and template?
๐ Teaching Tips:Ask students to trace URL → View → Response
Modify response text live
Show 404 error when URL is missing
Modify response text live
Show 404 error when URL is missing
No comments:
Post a Comment