Get the App
SLTechnology News&Howtos  ›  Development  › 

What the CBV and FBV views look like

Shulou Source: shulou.com Published: 2022-06-03 05:31:25 09月27日 Update

In view of what the CBV and FBV views look like, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

CBV and FBV views

FBV (functionbaseviews) uses functions to handle requests in the view.

Previously, the code was written in FBV mode, so I won't write examples.

CBV (classbaseviews) uses classes to handle requests in the view.

Python is an object-oriented programming language, if you only use functions to develop, there are many object-oriented advantages will be missed (inheritance, encapsulation, polymorphism). So Django later joined Class-Based-View. Let's write View with classes. There are two main advantages of this:

Improved code reusability by using object-oriented technologies such as Mixin (multiple inheritance)

You can use different functions to deal with different HTTP methods, rather than through many if judgments to improve the readability of the code.

Django's url assigns a request to a callable function, not a class. To solve this problem, class-basedview provides an as_view () static method (that is, class method). If you call this method, you will create an instance of the class, and then call the dispatch () method through the instance, and the dispatch () method will call the corresponding method to handle the request (such as get (), post (), etc.) according to the method of request. At this point, these methods are almost the same as function-basedview. To receive request, you get a response return. If the method is not defined, a HttpResponseNotAllowed exception is thrown.

CBV passes parameters, similar to FBV, named grouping, nameless grouping

Url: nameless grouped

Url (r'^ cv/ (\ d {2}) /', views.Myd.as_view (), name='cv')

Url (r'^ cv/ (? P\ d {2}) /', views.Myd.as_view (name='xxx'), name='cv'), # if you want to assign a value to the name attribute of a class, you must have a name attribute in your Myd class (class attribute, defining the init method to accept the property does not work, but you can study it yourself to see how it works, it doesn't make much sense), and the value of the name attribute in the previous class will be overwritten.

This is the answer to the question about what the CBV and FBV views are. I hope the above content can be of some help to you. If you still have a lot of doubts to solve, you can follow the industry information channel for more related knowledge.

Tags: Methods views properties functions problems processing differences code objects grouping advantages examples that is more help solutions polymorphism easy famous almost Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Shulou Information NVidia Xiaomi Redmi