Examples of CBV and FBV in Django and djangocbvfbv
Preface
This article mainly introduces the CBV and FBV content in Django and shares them for your reference. I will not talk about them much below. Let's take a look at the detailed introduction.
1. CBV
CBV uses an object-oriented method to write view files.
CBV execution process:
The browser sends a request to the server. py matches the url according to the request, finds the View class to be executed, executes the dispatch method to distinguish whether it is a POST request or a GET request, and executes views. the POST method or GET method in The py class.
Instance used:
Urls. py
path('login/',views.Login.as_view())
Views. py
From django import views # add class Login (views. views): def get (self, request) pass def pass (self, request) pass based on Views. py
Use decorator:
from django import viewsfrom django.utils.decorators import method_decoratordef outer(func): def inner(request,*args,**kwargs): return func(request,*args,**kwargs) return innerclass Login(views.View): @method_decorator(outer) def get(self,request,*args,**kwargs): pass
Adding a decorator to a class is a property of adding a decorator to a function. However, the addition method is different.
Eg:
@method_decorator(outer,name='dispatch')class Login(views.View):
Custom dispatch:
class Login(views.View): def dispatch(self, request, *args, **kwargs): print(2222) ret = super(Login, self).dispatch(request, *args, **kwargs) print(1111) return retdef get(self, request, *args, **kwargs): print('GET') return HttpResponse('OK')
Execution result: 2222
GET 1111
Ii. FBV
FBV writes views in the form of functions in views. py.
Check the Code:
Urls. py
from django.conf.urls import url, include# from django.contrib import adminfrom mytest import views urlpatterns = [ # url(r‘^admin/‘, admin.site.urls), url(r‘^index/‘, views.index),]
Views. py
from django.shortcuts import renderdef index(req): if req.method == ‘POST‘: print(‘method is :‘ + req.method) elif req.method == ‘GET‘: print(‘method is :‘ + req.method) return render(req, ‘index.html‘)
Note that the function [def index (req):] is defined here ):]
Index.html
<! DOCTYPE html>
The above is the use of FBV.
Summary
The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.