0
0
Djangoframework~30 mins

Why class-based views exist in Django - See It in Action

Choose your learning style9 modes available
Understanding Why Class-Based Views Exist in Django
📖 Scenario: You are building a simple web application using Django. You want to understand why Django offers class-based views (CBVs) instead of just function-based views (FBVs).
🎯 Goal: Learn the basic setup of a function-based view, then add a configuration variable, refactor it into a class-based view, and finally complete the class-based view with a method to handle GET requests.
📋 What You'll Learn
Create a simple function-based view that returns a greeting message.
Add a configuration variable to customize the greeting.
Refactor the function-based view into a class-based view.
Complete the class-based view by adding a get method to handle GET requests.
💡 Why This Matters
🌍 Real World
Web developers use Django views to handle user requests and return responses. Understanding why CBVs exist helps write cleaner and more maintainable code.
💼 Career
Many Django jobs require knowledge of both function-based and class-based views to build scalable web applications efficiently.
Progress0 / 4 steps
1
Create a simple function-based view
Create a function-based view called greeting_view that takes a request parameter and returns an HttpResponse with the text 'Hello, world!'.
Django
Need a hint?

Use def to define the function and HttpResponse to return the response.

2
Add a configuration variable for the greeting message
Add a variable called greeting_message and set it to the string 'Hello, Django!'. Then update the greeting_view function to return this variable inside the HttpResponse.
Django
Need a hint?

Define greeting_message before the function and use it inside HttpResponse.

3
Refactor the function-based view into a class-based view
Create a class called GreetingView that inherits from django.views.View. Inside the class, add a class variable called greeting_message set to 'Hello, Django!'.
Django
Need a hint?

Use class to define GreetingView and inherit from View.

4
Complete the class-based view with a GET method
Inside the GreetingView class, add a method called get that takes self and request parameters. This method should return an HttpResponse with the class variable greeting_message.
Django
Need a hint?

Define the get method to handle GET requests and return the greeting message.