前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Django请求处理的两种方式:FBV 和 CBV

Django请求处理的两种方式:FBV 和 CBV

作者头像
菲宇
发布2019-06-13 11:03:07
6260
发布2019-06-13 11:03:07
举报
文章被收录于专栏:菲宇菲宇

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

一、FBV

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

看代码:

urls.py

from django.conf.urls import url, include
from mytest import views 


urlpatterns = [ 
    url(r‘^index/‘, views.index), 
]

views.py

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

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

二、CBV

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

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

from mytest import views

urlpatterns = [
    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, 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‘)

参考文章

https://blog.csdn.net/qq471011042/article/details/79344526

https://blog.csdn.net/qq471011042/article/details/79347062

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年01月05日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、FBV
  • 二、CBV
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档