码迷,mamicode.com
首页 > 其他好文 > 详细

django中的FBV和CBV

时间:2017-10-09 00:31:34      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:turn   ret   get   注意   import   url   base   定义   class   

django中请求处理方式有2种:FBV 和 CBV

一、FBV

FBV(function-based views) 就是在视图里使用函数处理请求。

urls.py

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

from django.shortcuts import render
 
 
def index(request):
    if request.method == ‘POST‘:
        print(‘method is :‘ + request.method)
    elif request.method == ‘GET‘:
        print(‘method is :‘ + request.method)
    return render(request, index.html)

注意此处定义的是函数【def index(request):】

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <form action="" method="post">
        <input type="text" name="A" />
        <input type="submit" name="b" value="提交" />
    </form>
</body>
</html>

上面就是FBV的使用。

二、CBV

CBV(class-based views) 就是在视图里使用类处理请求。

将上述代码中的urls.py 修改为如下:

from mytest import views
 
urlpatterns = [
    # url(r‘^index/‘, views.index),
    url(r^index/, views.Index.as_view()),
]

注:url(r‘^index/‘, views.Index.as_view()),  是固定用法。

将上述代码中的views.py 修改为如下:

from django.views import View
 
 
class Index(View):
    def get(self, request):
        print(method is : + req.method)
        return render(request, index.html)
 
    def post(self, request):
        print(method is : + request.method)
        return render(request, index.html)

注:类要继承 View ,类中函数名必须小写。

django中的FBV和CBV

标签:turn   ret   get   注意   import   url   base   定义   class   

原文地址:http://www.cnblogs.com/NewTaul/p/7639140.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!