web前端基础知识-(七)Django进阶

通过上节课的学习,我们已经对Django有了简单的了解,现在来深入了解下~

1. 路由系统

1.1 单一路由对应

1
url(r'^index$', views.index),

1.2 基于正则的路由

1
2
url(r'^index/(\d*)', views.index),
url(r'^manage/(?P<name>\w*)/(?P<id>\d*)', views.manage),
  • 找到urls.py文件,修改路由规则
1
2
3
4
5
6
7
8
from django.conf.urls import url,include
from django.contrib import admin
from cmdb import views
  
urlpatterns = [
    url(r'^index', views.index),
    url(r'^detail-(\d+).html/', views.detail),
]
  • 在views.py文件创建对应方法
1
2
3
4
5
6
7
8
9
10
11
12
13
USER_DICT = {
    '1':{'name':'root1','email':'root@live.com'},
    '2':{'name':'root2','email':'root@live.com'},
    '3':{'name':'root3','email':'root@live.com'},
    '4':{'name':'root4','email':'root@live.com'},
}
  
def index(request):
    return render(request,"index.html",{"user_dict":USER_DICT})
  
def detail(request,nid):  # nid指定的是(\d+)里的内容
    detail_info = USER_DICT[nid]
    return render(request, "detail.html", {"detail_info": detail_info})

1.3 url分组

在url.py增加对应路径

1
2
3
4
5
6
7
8
from django.conf.urls import url,include
from django.contrib import admin
from cmdb import views
  
urlpatterns = [
    url(r'^index', views.index),
    url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html/', views.detail),<br>   # nid=\d+ uid=\d+
]

在views.py文件创建对应方法

1
2
3
4
5
6
def detail(request,**kwargs):
    print(kwargs)         
    #{'nid': '4', 'uid': '3'}
    nid = kwargs.get("nid")
    detail_info = USER_DICT[nid]
    return render(request, "detail.html", {"detail_info": detail_info})

1.4 为路由映射名称

1
2
3
4
5
6
7
8
9
from django.conf.urls import url,include
from django.contrib import admin
from cmdb import views
  
urlpatterns = [
    url(r'^asdfasdfasdf/', views.index, name='i1'),     #第一种方式i1
    url(r'^yug/(\d+)/(\d+)/', views.index, name='i2'),  #第二种方式i2
    url(r'^buy/(?P<pid>\d+)/(?P<nid>\d+)/', views.index, name='i3'),    #第三种方式i3
]

在templates目录下的index.html

