7.18. Django View-FBV and CBV

发布时间 : 2025-10-25 13:33:28 UTC      

Page Views: 9 views

FBV(function base views) A function-based view is to use a function to handle requests in the view.

CBV(class base views) A class-based view is to use classes to handle requests in the view.

7.18.1. FBV

In fact, we have been using the function-based view in the previous section, that is, we use the function to process the user’s request. Check the following example:

Routing configuration:

Urls.py file

urlpatterns = [ path("login/", views.login), ] 

Views.py file

from django.shortcuts import render,HttpResponse def login(request): if request.method == "GET": return HttpResponse("GET 方法") if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") if user == "runoob" and pwd == "123456": return HttpResponse("POST 方法") else: return HttpResponse("POST 方法1") 

If we access http://127.0.0.1:8000/login/ directly in the browser, the output is as follows:

GET 方法 

7.18.2. CBV

Based on the view of the class, we use the class to handle the user’s request, and we can use different methods to deal with different requests in the class, which greatly improves the readability of the code.

The defined class inherits the parent class View, so you need to import the library first:

from django.views import View 

The dispatch method is executed prior to the execution of the corresponding requested method (in get/post/put… Method), the dispatch () method invokes the corresponding method according to the request.

In fact, everything we’ve learned before knows that Django’s url assigns a request to a callable function, not a class, so how do you implement a class-based view? Mainly through a static method as_view () provided by the parent class View, the as_view method is based on the external interface of the class, it returns a view function, and the request is passed to the dispatch method, and the dispatch method handles different methods according to different requests.

Routing configuration:

Urls.py file

urlpatterns = [ path("login/", views.Login.as_view()), ] 

Views.py file

from django.shortcuts import render,HttpResponse from django.views import View class Login(View): def get(self,request): return HttpResponse("GET 方法") def post(self,request): user = request.POST.get("user") pwd = request.POST.get("pwd") if user == "runoob" and pwd == "123456": return HttpResponse("POST 方法") else: return HttpResponse("POST 方法 1") 

If we access http://127.0.0.1:8000/login/ directly in the browser, the output is as follows:

GET 方法 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。