1. 程式人生 > 其它 >django之路由層和反向解析

django之路由層和反向解析

目錄

視覺化介面之資料增刪改查

專案初始化步驟

1.建立django專案,建立模板和靜態目錄,建立app

django-admin startproject djangoday03
cd djangoday03
mkdir templates
mkdir static
python38 manage.py startapp app01


2.pycharm開啟新建立的djangoday03專案
3.修改templates路徑(settings.py)

'DIRS': [os.path.join(BASE_DIR,'templates')],

4.註冊app01(settings.py)

INSTALLED_APPS = [
 'app01',
]

5.修改資料庫為mysql(settings.py)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'day51',
        'HOST':'127.0.0.1',
        'PORT':3306,
        'USER':'root',
        'PASSWORD':'Abcd1234',
        'CHARSET':'utf8',
    }
}

6.新增靜態路徑支援(settings.py)

STATICFILES_DIRS = [os.path.join(BASE_DIR,'static'),
                    ]

7.post傳送請求會報錯註釋其中的一行(settings.py)

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

8.ORM資料模型準備(app01裡面的models.py)

class User2(models.Model):
    # 主鍵欄位可以不寫 ORM會自動幫你建立一個id的主鍵欄位
    name = models.CharField(max_length=32,verbose_name='使用者名稱')
    age = models.IntegerField(verbose_name='年齡')

    # 便於物件列印之後的檢視 不影響資料庫 所以不需要執行遷移命令
    def __str__(self):
        return '使用者物件:%s' % self.name

9.啟動django服務

python38 manage.py runserver

10.執行資料庫遷移相關命令(操作前確保沒有相關表)

python38 manage.py  makemigrations  將操作記錄到小本本上(migrations)
python38 manage.py  migrate			將操作同步到資料庫上

11.對User2表填充相關資料

#登入資料庫客戶端day51庫下進行操作,模擬資料
insert into app01_user2(name,age) values('jason',18),('tony',19),('winter',23),('jerry',28),('oscar',32);

訪問使用者資料的介面

1.新增路由及對應的功能函式(urls.py)

from app01 import  views
# 訪問使用者資料的介面
path('user_list/',views.user_list_func),

2.編輯檢視層,新增後端功能(view.py)

from django.shortcuts import render,HttpResponse,redirect
from app01 import models

# Create your views here.

def user_list_func(request):
    # 1.獲取user2表中所有的資料展示到html頁面上
    user_data = models.User2.objects.filter()  # 括號內不填篩選條件等價於檢視所有 QuerSet [物件1,物件2,物件3...]
    # 2.利用模板語法傳遞資料到html頁面並完成處理最終返回給瀏覽器展示
    return render(request,'userListPage.html',{'user_data':user_data})

3.準備對應的userListPage.html檔案

1.拷貝bootstrap-3.4.1-dist本地靜態資源到static目錄下
2.編寫userListPage.html檔案(templates目錄)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
    {% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.css' %}">
    <script src="{% static 'bootstrap-3.4.1-dist/js/bootstrap.js' %}"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <h1 class="text-center">資料展示頁</h1>
            <div class="col-md-8 col-md-offset-2">
            <table class="table  table-hover table-striped">
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>Name</th>
                        <th>Age</th>
                        <th class="text-center">Operation</th>
                    </tr>
                </thead>
                <tbody>
                    {% for user_obj in user_data %}
                        <tr>
                            <td>{{ user_obj.pk }}</td>
                            <td>{{ user_obj.name }}</td>
                            <td>{{ user_obj.age }}</td>
                            <td class="text-center">
                                <a href="#" class="btn btn-primary btn-xs">編輯</a>
                                <a href="#" class="btn btn-danger btn-xs delete">刪除</a>
                            </td>
                        </tr>
                    {% endfor %}

                </tbody>
            </table>
            </div>
        </div>
    </div>
</body>
</html>

4.瀏覽器開啟訪問

http://127.0.0.1:8000/user_list/

資料新增

1.新增路由層(urls.py)

# 新增使用者資料的介面
path('user_add/',views.user_add_func),

2.編輯檢視層,新增後端功能(view.py)

def user_add_func(request):
    #1.先返回一個獲取新增使用者資料的html頁面
    return render(request,'userAddPage.html')

3.建立對應userAddPage.html檔案(templates目錄)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
    {% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.css' %}">
    <script src="{% static 'bootstrap-3.4.1-dist/js/bootstrap.js' %}"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <h1 class="text-center">資料新增頁</h1>
            <div class="col-md-6 col-md-offset-3">
                <form action="" method="post">
                    <p>name:
                        <input type="text" name="name" class="form-control">
                    </p>
                    <p>age:
                        <input type="text" name="age" class="form-control">
                    </p>
                    <input type="submit" value="新增使用者" class="btn btn-warning btn-block">
                </form>
            </div>
        </div>
    </div>
</body>
</html>

4.資料展示頁面要新增一個數據新增入口(userListPage.html)

        <h1 class="text-center">資料展示頁</h1>
            <div class="col-md-8 col-md-offset-2">
                <a href="/user_add/" class="btn btn-success">資料新增</a>  /新增這行/

5.再次編輯後端邏輯介面(views.py)

def user_add_func(request):
    #2.根據不同的請求方式做不同的處理
    if request.method == 'POST':
        #3.獲取使用者相關資料
        name_data = request.POST.get('name')
        age_data = request.POST.get('age')
        #4.繼續一些小的判斷
        if len(name_data) == 0 or len(age_data) ==0:
            return HttpResponse('使用者名稱或年齡不能為空')
        user_data=models.User2.objects.filter(name=name_data)
        if user_data:
            return HttpResponse('使用者名稱已存在')
        models.User2.objects.create(name=name_data,age=age_data)
        # 5.重定向到資料展示頁
        return redirect('/user_list/')
    #1.先返回一個獲取新增使用者資料的html頁面
    return render(request,'userAddPage.html')



django請求生命週期流程圖

django路由層

反向解析