• 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
    <!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 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

  • 相关阅读:
    [转]Javascript中prototype和constructor详解
    [转]SCIM输入启动遭遇“Failed to load x11 FrontEnd module. ”错误
    [转]搭建高效的symbols服务器
    编译 boost 1.52.0
    opensuse 11.4 安装slickedit 2012 完美支持中文
    【转】MyEclipse 6.5 大提速
    [转]VS2005生成pdb签名的问题
    理解泛型 从需求演变开始
    数学中一个很简单的组合 但用程序如何去实现呢?
    从零开始开发服务器控件
  • 原文地址:https://www.cnblogs.com/qinghuani/p/8869264.html
Copyright © 2020-2023  润新知