前端常用词汇(求一箭三联)

基于Wirshark的TCP三次握手介绍2-2

  返回  

45.Django06

2021/8/20 12:31:11 浏览:

文章目录

      • 1.简单的图书管理系统
        • 1.1图书框架
          • 1.Navicat 创建库
          • 1.2创建Django项目
          • 1.3路由层
          • 1.4主页视图
          • 1.5主页HTML
        • 1.2图书的展示
        • 1.3书籍的添加
        • 1.4编辑
        • 1.5删除
      • 2.choices参数
      • 3.MTV模型个MVC模型
      • 4.多对多三种创建方式
        • 1.全自动
        • 2.纯手动
        • 3.半自动

文件地址:
链接:https://pan.baidu.com/s/1dtFp6Y1ght8wma3D96C1jA
提取码:zxn7

1.简单的图书管理系统

1.1图书框架

1.Navicat 创建库
day02 
	utf-8
	确定
1.2创建Django项目
选择自动创建app01
设置settings配置文件
注销掉中间键
 # 'django.middleware.csrf.CsrfViewMiddleware',
修改templates路径
'DIRS': [os.path.join(BASE_DIR, 'templates')],
# 修改mysql库链接
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': '127.0.0.1',
        'POST': 3306,
        'NAME': 'day06',
        'USER': 'root',
        'PASSWORD': '123',
        'CHARSET': 'utf8'
    }
}
# 设置替换数据库,在app应下__init__.py下
import pymysql
pymysql.install_as_MySQLdb()
创建static文件夹将bootstrap-3.3.7-dist复制过来。
# 在model.py中添加表

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    publish_date = models.DateField(auto_now_add=True)
    # 一对多
    publish = models.ForeignKey(to='Publish')
    # 多对多
    author = models.ManyToManyField(to='Author')
    def __str__(self):
        return self.title

class Publish(models.Model):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=64)
    email = models.EmailField()
    # 还是varchar(254) 字段是给models看的,

class Author(models.Model):
    name =models.CharField(max_length=32)
    age = models.IntegerField()
    # 一对一
    author_datail = models.OneToOneField(to="AuthorDateil")

class AuthorDateil(models.Model):
    phone = models.BigIntegerField()
    addr = models.CharField(max_length=64)
# 在终端执行数据库迁移命令
python manage.py makemigrations
python manage.py migrate
自己手动写写数据。
author
idnameageauthor_id
1J神181
2洛书192
3月月签到183
authordetail
idphoneaddr
1110北京
2120上海
3130深圳
publish
idnameemail
1北京出版社110@qq.com
2上海出版社120@qq.com
3深圳出版社130@qq.com
book
idtitlepricepublish_datepublish_id
1开局签到荒古圣体1002021/1/11
2重生之都市仙尊2002021/2/22
3开局签到燕云十八骑3002021/3/33
4开局签到4002021/4/41
book_author
idbook_idauthor_id
111
222
333
441
543
1.3路由层
from django.conf.urls import url
from django.contrib import admin
from app01 import views


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.home, name='home')
]
1.4主页视图
from django.shortcuts import render

def home(request):
    return render(request, 'home.html')
1.5主页HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图书管理系统</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script src="JQuery.js"></script>
    {% block css %}
    
    {% endblock %}
</head>
<body>
<nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">图书管理系统</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">图书 <span class="sr-only">(current)</span></a></li>
        <li><a href="#">作者</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">更多 <span class="caret"></span></a>
          <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>
            <li role="separator" class="divider"></li>
            <li><a href="#">One more separated link</a></li>
          </ul>
        </li>
      </ul>
      <form class="navbar-form navbar-left">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">kid</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">更多操作 <span class="caret"></span></a>
          <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>
        </li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
