Python django之搭建简单图书管理系统

1 创建项目

# 使用的django版本为2.1.2
django-admin startproject bookms

2 创建APP

cd bookms
python3 manage.py startapp app01

3 设置setting.py文件

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'bookms.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

# mysql数据库需要自己定义
DATABASES = {
    'default':
    {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'bookms',		# 数据库的名字
        'USER': 'root',		        # 登录数据库的用户名
        'PASSWORD': '123456',	    # 登录数据库的密码
        'HOST': '127.0.0.1',	    # 数据库的IP地址
        'PORT': '3306',		        # 数据库的端口
    }
}

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

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        },
    }
}

4 bookms/urls.py配置

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('addbook/', views.addbook),
    path('selectbook/', views.selectbook),
    re_path('books/(\d+)/delete/', views.delbook),
    re_path('books/(\d+)/change/', views.changebook),
]

5 app01/model.py配置(orm模型)

from django.db import models


class Book(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32,unique=True)
    # state = models.BooleanField()
    pub_date = models.DateField()
    price = models.DecimalField(max_digits=8,decimal_places=2)  # 最大值为999999.99 总共8个数字,其中包含小数点有两个
    publish = models.CharField(max_length=32)

6 app01/views.py 视图函数

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


def addbook(request):
    print(Book)
    if request.method.lower() == 'post':
        title = request.POST.get('title')
        price = request.POST.get('price')
        pub_date = request.POST.get('pub_date')
        publish = request.POST.get('publish')

        Book.objects.create(title=title,price=price,pub_date=pub_date,publish=publish)
        return redirect('/selectbook/')
        # return HttpResponse('{}-{}-{}-{}'.format(title,price,pub_date,publish))

    return render(request,'addbook.html')


def selectbook(request):
    book_list = Book.objects.all()
    return render(request,'selectbook.html',locals())


def delbook(request,id):

    Book.objects.filter(id=id).delete()
    return redirect('/selectbook/')


def changebook(request,id):
    book_obj = Book.objects.filter(id=id).first()

    if request.method.lower() == 'post':
        title = request.POST.get('title')
        price = request.POST.get('price')
        pub_date = request.POST.get('pub_date')
        publish = request.POST.get('publish')

        Book.objects.filter(id=id).update(title=title,price=price,pub_date=pub_date,publish=publish)
        return redirect('/selectbook/')

    return render(request,'changebook.html',locals())


# Create your views here.

7 templates/addbook.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bs/css/bootstrap.css">
<!--    <link rel="stylesheet" href="/static/bs/css/bootstrap.min.css">-->
<!--    <link href="https://cdn.bootcss.com/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">-->
    <style>
        .container{
            margin-top:100px;
        }
        .btn{
           margin-top:10px;
        }
    </style>
</head>
<body>

<center> <h3>添加书籍页面</h3> </center>

<center>
<div class="container">
    <div class="row">
        <div class="col-md-3 col-md-offset-7">
            <form action="/addbook/" method="post">
                {% csrf_token %}

                <div>
                    <label for="">书籍名称</label>
                    <input type="text" class="form-control" name="title">
                </div>
                <div>
                    <label for="">价格</label>
                    <input type="text" class="form-control" name="price">
                </div>
                <div>
                    <label for="">出版日期</label>
                    <input type="date" class="form-control" name="pub_date">
                </div>
                <div>
                    <label for="">出版社</label>
                    <input type="text" class="form-control" name="publish">
                </div>

                <input type="submit" class="btn btn-success pull-right">

            </form>
        </div>
    </div>
</div>
    <a href="/selectbook/" class="btn btn-primary">查询书籍页面</a>
</center>
</body>
</html>

8 templates/changebook.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bs/css/bootstrap.css">
<!--    <link rel="stylesheet" href="/static/bs/css/bootstrap.min.css">-->
<!--    <link href="https://cdn.bootcss.com/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">-->
    <style>
        .container{
            margin-top:100px;
        }
        .btn{
           margin-top:10px;
        }
    </style>
</head>
<body>

<center> <h3>编辑书籍页面</h3> </center>

<center>
<div class="container">
    <div class="row">
        <div class="col-md-3 col-md-offset-7">
            <form action="" method="post">
                {% csrf_token %}

                <div>
                    <label for="">书籍名称</label>
                    <input type="text" class="form-control" name="title" value="{{ book_obj.title }}">
                </div>
                <div>
                    <label for="">价格</label>
                    <input type="text" class="form-control" name="price" value="{{ book_obj.price }}">
                </div>
                <div>
                    <label for="">出版日期</label>
                    <input type="date" class="form-control" name="pub_date" value="{{ book_obj.pub_date|date:'Y-m-d' }}">
                </div>
                <div>
                    <label for="">出版社</label>
                    <input type="text" class="form-control" name="publish" value="{{ book_obj.publish }}">
                </div>

                <input type="submit" class="btn btn-success pull-right">

            </form>
        </div>
    </div>
</div>
    <a href="/selectbook/" class="btn btn-primary">查询书籍页面</a>
</center>
</body>
</html>

9 templates/selectbook.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bs/css/bootstrap.css">
    <link rel="stylesheet" href="/static/bs/css/bootstrap.min.css">
    <link href="https://cdn.bootcss.com/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .container{
            margin-top:100px;
        }
        .btn{
           margin-top:10px;
        }
    </style>
</head>
<body>

<center> <h3>查看书籍页面</h3> </center>

<center>
<div class="container">
    <div class="row">
        <div class="col-md-3 col-md-offset-7">
            <table class="table table-striped table-bordered">
              <thead>
                <tr>
                  <th>书籍名称</th>
                  <th>价格</th>
                  <th>出版日期</th>
                  <th>出版社</th>
                  <th>删除操作</th>
                  <th>编辑操作</th>
                </tr>
              </thead>
              <tbody>
              {% for book in book_list %}
                <tr>
                  <td>{{ book.title }}</td>
                  <td>{{ book.price }}</td>
                  <td>{{ book.pub_date|date:'Y-m-d' }}</td>
                  <td>{{ book.publish }}</td>
<!--                  <td> <a href="/books/{{ book.id }}/delete/" class="btn btn-danger">删除 </a> </td>-->
                  <td> <a href="/books/{{ book.pk }}/delete/" class="btn btn-danger">删除 </a> </td>
<!--                    book.pk为主键删除-->
                  <td> <a href="/books/{{ book.pk }}/change/" class="btn btn-info">编辑</a>   </td>

                </tr>
              {% endfor %}
              </tbody>
            </table>
        </div>
    </div>
</div>
    <a href="/addbook/" class="btn btn-primary">返回添加页面</a>
</center>
</body>
</html>

10 数据库迁移

python3 manage.py makemigrations  # 默认所有修改过的model层转为迁移文件

11 更新数据库

python3 manage.py migrate   # 默认将所有的迁移文件都执行,更新数据库

12 静态文件:bootstrap目录

下载连接:http://getbootstrap.com/2.3.2/assets/bootstrap.zip
项目根路径:bookms/static/

目录结构为
[root@a37a35a64335 bookms]# tree
.
`-- static
    `-- bs
        |-- css
        |-- img
        `-- js

13 运行项目

python3 manage.py runserver 0.0.0.0:8000
  • 3
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值