打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
django中的FBV和CBV

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

 

一、FBV

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

看代码:

urls.py

1
2
3
4
5
6
7
8
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

1
2
3
4
5
6
7
8
9
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‘)

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

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
='en'>
    ='UTF-8'>
    index/title>
/head>
    
='' method='post'>
        input type='text' name='A' />
        input type='submit' name='b' value='提交' />
    /form>
/body>
/html>

上面就是FBV的使用。

二、CBV

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

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

1
2
3
4
5
6
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 修改为如下:

1
2
3
4
5
6
7
8
9
10
11
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‘)

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

 

两种方式没有优劣,都可以使用。

django中的FBV和CBV

标签:base   text   onf   div   spa   2种   inpu   site   .py   

原文:http://www.cnblogs.com/wumingxiaoyao/p/6513981.html

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
python测试开发django-73.django视图 CBV 和 FBV
03 Django之视图函数
从cbv到fbv:用函数写视图与用类写视图的区别(drf与restful)
Django中URL视图函数的一些高级概念介绍
Django——视图层(请求&响应对象,cbv和fbv,文件上传)
Django——forms组件(form校验字段功能,渲染模板功能)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服