码迷,mamicode.com
首页 > 编程语言 > 详细

【python】-- Django路由系统(网址关系映射)、视图、模板

时间:2018-02-08 20:02:35      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:sed   func   base   res   etl   博文   ons   cti   dispatch   

Django路由系统(网址关系映射)、视图、模板

 

一、路由系统(网址关系映射)

1、单一路由对应:

一个url对应一个视图函数(类)

urls.py:
url(r‘^test‘, views.test), 
#url(r‘^home‘, views.Test.as_view()),

views.py:
def test(request):
    print(request.method)
    return render(request, "home.html")
"""
class Test(View):

    def get(self, request):
        print(request.method)
        return render(request, "home.html")

    def post(self, request):
        print(request.method)
        return render(request, "home.html")
"""

  

 2、基于正则路由对应:

多个url对应一个视图

urls.py
# 多个url对应一个视图函数,不过在给视图函数传参时,要根据对应形参位置进行传参
url(r‘^detail-(\d+)-(\d+).html‘, views.detail),
# 多个url对应一个视图函数,推荐这种写法,在正则匹配完毕后进行了分组分配,在传参时就可以形参位置变化也没有关系
url(r‘^detail-(?P<nid>\d+)-(?P<uid>\d+).html‘, views.detail),

views.py:
#普通传参
def detail(request, nid, uid):
    print(nid, uid)
    return HttpResponse("%s - %s" % (nid, uid))
#args传参
def detail(request, *args, **kwargs):
    print(args[0], args[1])
    return HttpResponse("%s - %s" % (args[0], args[1]))
#kwargs传参
def detail(request, *args, **kwargs):
    print(kwargs["nid"], kwargs["uid"])
    return HttpResponse("%s - %s" % (kwargs["nid"], kwargs["uid"]))

 

3、name:

对URL路由关系进行命名,以后可以根据此名称生成自己想要的URL

urls.py:
url(r‘^url_1/‘, views.index, name=‘i1‘),
url(r‘^url_2/(\d+)/(\d+)/‘, views.index, name=‘i2‘),
url(r‘^url_3/(?P<pid>\d+)/(?P<nid>\d+)/‘, views.index, name=‘i3‘),
		
views.py:
from django.urls import reverse
def func(request, *args, **kwargs):
    url1 = reverse(‘i1‘)                              # url_1/
    url2 = reverse(‘i2‘, args=(1,2,))                 # url_2/1/2/
    url3 = reverse(‘i3‘, kwargs={‘pid‘: 1, "nid": 9}) # url_3/1/9/


xxx.html:
    
    {% url "i1" %}               # url_1/
    {% url "i2" 1 2 %}           # url_2/1/2/
    {% url "i3" pid=1 nid=9 %}   # url_3/1/9/

PS:
    # 显示当前的URL
    request.path_info 

 

4、多级路由:

多级路由目的避免有多个app时,在project urls.py的路由(网址)因路径名称一致而引起的冲突

#project/urls.py:
    from django.conf.urls import url, include
    from django.contrib import admin
    urlpatterns = [
        url(r‘^app1/‘, include("app1.urls")),
        url(r‘^app2/‘, include("app2.urls")),
    ]

#app01/urls.py:
    from django.conf.urls import url
    from app1 import views
    urlpatterns = [
        url(r‘^test‘, views.test),
    ]

#app02/urls.py:
    from django.conf.urls import url
    from app2 import views
    urlpatterns = [
        url(r‘^test‘, views.test),
    ]

5、默认值、命名空间

pass

  

  

二、视图

1、FBV&CBV

1.1、 FBV (Function Base VIew)在view(视图)中基于函数编写逻辑

#urls.py:
url(r‘^test‘, views.test),  # FBV  function base view


#views.py:
def test(request):
    if request.method == "GET":
        return render(request, ‘test.html‘)

1.2、CBV(Class Base Viev)在view(视图)中基于类编写逻辑

#urls.py;
url(r‘^home‘, views.Test.as_view()),  # CBV  class base view   .as_view() Test没有view所以在views.py中Test类中继承Django的View


#views.py:
from django.views import View


class Test(View):

    # 调用父类中的dispatch方法,并重写
    def dispatch(self, request, *args, **kwargs):  # 通过dispatch的反射可以找到如:get、post方法的起始点
        print("before")
        result = super(Test, self).dispatch(request, *args, **kwargs)
        return result

    def get(self, request):
        print(request.method)
        return render(request, "home.html")

    def post(self, request):
        print(request.method)
        return render(request, "home.html")

 

2、HTML from表单提交数据的提取示例:

技术分享图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/test" method="POST" enctype="multipart/form-data"><!--enctypes属性没有的话,默认提交的是字符串,无法实现文件上传-->
        <p>
            <input type="text" name="user" placeholder="用户名" />
        </p>
        <p>
            <input type="password" name="pwd" placeholder="密码" />
        </p>
        <p>
            男:<input type="radio"  name="gender" value="1"/>
            女:<input type="radio" name="gender" value="2"/>
            张扬:<input type="radio" name="gender" value="3"/>
        </p>
        <p>
            男:<input type="checkbox"  name="favor" value="11"/>
            女:<input type="checkbox" name="favor" value="22"/>
            张扬:<input type="checkbox" name="favor" value="33"/>
        </p>
        <p>
            <select name="city" multiple>
                <option value="sh">上海</option>
                <option value="bj">北京</option>
                <option value="tj">天津</option>
            </select>
        </p>
        <p>
            <input type="file" name="file"/>
        </p>

        <input type="submit" value="提交"/>
    </form>
</body>
</html>
test.html
def test(request):
    if request.method == "GET":
        return render(request, ‘test.html‘)
    elif request.method == "POST":
        # text
        v = request.POST.get(‘pwd‘)   # 获取input输入框输入的value
        print(v)
        # radio
        v0 = request.POST.get(‘gender‘)   # 获取radio的value
        print(v0)
        # checkbox
        v1 = request.POST.getlist(‘favor‘)   # 获取checkbox多选情况下的value
        print(v1)
        # select
        v2 = request.POST.getlist(‘city‘)   # 获取select下拉框multiple情况下的value
        print(v2)
        # file
        obj = request.FILES.get(‘file‘)    # 获取上传文件并保存
        print(obj, type(obj), obj.name)
        import os
        file_path = os.path.join(‘upload‘, obj.name)
        f = open(file_path, mode="wb")
        for i in obj.chunks():  # chunks()利用生成器,每次只加载部分上传的文件,直至加载完毕
            f.write(i)
        f.close()
        return redirect("/test")
    else:
        # PUT,DELETE,HEAD,OPTION...
        return redirect("/test")

  

 三、模板

上一篇博文有粗略概况

pass

  

【python】-- Django路由系统(网址关系映射)、视图、模板

标签:sed   func   base   res   etl   博文   ons   cti   dispatch   

原文地址:https://www.cnblogs.com/Keep-Ambition/p/8432374.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!