The Class-based-view of Django Learning notes

Source: Internet
Author: User
Preface

We all know that it's very easy to learn Django, so you can get started with almost no effort. Configure a URL, give it a function to process it, return to response, almost nothing difficult to understand the place.

Write more, some problems only gradually realize. For example, a view is more complex and calls a lot of other functions. What if you want to encapsulate these functions? Of course, you can use the comment #------view------This way to isolate the function, this method is too low, is simply deceiving themselves, even the package is not counted.

Python is an object-oriented programming language, and if it is developed using only functions, there are many object-oriented advantages that are missed (inheritance, encapsulation, polymorphism). So Django joined the Class-based-view later. Let's write the view in class. The main advantages of this are the following two kinds:

    1. Improved reusability of code, using object-oriented techniques such as mixin (multiple inheritance)

    2. You can use different functions for different HTTP methods, rather than using many if judgments to improve code readability

Using class-based views

If we are going to write a view that handles the Get method, the following is the case with the function.

From django.http import HttpResponse def my_view (Request): if Request.method = = ' GET ':  # <view logic>  retur n HttpResponse (' result ')

If you write with class-based view, it is the following.

From django.http import httpresponsefrom django.views Import view class MyView (view): Def get (self, request):  # <vi EW logic>  return httpresponse (' result ')

The Django URL is to assign a request to a callable function instead of a class. To address this problem, class-based view provides a as_view() static method (that is, a class method) that calls this method, creates an instance of a class, and then invokes the dispatch() method dispatch() through the instance, Method calls the appropriate method to process the request (such as get() , etc.) according to the different methods of the request post() . Here, these methods are almost the same as Function-based view, to receive the request and get a response back. If the method is not defined, a httpresponsenotallowed exception is thrown.

In the URL, just write this:

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

The properties of a class can be set in two ways, the first being a common Python method that can be overridden by a 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 this in a subclass class Morninggreetingview (greetingview): greeting = "Morning to Ya"

The second method, you can also specify the properties of the class in the URL:

To set the properties of a class in a URL python

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

Using Mixin

I think to understand Django's Class-based-view (hereinafter referred to as CBV), the first thing to understand is the purpose of Django introduced CBV. Before django1.3, generic view was the so-called generic view, using Function-based-view (FBV), a function-based view. Some people think that fbv than CBV more pythonic, stealing think otherwise. One of the most important features of Python is object-oriented. And CBV is more capable of embodying Python's object-oriented. CBV is a way of implementing view methods through class. Class is more likely to take advantage of polymorphism than function, so it is easier to abstract the more common functions within a project from a macro level. About polymorphism, not much explanation, interested students themselves Google. In short, it can be understood that a thing has many forms (characteristics). CBV the implementation of the principle by looking at the Django source code is easy to understand, basically by the URL routed to this CBV, through the CBV internal dispatch method to distribute, The GET request is distributed to the Cbv.get method processing, and the post request is distributed to the Cbv.post method, and other methods are similar. How do you use polymorphism? The concept of mixin was introduced in CBV. Mixin are some of the basic classes that have been written, and then become the ultimate class by different mixin combinations.

So, understanding CBV is based on understanding mixin. Django uses mixin to reuse code, a view class can inherit multiple mixin, but only one view (including the sub-class of view), it is recommended to write the view on the far right, and multiple mixin on the left. Mixin is also a relatively complex technology, this article does not elaborate, later write an article for mixin.

Using adorners

In CBV, you can use Method_decorator to decorate 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)

It can also be written on the class, passing in the name of the method.

@method_decorator (login_required, Name= ' dispatch ') class Protectedview (Templateview): template_name = ' secret.html '

If you have more than one adorner decorating a method, you can write a list. For example, the following two types of notation 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 '


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.