<div class="container-fluid">
    <div class="row">
         <div class="col-md-3">
            <div class="list-group">
              <a href="#" class="list-group-item active">
                首页
              </a>
              <a href="#" class="list-group-item">图书列表</a>
              <a href="#" class="list-group-item">出版社列表</a>
              <a href="#" class="list-group-item">作者列表</a>
              <a href="#" class="list-group-item">更多</a>
            </div>

        </div>
        <div class="col-md-9">
            <div class="panel panel-primary">
              <div class="panel-heading">
                <h3 class="panel-title">BMS图书管理系统</h3>
              </div>
              <div class="panel-body">
                  {% block centent %}
                      <div class="jumbotron">
                  <h1>欢迎来到亚洲最大的线上读书平台!</h1>
                  <p>你想学习点什么?</p>
                  <p><a class="btn btn-primary btn-lg" href="#" role="button">开始学习!</a></p>
                </div>
                      <div class="row">
                          <div class="col-sm-6 col-md-4">
                            <div class="thumbnail">
                              <img src="https://z3.ax1x.com/2021/08/18/fTQuKs.jpg" alt="...">
                              <div class="caption">
                                <h3>Thumbnail label</h3>
                                <p>...</p>
                                <p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
                              </div>
                            </div>
                          </div>
                          <div class="col-sm-6 col-md-4">
                                <div class="thumbnail">
                                  <img src="https://z3.ax1x.com/2021/08/18/fTQe2Q.jpg" alt="...">
                                  <div class="caption">
                                    <h3>Thumbnail label</h3>
                                    <p>...</p>
                                    <p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
                                  </div>
                                </div>
                              </div>
                          <div class="col-sm-6 col-md-4">
                                <div class="thumbnail">
                                  <img src="https://z3.ax1x.com/2021/08/18/fTQmvj.jpg" alt="...">
                                  <div class="caption">
                                    <h3>Thumbnail label</h3>
                                    <p>...</p>
                                    <p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
                                  </div>
                                </div>
                              </div>
                      </div>
                  {% endblock %}

              </div>
            </div>
        </div>
    </div>
</div>
{% block js %}

{% endblock %}
</body>
</html>

1.2图书的展示

# 路由层添加图书展示
    url(r'^book/list/', views.book_list, name='book_list')
# 视图
def book_list(request):
    # 1. 先查询出所有书籍的信息,传递给html页面
    book_queryset = models.Book.objects.all()

    return render(request, 'book_list.html', locals())
# book_list.html
{% extends 'home.html' %}

{% block centent %}
    <a href="" class="btn btn-success">添加</a>
    <br>
    <table class="table table-hover table-striped">
        <thead>
            <tr>
                <th>ID</th>
                <th>书名</th>
                <th>作者</th>
                <th>价格</th>
                <th>出版社</th>
                <th>出版日期</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {% for book_obj in book_queryset  %}
                <tr>
                    <td>{{ book_obj.pk }}</td>
                    <td>{{ book_obj.title }}</td>
                    <td>
                        {% for authoe_obj in book_obj.author.all %}
                            {% if forloop.last %}
                                {{ authoe_obj.name }}
                             {% else %}
                                {{ authoe_obj.name }},
                            {% endif %}
                        {% endfor %} 
                    </td>
                    
                    <td>{{ book_obj.price}}</td>
                    <td>{{ book_obj.publish.name }}</td>
                    <td>{{ book_obj.publish_date|date:'Y-m-d' }}</td>

                    <td>
                        <a href="" class="btn btn-primary btn-sm">编辑</a>
                        <a href="" class="btn btn-danger btn-sm">删除</a>
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

{% endblock %}
# home.html中将图书列表的点击地址设置下

<a href="{% url 'book_list' %}" class="list-group-item">图书列表</a>

1.3书籍的添加

# 添加路由
    url(r'^book/add/', views.book_add, name='book_add')
# 添加视图函数01
def book_add(request):
    publish_queryeset = models.Publish.objects.all()
    author_queryeset = models.Author.objects.all()
    return render(request, 'book_add.html', locals())
# book_add.html页面
{% extends 'home.html' %}
{% block centent %}
    <h1 class="text-center">书籍的添加</h1>
    <form action="" method="post">
        <p>书名:<input type="text" name="title" class="form-control"></p>
        <p>作者:
            <select name="author" id=""  multiple class="form-control">
                {% for author_obj in author_queryeset %}
                    <option value="{{ author_obj.pk }}">{{ author_obj.name }}</option>
                {% endfor %}
            </select>
        
        </p>
        <p>价格:<input type="text" name="price" class="form-control"></p>
        <p>出版社:
            <select name="publish" id="" class="form-control">
                {% for publish_obj in publish_queryeset %}
                    <option value="{{ publish_obj.pk }}">{{ publish_obj.name }}</option>
                {% endfor %}
            </select>
        
        </p>
        <p>出版日期:<input type="date" name="publish_date" class="form-control"></p>
        <input type="submit" value="新增" class="btn btn-primary btn-block">

    </form>
{% endblock %}
# book_list中的为a便签设置网站网页的跳转
<a href="{% url 'book_add' %}" class="btn btn-success">添加</a>
# 完善视图
from django.shortcuts import  redirect
def book_add(request):
    # 获取当前系统中所有的出版社信息和作者信息
    # 获取前端提交过来的所有数据
    if request.method == 'POST':
        title = request.POST.get('title')
        # 一本书的作者可能有多个
        author_list = request.POST.getlist('author')
        price = request.POST.get('price')
        publish_id = request.POST.get('publish')
        publish_date = request.POST.get('publish_date')

        # 数据库的操作  书  书 与作者
        book_obj = models.Book.objects.create(title=title, price=price, publish_date=publish_date, publish_id=publish_id)
        print(author_list)  # ['1', '3']
        print(book_obj)    # 开局签到世界树1
        # book_obj.author.add(1,3)  # 为开局签到世界树1的书籍绑定一个主键为1和3的作者
        # 为第三张表写数据, 对象套作者id
        book_obj.author.add(*author_list)
        """
        redirect 括号内可以直接写url,也可以写别名
        如果别名需要加额外的参数那么就必须使用reverse解析
        """
        return redirect('book_list')

