天天看點

第07章節-Python3.5-Django基于正規表達式的URL(一) 6效果圖:$ 效果圖:

image.png

  • urls.py:
"""s14day19_2 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^login/', views.login),
    # url(r'^home/', views.home),
    # views.Home.as_view()是固定用法
    url(r'^home/', views.Home.as_view()),
    url(r'^detail/', views.detail),
]

           
  • index.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--{{ user_dict.k1 }}-->
    <!--<ul>-->
        <!--{% for k in user_dict.keys %}-->
            <!--<li>{{ k }}</li>-->
        <!--{% endfor %}-->
    <!--</ul>-->
    <!--<ul>-->
        <!--{% for val in user_dict.values %}-->
            <!--<li>{{ val }}</li>-->
        <!--{% endfor %}-->
    <!--</ul>-->
    <ul>
        {% for k,row in user_dict.items %}
        <!--target="_blank"表示在新頁面打開-->
        <li><a target="_blank" href="/detail/?nid={{ k }}">{{ row.name }}</a></li>
        {% endfor %}
    </ul>

</body>
</html>
           
  • detail.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>詳細資訊</h1>
    <h6>使用者名: {{ detail_info.name }}</h6>
    <h6>郵箱: {{ detail_info.email }}</h6>

</body>
</html>
           
  • @ 進一步動态路由
  • 修改urls.py(Django基于正規表達式的URL):
from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^login/', views.login),
    # url(r'^home/', views.home),
    # views.Home.as_view()是固定用法
    url(r'^home/', views.Home.as_view()),
    # url(r'^detail/', views.detail),
    url(r'^detail-(\d+).html', views.detail),
]

           
  • 修改views.py:
from django.shortcuts import render,HttpResponse,redirect

# Create your views here.

# USER_DICT = {
#     'k1': 'root1',
#     'k2': 'root2',
#     'k3': 'root3',
#     'k4': 'root4',
# }

USER_DICT = {
    '1': {'name': 'root1', 'email': '[email protected]'},
    '2': {'name': 'root2', 'email': '[email protected]'},
    '3': {'name': 'root3', 'email': '[email protected]'},
    '4': {'name': 'root4', 'email': '[email protected]'},
    '5': {'name': 'root5', 'email': '[email protected]'},
}


def index(request):
    return render(request, 'index.html', {'user_dict': USER_DICT})


# def detail(request):
#     nid = request.GET.get('nid')
#     detail_info = USER_DICT[nid]
#     return render(request, 'detail.html', {'detail_info': detail_info})


def detail(request, nid):
    # return HttpResponse(nid)
    detail_info = USER_DICT[nid]
    return render(request, 'detail.html', {'detail_info': detail_info})


'''
def login(request):
    # 判斷使用者擷取資料方式是GET,就傳回什麼資料
    if request.method == "GET":
        return render(request, 'login.html')
    # 判斷使用者擷取資料方式是POST,就判斷使用者送出的資料是否正确
    elif request.method == "POST":
        u = request.POST.get('user')
        p = request.POST.get('pwd')
        if u == 'alex' and p == '123':
            return redirect('/index/')
        else:
            return render(request, 'login.html')
    else:
        # PUT,DELETE,HEAD,OPTION...
        return redirect("/index/")

'''


def login(request):
    # 判斷使用者擷取資料方式是GET,就傳回什麼資料
    if request.method == "GET":
        return render(request, 'login.html')
    # 判斷使用者擷取資料方式是POST,就判斷使用者送出的資料是否正确
    elif request.method == "POST":
        # radio
        # v = request.POST.get('gender')
        # print(v)
        # v = request.POST.getlist('favor')
        # print(v)
        v = request.POST.get('fff')
        print(v)
        # 所有上傳檔案都上傳到request.FILES
        obj = request.FILES.get('fff')
        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():
            f.write(i)
        f.close()

        return render(request, 'login.html')
    else:
        # PUT,DELETE,HEAD,OPTION...
        return redirect("/index/")


# def home(request):
#     return HttpResponse('Home')


from django.views import View


class Home(View):

    # 調用父類中的dispatch(相當于助理,)
    def dispatch(self, request, *args, **kwargs):
        print('before')
        result = super(Home,self).dispatch(request, *args, **kwargs)
        print('after')
        return result

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

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

           
  • 修改index.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--{{ user_dict.k1 }}-->
    <!--<ul>-->
        <!--{% for k in user_dict.keys %}-->
            <!--<li>{{ k }}</li>-->
        <!--{% endfor %}-->
    <!--</ul>-->
    <!--<ul>-->
        <!--{% for val in user_dict.values %}-->
            <!--<li>{{ val }}</li>-->
        <!--{% endfor %}-->
    <!--</ul>-->
    <!--<ul>-->
        <!--{% for k,row in user_dict.items %}-->
        <!--&lt;!&ndash;target="_blank"表示在新頁面打開&ndash;&gt;-->
        <!--<li><a target="_blank" href="/detail/?nid={{ k }}">{{ row.name }}</a></li>-->
        <!--{% endfor %}-->
    <!--</ul>-->
    <ul>
        {% for k,row in user_dict.items %}
        <!--target="_blank"表示在新頁面打開-->
        <li><a target="_blank" href="/detail-{{ k }}.html">{{ row.name }}</a></li>
        {% endfor %}
    </ul>

</body>
</html>
           
  • $ 效果圖: