微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Django中CBV(类通用视图)和FBV(视图函数)详细解释

FBV、CBV是Django视图路由处理模型,当用户请求送达路由系统URL后,由其转发给视图view来分析并处理

CBV全称是class base views中文名字类通用视图

FBV全称是function base views中文名字视图函数

一、FBV实例:

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(req, ‘index.html‘)

index.html

<!DOCTYPE html>
<html>
<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实例

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, request):
        print(‘method is :‘ + request.method)
        return render(request, ‘index.html‘)
 
    def post(self,51); max-height: 35em; position: relative; widows: 1; margin-top: 0px !important;'><!DOCTYPE html>
<html>
<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 工程的网站:ccbv。结合 Django 源码学习 cbv 非常清晰。

参考:http://zmrenwu.com/post/33/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