Day 2 of 5
⏱ ~60 minutes
Django in 5 Days — Day 2

Views and URLs

Map URLs to Python functions and classes. Pass data from models to templates. Understand function-based views and class-based views.

URL Patterns

mysite/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
]
blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('posts//', views.post_detail, name='post_detail'),
]
blog/views.py — Function-Based Views
from django.shortcuts import render, get_object_or_404
from .models import Post

def post_list(request):
    posts = Post.objects.filter(published=True)
    return render(request, 'blog/post_list.html', {'posts': posts})

def post_detail(request, slug):
    post = get_object_or_404(Post, slug=slug, published=True)
    return render(request, 'blog/post_detail.html', {'post': post})
Class-Based Views (CBV) alternative
from django.views.generic import ListView, DetailView
from .models import Post

class PostListView(ListView):
    model = Post
    queryset = Post.objects.filter(published=True)
    template_name = 'blog/post_list.html'
    context_object_name = 'posts'
    paginate_by = 10

class PostDetailView(DetailView):
    model = Post
    template_name = 'blog/post_detail.html'
ℹ️
Use function-based views when you need custom logic. Use class-based views for standard CRUD operations — they reduce boilerplate significantly. ListView, DetailView, CreateView, UpdateView, DeleteView cover 80% of web app views.
📝 Day 2 Exercise
Add Views to Your Blog
  1. C
  2. r
  3. e
  4. a
  5. t
  6. e
  7. p
  8. o
  9. s
  10. t
  11. _
  12. l
  13. i
  14. s
  15. t
  16. a
  17. n
  18. d
  19. p
  20. o
  21. s
  22. t
  23. _
  24. d
  25. e
  26. t
  27. a
  28. i
  29. l
  30. v
  31. i
  32. e
  33. w
  34. s
  35. .
  36. W
  37. i
  38. r
  39. e
  40. t
  41. h
  42. e
  43. m
  44. t
  45. o
  46. U
  47. R
  48. L
  49. p
  50. a
  51. t
  52. t
  53. e
  54. r
  55. n
  56. s
  57. .
  58. P
  59. a
  60. s
  61. s
  62. t
  63. h
  64. e
  65. Q
  66. u
  67. e
  68. r
  69. y
  70. S
  71. e
  72. t
  73. a
  74. s
  75. c
  76. o
  77. n
  78. t
  79. e
  80. x
  81. t
  82. .
  83. V
  84. e
  85. r
  86. i
  87. f
  88. y
  89. b
  90. o
  91. t
  92. h
  93. p
  94. a
  95. g
  96. e
  97. s
  98. w
  99. o
  100. r
  101. k
  102. i
  103. n
  104. t
  105. h
  106. e
  107. b
  108. r
  109. o
  110. w
  111. s
  112. e
  113. r
  114. .

Day 2 Summary

  • URL patterns are matched top to bottom. Put more specific patterns first.
  • render(request, template, context) — the three things every view does.
  • get_object_or_404 returns the object or a 404 response. Use it instead of .get() in views.
  • CBVs reduce boilerplate for standard CRUD. FBVs give you full control for custom logic.
Finished this lesson?