URL Routing & View Functions

🐍 DjangoLesson 3Beginner

Views are Python functions or classes that receive a web request and return a web response. URL Routing maps incoming URLs to specific views based on path matching.

1 Basic View Functions
Python — views.py
from django.http import HttpResponse, JsonResponse

def home_view(request):
    return HttpResponse("<h1>Welcome to Django!</h1>")

def api_status(request):
    return JsonResponse({"status": "running", "version": "5.0"})
2 URL Configuration
Python — urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("", views.home_view, name="home"),
    path("status/", views.api_status, name="status"),
    # Path parameters / dynamic URLs
    path("posts/<int:post_id>/", views.post_detail, name="post-detail"),
    path("category/<str:slug>/", views.category_list, name="category"),
]
3 Code Challenge
Challenge: Write a view function user_profile(request, username) that returns a JSON response containing the username passed through the path. Configure its route in urls.py mapping to /user/<str:username>/.