django中的FBV和CBV
2017-05-23 22:45
465 查看
django中请求处理方式有2种:FBV 和 CBV
一、FBV
FBV(function base 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(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>
上面就是FBV的使用。
二、CBV
CBV(class base 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, 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 ,类中函数名必须小写。
两种方式没有优劣,都可以使用。
标签:base text onf div spa 2种 inpu site .py
原文:http://www.cnblogs.com/wumingxiaoyao/p/6513981.html
相关文章推荐
- python3-开发进阶Django-CBV和FBV及CBV的源码分析
- Django(CBV/FBV/COOKIE/SESSION/TEMPLATE/HEADER)
- Django的CBV和FBV
- Python菜鸟之路:Django 路由补充1:FBV和CBV - 补充2:url默认参数
- Django 之 CBV & FBV
- django中的FBV和CBV
- Django的CBV和FBV
- django -- cbv,fbv,中间件
- django中的FBV和CBV
- django学习 笔记---给cookie添加装饰器(FBV和CBV模式)
- Django框架学习笔记(6.FBV和CBV简单介绍)
- Django-CBV和FBV
- Django CBV(Class-Base View) vs FBV(Function-Base View)
- Django-中的FBV和CBV
- Django之FBV和CBV
- django路由系统,FBV,CBV,ORM操作
- Python/Django(CBV/FBV/ORM操作)
- Django中的Cookie和Session操作以及CBV
- django cbv
- Django的CBV方式讲解