Challenge 2: Convert It to a Class-Based View — Possible Solution ==================================================================== # catalog/views.py from django.http import HttpResponse from django.views import View class SubscribeView(View): def get(self, request): form_html = """
""" return HttpResponse(form_html) def post(self, request): email = request.POST.get("email", "") if not email: return HttpResponse("Please provide an email address.", status=400) return HttpResponse(f"Thanks — {email} is now subscribed!") # catalog/urls.py from django.urls import path from . import views urlpatterns = [ path("subscribe/", views.SubscribeView.as_view(), name="subscribe"), ] WHY THIS WORKS -------------- - The single subscribe(request) function split cleanly into two methods, get() and post(), because View's dispatch mechanism reads request.method internally and calls whichever method matches — there's no need to write the `if request.method == "POST"` check by hand anymore; the base class does that branching for you. - Both methods take `self` in addition to `request` — a detail easy to forget coming from FBVs, since these are genuinely instance methods on the view class, not standalone functions. - The urls.py change is the one piece that's easy to miss: `path()` expects a callable, and a class itself isn't directly callable in the way View expects — `.as_view()` returns the actual callable function that path() needs, which is why forgetting `.as_view()` (passing `views.SubscribeView` instead of `views.SubscribeView.as_view()`) is a very common first mistake when adopting CBVs.