0
0
Djangoframework~30 mins

Function-based vs class-based decision in Django - Hands-On Comparison

Choose your learning style9 modes available
Function-based vs Class-based Views Decision in Django
📖 Scenario: You are building a simple Django web app to show a list of books. You want to learn how to create views using both function-based and class-based approaches. This will help you decide which style to use in different situations.
🎯 Goal: Create a Django view that shows a list of books using a function-based view first, then add a class-based view version. Finally, configure the URL patterns to use the class-based view.
📋 What You'll Learn
Create a list of books as a Python list of dictionaries
Write a function-based view called book_list_function that returns an HTTP response with the book titles
Write a class-based view called BookListClass inheriting from django.views.View that returns the same response
Configure the URL pattern to use the class-based view BookListClass.as_view()
💡 Why This Matters
🌍 Real World
Web developers often choose between function-based and class-based views in Django to organize their code and handle HTTP requests efficiently.
💼 Career
Understanding both view types is essential for Django developers to maintain and extend web applications professionally.
Progress0 / 4 steps
1
Create the initial data list of books
Create a Python list called books with these exact dictionaries: {'title': 'Django for Beginners'}, {'title': 'Python Crash Course'}, and {'title': 'Two Scoops of Django'}.
Django
Need a hint?

Use square brackets to create a list. Each book is a dictionary with a 'title' key.

2
Write a function-based view to display book titles
Write a function called book_list_function that takes a request parameter and returns an HttpResponse with the book titles joined by commas. Use from django.http import HttpResponse.
Django
Need a hint?

Use a generator expression inside join() to get all titles from the books list.

3
Write a class-based view to display book titles
Write a class called BookListClass that inherits from django.views.View. Add a get method that takes self and request and returns an HttpResponse with the book titles joined by commas.
Django
Need a hint?

Remember to import View from django.views. The get method handles GET requests.

4
Configure URL pattern to use the class-based view
In the urlpatterns list, add a path with the URL string '' (empty string) that uses BookListClass.as_view() as the view. Import path from django.urls.
Django
Need a hint?

Use path with an empty string for the root URL and call as_view() on the class-based view.