1
2
3
4
5
6
7
8
9
10
11
12
<body>
{#第一种方法i1       路径asdfasdfasdf/#}
{#<form action="{% url "i1" %}" method="post">#}
{#第二种方法i2       路径yug/1/2/#}
{#<form action="{% url "i2" 1 2 %}" method="post">#}
{#第三种方法i3       路径buy/1/9//#}
<form action="{% url "i3" pid=1 nid=9 %}" method="post">
    <p><input  name="user" type="text" placeholder="用户名"/></p>
    <p><input  name="password" type="password" placeholder="密码"/></p>
    <p><input type="submit" value="提交"/></p>
</form>
</body>

1.5 根据app对路由分类

主程序urls.py文件

1
2
3
4
5
6
from django.conf.urls import url,include
from django.contrib import admin
  
urlpatterns = [
    url(r'^monitor/', include('monitor.urls')), #调整到monitor目录中的urls.py文件
]

cmdb下的url.py文件

1
2
3
4
5
6
7
from django.conf.urls import url
from django.contrib import admin
from monitor import views
#
urlpatterns = [
    url(r'^login', views.login),
]

1.6 获取当前URL

view.py中配置

1
2
3
4
def index(request):
    print(request.path_info)    #获取客户端当前的访问链接
    # / index
    return render(request,"index.html",{"user_dict":USER_DICT})

在templates目录下的index.html文件

1
2
3
4
5
<form action="{{ request.path_info }}" method="post">
    <p><input  name="user" type="text" placeholder="用户名"/></p>
    <p><input  name="password" type="password" placeholder="密码"/></p>
    <p><input type="submit" value="提交"/></p>
</form>

2. 视图

2.1 获取用户请求数据

request.GET

request.POST

request.FILES 

其中,GET一般用于获取/查询 资源信息,而POST一般用于更新 资源信息 ; FILES用来获取上传文件;

2.2 checkbox等多选的内容

在templates目录下创建login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/login" method="POST" >
        <p>
            男:<input type="checkbox"  name="favor" value="11"/>
            女:<input type="checkbox" name="favor" value="22"/>
            人妖:<input type="checkbox" name="favor" value="33"/>
        </p>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

修改views.py文件对表单处理

1
2
3
4
5
6
7
8
9
10
11
def login(request):
    #checkbox  多选框
    if request.method == "POST":
        favor_list = request.POST.getlist("favor")      #getlist获取多个值
        print(favor_list)           #多选框获取到的是列表格式
        #['11', '22', '33']
        return render(request,"login.html")
    elif request.method == "GET":
        return render(request,"login.html")
    else:
        print("other")

2.3 上传文件

1
2
3
4
文件对象 = reqeust.FILES.get()
文件对象.name
文件对象.size
文件对象.chunks()

 

在templates目录下创建login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/login" method="POST" enctype="multipart/form-data">
        <p>
            <input type="file" name="files"/>
        </p>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

修改views.py文件对表单处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def login(request):
    #file 上传文件
    if request.method == "POST":
        obj = request.FILES.get('files')       #用files获取文件对象
        if obj:
            print(obj, type(obj), obj.name)
            # test.jpg <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> test.jpg
            import os
            file_path = os.path.join('upload', obj.name)
            f = open(file_path, "wb")
            for item in obj.chunks():      #chunks表示所有的数据块,是个迭代器
                f.write(item)
            f.close()
        return render(request,"login.html")
    elif request.method == "GET":
        return render(request,"login.html")
    else:
        print("other")

2.4 FBV & CBV

2.4.1 FBV

1.在templates目录下创建home.html文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/home/" method="POST">
    <p>
        <input type="text" name="user" placeholder="用户名"/>
    </p>
    <p>
        <input type="password" name="pwd" placeholder="密码"/>
    </p>
    <p>
        <input type="submit" value="提交">
    </p>
</form>
</body>
</html>

2. 在urls.py文件增加home路径

1
2
3
4
5
6
7
8
from django.conf.urls import url,include
from django.contrib import admin
from cmdb import views
  
urlpatterns = [
     # 固定语法
    url(r'^home/', views.Home.as_view()),
]

3. 在views.py文件创建函数Home

1
2
def home(request):
        return render(request,"home.html")

2.4.2 CBV

1. 在templates目录下创建home.html文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/home/" method="POST">
    <p>
        <input type="text" name="user" placeholder="用户名"/>
    </p>
    <p>
        <input type="password" name="pwd" placeholder="密码"/>
    </p>
    <p>
        <input type="submit" value="提交">
    </p>
</form>
</body>
</html>

2. 在urls.py文件增加home路径

1
2
3
4
5
6
7
8
from django.conf.urls import url,include
from django.contrib import admin
from cmdb import views
  
urlpatterns = [
     # 固定语法
    url(r'^home/', views.Home.as_view()),
]

3. 在views.py文件创建类Home

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from django.views import View
  
class Home(View):
    # 先执行dispatch里面的内容
    def dispatch(self,request, *args, **kwargs):
        print("before")
        # 调用父类中的dispatch
        result = super(Home,self).dispatch(request, *args, **kwargs)
        print("after")
        return result
  
    # 根据反射获取用户提交方式,执行get或post方法
    def get(self,request):
        print(request.method)
        return render(request,"home.html")
  
    def post(self,request):
        print(request.method)
        return render(request,"home.html")
posted @ 2016-12-23 16:43  wangsen123  阅读(145)  评论(0编辑  收藏  举报