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 %}

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