1. 程式人生 > >Django 系列部落格(三)

Django 系列部落格(三)

Django 系列部落格(三)

前言

本篇部落格介紹 django 的前後端互動及如何處理 get 請求和 post 請求。

get 請求

get請求是單純的請求一個頁面資源,一般不建議進行賬號資訊的傳輸。

配置路由

from django.conf.urls import url
from django.contrib import admin

import app.views as app_views
import newApp.views as new_views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', app_views.home),
    # 路由採用正則匹配, ^以什麼開頭 $以什麼結果
    # 注: 當路由沒有子路由是,才在末尾新增$
    url(r'^index/$', app_views.index),
    url(r'login', app_views.login_action),
    url(r'^new/index/$', new_views.index)
]

配置檢視

from django.shortcuts import render, redirect

from django.http import HttpResponse

# Create your views here.

# 每一個請求,都對應一個檢視響應函式,來出現請求,完成響應
# def index(abc):
#     return HttpResponse('hello django')  # 第一個響應

import django.core.handlers.wsgi
def login_action(request):
    return render(request, 'login.html') # 第一個響應頁面

# def home(request):
#     return redirect('/index/') # 第一個重定向

def home(request):
    return render(request, 'index.html')

def index(request):
    return redirect('/')

配置頁面資源

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>主頁</title>
</head>
<body>
    <h1 style="text-align: center">app的主頁</h1>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>登入</title>
</head>
<body>
    <h1 style="color: red">登入</h1>
</body>
</html>

post 請求

配置路由

from django.conf.urls import url
from django.contrib import admin

from app import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.home),
    url(r'^index/$', views.index),
    url(r'^login/$', views.login, name='lg'),
]

配置檢視

from django.shortcuts import render, redirect
import pymysql

# Create your views here.

def home(request):
    return render(request, 'index.html')

def index(request):
    return redirect('/')

'''
def login(request):
    print(request.method)
    # 如果獲取GET請求的提交資料
    # import django.core.handlers.wsgi
    # print(type(request))
    # import django.http.request.QueryDict
    # print(type(request.GET))
    print(request.GET)
    # usr = request.GET['usr']  # 不安全
    usr = request.GET.get('usr', 'USR') # 安全, 第一個引數為資料的key, 第二個引數為預設值
    print(usr)
    pwd = request.GET.get('pwd') # 不設預設值,沒有取到值時,返回值為None
    print(pwd)
    return render(request, 'login.html')
'''

from django.http import HttpResponse

def login(request):
    if request.method == 'GET':
        stus = request.GET.getlist('stu')
        print(stus)
        return render(request, 'login.html')

    # 沒有GET分支, 發來的請求為POST
    usr = request.POST.get('usr')
    pwd = request.POST.get('pwd')
    print(usr, pwd)

    # 連線資料庫 => ORM
    conn = pymysql.connect(host='localhost', port=3306, user='root', password='root', db='django')
    cur = conn.cursor(pymysql.cursors.DictCursor)
    # cur.execute('select * from user')
    # users = cur.fetchall()
    cur.execute('select * from user where usr=%s and pwd=%s', [usr, pwd])
    res = cur.fetchone()
    print(res)
    if res != None:
        return HttpResponse('登入成功')
    return HttpResponse('登入失敗')

配置頁面資源

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>主頁</title>
{#    <link rel="stylesheet" href="./index.css">#}
{#    <link rel="stylesheet" href="/static/index.css">#}
{#    <link rel="stylesheet" href="/static/temp.css">#}

{#    <link rel="stylesheet" href="/ooo/index.css">#}
{#    <link rel="stylesheet" href="/ooo/temp.css">#}

{#    <link rel="stylesheet" href="/static/css/test.css">#}

    <link rel="stylesheet" href="/static/css/index.css">
</head>
<body>
    <h1 style="text-align: center">主頁</h1>
    <img src="/static/img/001.png" alt="">
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>登入</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
    <style>
        .box {
            border: 1px solid #ccc;
            padding: 20px;
            border-radius: 20px;
            height: 380px;
        }
    </style>
</head>
<body>
{#<button class="btn btn-warning"> 按鈕</button>#}
{#<div class="btn-group">#}
{#    <button class="btn btn-default btn-lg dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true"#}
{#            aria-expanded="false">#}
{#        Large button <span class="caret"></span>#}
{#    </button>#}
{#    <ul class="dropdown-menu">#}
{#        <li><a href="#">Action</a></li>#}
{#        <li><a href="#">Another action</a></li>#}
{#        <li><a href="#">Something else here</a></li>#}
{#        <li role="separator" class="divider"></li>#}
{#        <li><a href="#">Separated link</a></li>#}
{#    </ul>#}
{#</div>#}

<div class="container">
    <div class="box row col-sm-6 col-sm-offset-3">
        {# action: 沒寫 | http://localhost:8801/login | /login/ | {% url 'url_name' %} #}
        <form action="{% url 'lg' %}" method="GET">
{#            {% csrf_token %}#}
            <div class="form-group">
                <label for="usr">使用者名稱:</label>
                <input type="text" class="form-control" name="usr" id="usr" placeholder="請輸入使用者名稱">
            </div>
            <div class="form-group">
                <label for="pwd">Password</label>
                <input type="password" class="form-control" name="pwd" id="pwd" placeholder="請輸入密碼">
            </div>
            <div class="checkbox">
                <label>
                    <input name="stu" type="checkbox" value="stu1"> 學生1
                </label>
                <label>
                    <input name="stu" type="checkbox" value="stu2"> 學生2
                </label>
                <label>
                    <input name="stu" type="checkbox" value="stu3"> 學生3
                </label>
            </div>
            <button type="submit" class="btn btn-info pull-right">登入</button>
        </form>
    </div>
</div>
{#<a href="/index/">前往主頁</a>#}
</body>
<script src="/static/bootstrap-3.3.7-dist/js/jquery-3.3.1.js"></script>
<script src="/static/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
</html>

前後端互動

Django請求生命週期