Django 之 練習1:書籍管理


代碼目錄結構

在這裏插入圖片描述


配置文件

__init__.py(djangoSite)

# 聲明連接 mysql 數據庫, 使用 pymysql 模塊
# pymysql 使用 pip 安裝
# 安裝後需要連接可能會報錯, 需要註釋源碼中 26,27 行即可

import pymysql
pymysql.install_as_MySQLdb()

settings.py

# 當前 Django 項目中安裝的app都有哪些
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    'app02', # 這兩行都會生效, 一般使用這個即可
]

#  403 報錯需要註釋一箇中間件
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',
]

# 數據庫配置
DATABASES = {
    'default': {
        # sqlite3
        # 'ENGINE': 'django.db.backends.sqlite3',
        # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'xxx', # databaseName
        'HOST': 'xxx', # ip
        'PORT': 3306,
        'USER': 'root',
        'PASSWORD': '',
    }
}

# 靜態文件存放的路徑別名, 並非是存放路徑
STATIC_URL = '/static/'
# 實際存放路徑, 存放 css, js等
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]


邏輯代碼

訪問順序

瀏覽器 --> 接收 url --> urls.py 分析 --> views.py 處理邏輯 --> template 渲染頁面/ORM 操作數據庫 

urls.py

"""
因爲是 django3.0.3, 所以 path 和 re_path 是兩個不同的方法
"""

from django.contrib import admin
from django.urls import path, re_path
from app01 import views


# 用戶訪問的url和將要執行的函數的對應關係
urlpatterns = [
    path('admin/', admin.site.urls),
    # 新版django使用正則表達式需要使用re_path()
    re_path(r'^index/$', views.index),
    re_path(r'^login/$', views.login),
    path('publisher_list/', views.publisher_list),
    path('publisher_add/', views.publisher_add),
    re_path('publisher_edit/', views.publisher_edit),
    re_path('publisher_del/', views.publisher_del),
]

views.py(app01)

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

# Create your views here.

# 定義處理用戶請求的函數
def index(request):
    """

    :param request: 所有跟用戶請求相關的數據都封裝到了一個名爲request的對象中
    :return:
    """
    # 拿到用戶請求的方法
    print(request.method)

    # 拿到用戶請求的路徑
    print(request.path_info)

    # 自己打開文件, 然後讀取內容
    # with open('index.html', 'rb') as f:
        # data = f.read()

    # 直接返回字符串
    # return HttpResponse("ok")

    # django 幫我打開文件
    return render(request, "index.html")

# Login
def login(request):
    # 根據用戶請求的方法不同, 做不同的操作
    if request.method == "GET":
        return render(request, "login.html")
        
    else:
    	# 檢查用戶名密碼
        username = request.POST.get("username", "")
        pwd = request.POST.get("password", "")
        if username == "111" and pwd == "111":
            return redirect("/index/")
        else:
            return HttpResponse(404)


# 出版社列表
def publisher_list(request):
    # 查詢出版社數據
    data = models.Publisher.objects.all()
    print(data)
    
    # 展示, "name"和"b"都是測試使用, 在 publisher_list.html 中會有使用方法
    return render(request, "publisher_list.html", {"data": data, "name": "alex", "b": {"k": "v"}})


# 添加出版社
def publisher_add(request):
    if request.method == "GET":
        return render(request, "publisher_add.html")
        
    elif request.method == "POST":
        publisher_name = request.POST.get("publisher_name")
        models.Publisher.objects.create(name=publisher_name)
        return redirect("/publisher_list/")
        
    else:
        return HttpResponse("wrong method")


# 編輯出版社
def publisher_edit(request):
    if request.method == "GET":
        # 獲取 id
        publisher_id = request.GET.get('id')
        # 根據 ID 去查詢出版社信息
        publisher_data = models.Publisher.objects.get(id=publisher_id)
        # 在頁面上展示
        return render(request, "publisher_edit.html", {"data": publisher_data})

    elif request.method == "POST":
        publisher_id = request.POST.get("publisher_id")
        publisher_name = request.POST.get("publisher_name")
        obj = models.Publisher.objects.get(id=publisher_id)
        obj.name = publisher_name
        # 同步到數據庫
        obj.save()
        # 返回頁面
        return redirect("/publisher_list/")

    else:
        return HttpResponse("wrong method")


# 刪除出版社
def publisher_del(request):
    # 取用戶要刪除的那一條數據的 ID
    publisher_id = request.GET.get("id")

    # 使用 ORM 刪除
    models.Publisher.objects.get(id=publisher_id).delete()
	
	# 返回頁面
    return redirect("/publisher_list/")


models.py

from django.db import models

# Create your models here.

# 所有和數據庫 ORM 相關的類都在這個文件中定義, 並且只能在這個文件定義

# 定義一個 出版社 類
class Publisher(models.Model):
    id = models.AutoField(primary_key=True) # 主鍵, 自增
    name = models.CharField(max_length=32) # 字符串長度 32

    def __str__(self): # 默認返回
        return self.name
        

template

publisher_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>出版社列表頁面</title>
</head>
<body>
<h1>出版社列表</h1>

<p><a href="/publisher_add/" methods="get">添加新的出版社</a></p>
<table border="1">
    <thead>
        <tr>
            <th>序號</th>
            <th>出版社 ID</th>
            <th>出版社名稱</th>
            <th>操作</th>
        </tr>
    </thead>
    {# 按照 Django 的特殊語法 寫特殊符號, 替換數據#}
    <tbody>
        {% for obj in data %}
            <tr>
                <td>{{ forloop.counter }}</td>
                <td>{{ obj.id }}</td>
                <td>{{ obj.name }}</td>
                <td><a href="/publisher_edit/?id={{ obj.id }}">編輯</a> <a href="/publisher_del/?id={{ obj.id }}">刪除</a></td>
            </tr>
        {% endfor %}
    </tbody>
</table>

<p>{{ name }}</p>
<p>{{ b.k }}</p>


</body>
</html>

publisher_add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加出版社</title>
</head>
<body>
<form action="/publisher_add/" method="post">
    <input type="text" name="publisher_name">
    <button type="submit">添加</button>
</form>
</body>
</html>

publisher_edit.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>編輯出版社</title>
</head>
<body>
<form action="/publisher_edit/" method="post">
    <input type="text" name="publisher_id" value="{{ data.id }}" style="display: none">
    <input type="text" name="publisher_name" value="{{ data.name }}">
    <button type="submit">提交</button>
</form>
</body>
</html>


總結

orm

# 操作數據表
python manage.py makemigrations
python manage.py migrate

# 操作數據
# 增
model.Publisher.objects.create(name="xxx") # 字段數據要寫全
# 刪
model.Publisher.objects.get(id=1).delete() # 刪除 id 爲 1 的出版社

# 改
obj = models.Publisher.objects.get(id=1)
obj.name = "新值"
obj.save()

# 查
model.Publisher.objects.all() # 查詢所有數據
model.Publisher.objerts.get(id=1) # 查詢 id 爲 1 的數據

django-html

{# django 的特殊語法, 這個是註釋 #}

{# 傳數據和取數據寫法 #}
render(request, "index.html", {"data":data})

render(request, "index.html", {"data":data, "name": "alex"}) # 傳
{{ name }} # 取

render(request, "index.html", {"data":data, "name": "alex", "d":{"key": "hahaha"}})
{{ d.key }}


{# 循環的語法 #}
{% for obj in data %}
	{{ obj.name }}
	{{ obj.id }}
{% endfor %}


{# if 判斷 #}
{% if 條件 %}

{% elif 條件 %}

{% else %}

{% endif %}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章