1.4编辑

# 设置路由
url(r'^book/edit/', views.book_edit, name='book_edit')
# book_edit
{% extends 'home.html' %}
{% block centent %}
    <h1 class="text-center">书籍的编辑</h1>
    <form action="" method="post">
        <p>书名:<input type="text" name="title" class="form-control" value="{{ edit_obj.title }}"></p>
        <p>作者:
            <select name="author" id=""  multiple class="form-control">
                {% for author_obj in author_queryeset %}
                    {% if author_obj in edit_obj.author.all %}
                         <option value="{{ author_obj.pk }}" selected>{{ author_obj.name }}</option>
                    {% else %}
                         <option value="{{ author_obj.pk }}">{{ author_obj.name }}</option>
                    {% endif %} 

                {% endfor %}
            </select>

        </p>
        <p>价格:<input type="text" name="price" class="form-control"  value="{{ edit_obj.price }}"></p>
        <p>出版社:
            <select name="publish" id="" class="form-control">
                {% for publish_obj in publish_queryeset %}
                {#   这里将所有的出版社for遍历出来,当这个值是我们当前需要编辑的出版时将他高亮  #}
                    {% if edit_obj.publish == publish_obj %}
                        <option value="{{ publish_obj.pk }}" selected>{{ publish_obj.name }}</option>
                        {% else %}
                             <option value="{{ publish_obj.pk }}" >{{ publish_obj.name }}</option>
                    {% endif %} 

                {% endfor %}
            </select>


        </p>
        <p>出版日期:<input type="date" name="publish_date" class="form-control"  value="{{ edit_obj.publish_date|date:'Y-m-d' }}"></p>
        <input type="submit" value="提交" class="btn btn-info btn-block">

    </form>
{% endblock %}
# book_list中绑定编辑的页面跳转
<a href="{% url 'book_edit' book_obj.pk %}" class="btn btn-primary btn-sm">编辑</a>
# 视图
def book_edit(request, edit_id):
    edit_obj = models.Book.objects.filter(id=edit_id).first()
    if request.method == 'POST':
        title = request.POST.get('title')
        # 一本书的作者可能有多个
        author_list = request.POST.getlist('author')
        price = request.POST.get('price')
        publish_id = request.POST.get('publish')
        publish_date = request.POST.get('publish_date')
        models.Book.objects.filter(pk=edit_id).update(
            title=title,
            price=price,
            publish_date=publish_date,
            publish_id=publish_id
        )  # set需要的就是一个可迭代对象
        edit_obj.author.set(author_list)
        return redirect('book_list')


    # 获取单前用户想要编辑的数据

    publish_queryeset = models.Publish.objects.all()
    author_queryeset = models.Author.objects.all()
    return render(request, 'book_edit.html', locals())

1.5删除

 # 添加路由
 url(r'^book/delete/(\d+)/', views.book_delete, name='book_delete')
]
# 视图
def book_delete(request, delete_id):
    models.Book.objects.filter(pk=delete_id).delete()
    return redirect('book_list')
# book_list中绑定删除的页面跳转
<a href="{% url 'book_delete' book_obj.pk %}" class="btn btn-danger btn-sm">删除</a>

2.choices参数

存储针对某个可以列举完全可能性字段。
只要某个字段的可能性是可以完全列举完全的,那么一般情况下都会才有choices参数。
新建一个项目,配置好。直接使用自带的库。
# models.py
from django.db import models

# Create your models here.

