Django Class-Based Views
A class-based view is a view written as a class. Each method of the class answers one request method.
A view as a class
This class answers a GET request with the home page. The method is named get.
from django.http import HttpResponse
from django.views import View
class HomeView(View):
def get(self, request):
return HttpResponse("Home page")Wire it up
as_view turns the class into a view. The address list uses it like a function view.
urlpatterns = [path("", HomeView.as_view())]A view with two methods
This class answers GET with a page and POST with a short reply. Each method matches its request method.
class HelloView(View):
def get(self, request):
return HttpResponse("Hello page")
def post(self, request):
return HttpResponse("Hello back")Ask both pages
The test client asks for the home page and the about page. The prints show both pages.
client = Client()
print(client.get("/").content.decode())
print(client.get("/about/").content.decode())Example
import django
from django.conf import settings
settings.configure(DEBUG=True, SECRET_KEY="key", ROOT_URLCONF=__name__, ALLOWED_HOSTS=["*"])
django.setup()
from django.http import HttpResponse
from django.urls import path
from django.views import View
class HomeView(View):
def get(self, request):
return HttpResponse("Home page")
class AboutView(View):
def get(self, request):
return HttpResponse("About page")
urlpatterns = [path("", HomeView.as_view()), path("about/", AboutView.as_view())]
from django.test import Client
client = Client()
print(client.get("/").content.decode())
print(client.get("/about/").content.decode())
Key points
- View is the base class for class-based views.
- def get(self, request) answers a GET request.
- as_view() turns the class into a view for the address list.
- A class can hold get and post side by side.
In this example, the setup lines configure Django. HomeView and AboutView are classes built on View. Each class has a get method for GET requests. as_view turns each class into a view for the address list. The test client asks for both pages. The prints show the home page and the about page.
Note
A class-based view still returns a response, like a function view.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does the address list use a class-based view?