Detailed Explanation of the Usage of django Class View

  • 2021-07-26 08:11:42
  • OfStack

Preface

When we are developing a registration module. The browser will make the registration form pop up through get request, and then the user will submit the information to the server through post request after entering the registration information. At this point we have two view functions on the back end, one for get requests and one for post requests. Both view functions have different names.

But as the development progresses. When you want to find these two views of the registration module, it is too much trouble. If these two view functions can be placed in one, they will be classified into one class as the class of the registration module. In this way, the maintenance in the future will be much more convenient. At this time, the class view of django can realize this function.

Contrast

Before there was no class view, the view looked like this:


def get_register_page(request):
  return render(request," Registration page .html")

def post_register_page(request):
  #  Processing requests and writing information into the database 
  return HttpResponse(" Successful registration ")

With django's class view, the view looks like this:


class register(View):
  def get(self,request):
    return render(request,"register.html")

  def post(self,request):
    title = request.POST.get("name")
    content = request.POST.get("password")
    return HttpResponse(" Successful registration ")

Don't miss the urls settings in the project:


url(r'^register$',views.register.as_view())

Note that as_view () is used to distribute the request method. You can distribute different request methods for the same page to different views for execution.


Related articles: