The following article mainly introduces Class-basedView. Why does this Class-basedView exist? Isn't view a method? What is the relationship with the class? In fact, the answer is obvious. classes are actually used for abstraction, abstraction, and universal exposure, so that we can implement complex functions with the least amount of code. Let's take a look at the detailed introduction.
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:
This improves code reusability by using object-oriented technologies, such as Mixin (multi-inheritance)
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': #
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): #
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'
For more articles about Class-Based-View in Django learning notes, refer to PHP!