Views got classier

Class-based views were introduced in Django 1.4. Here is how the previous view looks when rewritten to be a functionally equivalent class-based view:

from django.views.generic import View 
 
 
class HelloView(View): 
    def get(self, request, name="World"): 
        return HttpResponse("Hello {}!".format(name)) 

Again, the corresponding URLConf would have two lines, as shown in the following commands:

# In urls.py 
    path('hello-cl/<str:name>/', views.HelloView.as_view()), 
    path('hello-cl/', views.HelloView.as_view()),

There are several interesting differences between this View class and our earlier view function. The most obvious one being that we need to define a class. Next, we explicitly define that we will handle only the GET requests. ...

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.