Django learning notes Class-Based-View, django

Source: Internet
Author: User

Django learning notes Class-Based-View, django

Preface

As we all know, it is very easy to learn Django and you can get started without any effort. Configure a url, assign it to a function, and return response. There is almost nothing difficult to understand.

After writing too much, I gradually realized some problems. For example, a view is complex and many other functions are called. What should I do if I want to encapsulate these functions? Of course, you can use the comment # ------ view ------ To isolate the function. This method is too low, and it is just a lie to yourself, not even the encapsulation.

Python is an object-oriented programming language. If you only use functions for development, many object-oriented advantages will be missed (inheritance, encapsulation, and polymorphism ). So Django later added Class-Based-View. We can use classes to write views. The following two advantages are provided:

  1. This improves code reusability by using object-oriented technologies, such as Mixin (Multi-inheritance)
  2. Different functions can be used to process different HTTP methods, instead of using many if statements to improve code readability.

Use class-based views

If we want to write a view for processing the GET method, use the function to write the following.

from django.http import HttpResponse def my_view(request): if request.method == 'GET':  # <view logic>  return HttpResponse('result')

If you use class-based view, the following is the case.

from django.http import HttpResponsefrom django.views import View class MyView(View): def get(self, request):  # <view logic>  return HttpResponse('result')

The Django url assigns a request to the callable function instead of a class. To solve this problem, class-based view providesas_view()A static method (that is, a class method). When this method is called, an instance of the class is created and then called through the instance.dispatch()Method,dispatch()The method calls the corresponding method to process the request according to the method of the request (for exampleget() , post()). At this point, these methods are similar to function-based view. You need to receive the request and get a response. If the method is not defined, an HttpResponseNotAllowed exception is thrown.

In the url, write as follows:

# urls.pyfrom django.conf.urls import urlfrom myapp.views import MyView urlpatterns = [ url(r'^about/$', MyView.as_view()),]

Class attributes can be set in two ways. The first is a common Python method, which can be overwritten by the quilt class.

from django.http import HttpResponsefrom django.views import View class GreetingView(View): greeting = "Good Day"  def get(self, request):  return HttpResponse(self.greeting) # You can override that in a subclass class MorningGreetingView(GreetingView): greeting = "Morning to ya"

In the second method, you can also specify the class attributes in the url:

Set class attributes in url Python

urlpatterns = [ url(r'^about/$', GreetingView.as_view(greeting="G'day")),]

Use Mixin

I think to understand django's class-based-view (hereinafter referred to as cbv), we must first understand what the purpose of django's cbv introduction is. Prior to django1.3, generic view was also called a general view, using function-based-view (fbv), that is, a function-based view. Some people think that fbv is more pythonic than cbv. An important feature of python is object-oriented. While cbv is more representative of python object-oriented. Cbv implements the view method through class. Compared with the function, the class can better utilize the specific polymorphism, so it is easier to abstract the more common functions in the project from the macro level. There is not much explanation about polymorphism. If you are interested, Google. In short, it can be understood that one thing has multiple forms (features ). The implementation principle of cbv is easy to understand by looking at django's source code. Generally, after the url is routed to this cbv, the cbv internal dispatch method is used to distribute get requests to cbv. get method to distribute post requests to cbv. post method. Other methods are similar. How can we use polymorphism? Cbv introduces the concept of mixin. Mixin is some of the basic classes that have been written, and then combined into the desired class through different Mixin combinations.

Therefore, the basic understanding of cbv is to understand Mixin. In Django, Mixin is used to reuse code. A View Class can inherit multiple mixins, but only one View (including the View subclass) can be inherited. We recommend that you write the View on the rightmost side, multiple mixins are written on the left. Mixin is also a complex technology. I will not elaborate on it in this article. I will write an article on Mixin later.

Use decorator

In CBV, you can use method_decorator to describe the method.

from django.contrib.auth.decorators import login_requiredfrom django.utils.decorators import method_decoratorfrom django.views.generic import TemplateView class ProtectedView(TemplateView): template_name = 'secret.html'  @method_decorator(login_required) def dispatch(self, *args, **kwargs):  return super(ProtectedView, self).dispatch(*args, **kwargs)

You can also enter the method name in the class.

@method_decorator(login_required, name='dispatch')class ProtectedView(TemplateView): template_name = 'secret.html'

If you have multiple decorator decoration methods, you can write them as a list. For example, the two statements below are equivalent.

decorators = [never_cache, login_required] @method_decorator(decorators, name='dispatch')class ProtectedView(TemplateView): template_name = 'secret.html' @method_decorator(never_cache, name='dispatch')@method_decorator(login_required, name='dispatch')class ProtectedView(TemplateView): template_name = 'secret.html'

Summary

The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.