In Django, two request processing methods are available: fbv and CBV.
I. fbv
Fbv (function base views)Is to use functions in the view to process requests.
Check the Code:
URLs. py
12345678 |
from django.conf.urls import url, include # from django.contrib import admin from mytest import views urlpatterns = [ # url(r‘^admin/‘, admin.site.urls), url(r‘^index / ‘, views.index), ] |
Views. py
123456789 |
from django.shortcuts import render def 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
12345678910111213 |
<!DOCTYPE html> = "en" > <meta charset = "UTF-8" > <title>index< / title> < / head> <body> <form action = " " method=" post"> < input type = "text" name = "A" / > < input type = "submit" name = "b" value = "Submit" / > < / form> < / body> < / html>
|
The above is the use of fbv.
Ii. CBV
CBV (class base views)The class is used to process requests in the view.
Modify URLs. py in the above Code as follows:
123456 |
from mytest import views urlpatterns = [ # url(r‘^index/‘, views.index), url(r‘^index / ‘, views.Index.as_view()), ] |
Note: URL (R' ^ index/', views. Index. as_view () is a fixed usage.
Modify views. py in the above Code as follows:
1234567891011 |
from django.views import View class Index(View): def get( self , req): print (‘method is :‘ + req.method) return render(req, ‘index.html‘) def post( self , req): print (‘method is :‘ + req.method) return render(req, ‘index.html‘) |
Note: To Inherit the view, the number of letters in the class must be in lower case.
You can use either of the two methods.
Fbv and CBV in Django
Fbv and CBV in Django