class User(models.Model):
    username = models.CharField(max_length=32)
    age = models.IntegerField()
    # 性别
    gender_choices = (
        (1, '男'),
        (2, '女'),
        (3, '其他'),
    )
    # 该gender字段存的还是数字。存的数字在上面元组列举的范围之内
    # 那么可以非常轻松的获取到数字对应的真正内容
    gender = models.IntegerField(choices=gender_choices)
执行数据库迁移命令。
在制作一个测试环境。
# test.py
from django.test import TestCase

# Create your tests here.

import os
import sys
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django06_2.settings")
    import django
    django.setup()
	#  在下方测试
    from app01 import models
	# 存
    models.User.objects.create(username='kid1', age=18, gender=1)
    models.User.objects.create(username='kid2', age=19, gender=2)
    models.User.objects.create(username='kid3', age=20, gender=3)
    # 存一个不存在的
    models.User.objects.create(username='kid3', age=20, gender=99)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6MfTXrLY-1629433579841)(https://i.loli.net/2021/08/18/zJZBoXGsxhWdH4K.png)]

    from app01 import models

    user_obj = models.User.objects.filter(pk=1).first()
    print(user_obj)
    print(user_obj.get_gender_display())
    # User object
    # 男
    user_obj = models.User.objects.filter(pk=1).first()
    print(user_obj.get_gender_display())
    # 99
choices 取值搭配固定的语法 get_字段名_display()
如果没有对应关系,如果字段的值是什么就显示生命。
# models.py
class Test(models.Model):
    username = models.CharField(max_length=32)

    report_choices =(
        ('A', '优秀'),
        ('B', '良好'),
        ('C', '及格'),
    )

    # 保证字段类型跟列举出来的元组的第一个数据类型一致即可
    report = models.CharField(report=report_choices)
import os
import sys
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django06_2.settings")
    import django
    django.setup()

    from app01 import models
    test_obj = models.Test.objects.filter(pk=1).first()
    print(test_obj.get_report_display())
    # 优秀
    from app01 import models

    models.Test.objects.create(username='kid1', report='A')
    models.Test.objects.create(username='kid2', report='B')
    models.Test.objects.create(username='kid3', report='C')

3.MTV模型个MVC模型

MTV:Django号称MTV模型
MVC:其实jango本质是MVC模型

M: models
t: templates
v: views
c:controller(urls.py)

# vue模型 MVVM模型

4.多对多三种创建方式

1.全自动

全自动利用orm自动创建第三张光系表
class Book(models.Model):
    name = models.CharField(max_length=32)
    author = models.ManyToManyField(to='Author')
    
class Author(models.Model):
    name = models.CharField(max_length=32)
优点:自动,支持orm操作第三表的方法,add() remove() clear() ···正方向查询···
缺点:第三张拓展性差,没法添加额外的字段。

2.纯手动

class Book(models.Model):
    name = models.CharField(max_length=32)

class Author(models.Model):
    name = models.CharField(max_length=32)

    # 手动创建第三张表
class BookToAuthor(models.Model):
    book_id = models.ForeignKey(to='Book')
    author_id = models.ForeignKey(to='Author')
优点:第三表完全可以自己拓展。
缺点:add() remove() clear() ···正方向查询···不能用。
不建议

3.半自动

through_fields字段先后顺序
判断本质:通过第三张表查询,需要用到哪个字典就将那个字段放在前面,简化判断,当前表示谁就放在前面。
# 通过第三张表查book
class Book(models.Model):
	name = models.CharField(max_length=32)
    author = models.ManyToManyField(to='Author',
                                   through='BookToAuthor',
                                   through=_fields=('book','author'))
   					# through=_fields=('book_id','author_id') _id自动加的

class Author(models.Model):
	name = models.CharField(max_length=32)
    
class BookToAuchor(models.Models):
    book_id = models.ForeignKey(to='Book')
    author_id = models.ForeignKey(to='Author')
    
# 通过第三张表查author
class Book(models.Model):
	name = models.CharField(max_length=32)


class Author(models.Model):
	name = models.CharField(max_length=32)
	    author = models.ManyToManyField(to='Author',
                                   through='BookToAuthor',
                                   through=_fields=('author','book'))
class BookToAuchor(models.Models):
    book_id = models.ForeignKey(to='Book')
    author_id = models.ForeignKey(to='Author')
可是使用 正方向查询,不能使用:add() remove() clear() ···
拓展性高

联系我们

如果您对我们的服务有兴趣,请及时和我们联系!

服务热线:18288888888
座机:18288888888
传真:
邮箱:888888@qq.com
地址:郑州市文化路红专路93号