书籍管理系统 -----没有form组件

urls:

from django.contrib import admin
from django.urls import path,re_path
from first import views
urlpatterns = [
    path(‘admin/‘, admin.site.urls),
    path(‘index/‘,views.index,  name=‘index‘),  #显示的主界面
    # path(‘one/‘,views.one)
    path(‘add/‘,views.add,name=‘add‘),  #添加界面
    # re_path(‘del_me/(?P<id>\d+)‘,views.del_message,name = ‘edit_book‘),
    re_path(‘del_book/‘,views.del_message,name=‘d_book‘),   #删除
    re_path(‘edit_book/(\d+)/‘,views.edit_book,name =‘edit_book‘),  #编辑
    re_path(‘login/‘,views.login,name=‘login‘),  #登陆
    path(‘logout/‘,views.logout, name=‘logout‘),  #注销
]

urls

views:

from django.shortcuts import render,redirect,HttpResponse,reverse
from first.models import Book,Publish,Author,Gfriend,User
import json
import datetime
# Create your views here.

# 等一一个装饰器来验证是否可以登陆后进行操作

def required_login(func):
    def inner(*args, **kwargs):
        request = args[0]  # 因为你的参数实在args内 所以你的接收的内容也是args
        if request.COOKIES.get(‘is_login‘):
            return func(*args, **kwargs)

        else:
            return redirect(reverse(‘login‘))

    return inner

@required_login

def index(request):
    book_obj = Book.objects.all()
    author_obj = Author.objects.all()
    publish_obj = Publish.objects.all()
    # book_author = Book.authors.all()

    # print(book_obj)
    # print(1111)
    return render(request, ‘index.html‘,locals())

@required_login
def add(request):
    author_obj = Author.objects.all()
    publish_obj = Publish.objects.all()
    if request.method =="POST":
        name = request.POST.get(‘name‘)
        price = request.POST.get(‘price‘)
        dat = request.POST.get(‘datetime‘)
        publish = request.POST.get(‘publish‘)
        author_list =request.POST.getlist(‘authors‘)  #获取的作者是多个就需要用getlist来获取
        print(author_list)
        book = Book.objects.create(name = name,price = price,date = dat,publish_id = publish )
        # book.publish_id.add(publish)
        book.authors.set(author_list)  #用set依次添加
        return redirect(‘/index/‘)
    # ut = reverse(‘add‘)
    return render(request,‘add.html‘,locals())

@required_login
def del_message(request):
    del_id = request.POST.get(‘del_id‘)
    # Book.objects.filter(id = del_id).delete()

    del_book = Book.objects.filter(id = del_id)
    # print(del_book)
    del_book.delete()
    # return redirect(‘/index/‘
    #删除成功过后你需要进行发送一个信息  不能重定向了 因为用的是ajax局部刷新的
    return HttpResponse(json.dumps({‘status‘:1}))  #返送一个序列化字符串

@required_login
def edit_book(request,edid):
    book_obj = Book.objects.get(id = edid)
    author_obj = Author.objects.all()
    publish_obj = Publish.objects.all()

    if request.method == ‘POST‘:
        name = request.POST.get(‘name‘)
        price = request.POST.get(‘price‘)  #get这个值是获取你前端界面的name的属性  value的属性是显示的属性
        date = request.POST.get(‘datetime‘)
        publish = request.POST.get(‘publish‘)
        authors = request.POST.getlist(‘authors‘)
        book_obj.name = name
        book_obj.price = price
        book_obj.date = date
        book_obj.publish_id = publish
        book_obj.authors.set(authors)
        book_obj.save()
        return redirect(‘/index/‘)
    return render(request,‘edit_book.html‘,locals())

# @required_login
def login(request):
    if request.method == ‘POST‘:
        name = request.POST.get(‘user‘)
        pwd = request.POST.get(‘pwd‘)
        user_obj = User.objects.filter(name = name,pwd=pwd)
        print(user_obj)
        user_obj = user_obj.first()   #因为你取到的user_obj是一个queryset所以你要进行取到第一个是对象

        if user_obj: #登陆成功
            # 然后用cookie
            ret  = redirect(reverse(‘index‘))  #登陆成功后跳转到index界面 这个用的反向解析

            ret.set_cookie(‘name‘,name)
            ret.set_cookie(‘pwd‘,pwd)
            ret.set_cookie(‘is_login‘,True)
            #然后你求登陆时间  选哟调用你你数据库中的上一次登陆成功后存储的时间
            ret.set_cookie(‘last_time‘,user_obj.date)
            user_obj.date = datetime.datetime.now()  #把你这一次登陆的时间再设置回数据库
            user_obj.save()
            return ret
    return render(request,‘login.html‘)

@required_login
def logout(request):
    ret = redirect(reverse(‘login‘))  #退还到你的登陆框
    ret.delete_cookie(‘is_login‘)
    ret.delete_cookie(‘user‘)
    ret.delete_cookie(‘last_time‘)
    return ret

views

models:(数据库):

from django.db import models

# Create your models here.

class Book(models.Model):
    name = models.CharField(max_length = 30)
    price = models.DecimalField(max_digits=30,decimal_places=3)
    date = models.DateTimeField()
    publish = models.ForeignKey(to="Publish",to_field=‘id‘,on_delete = models.CASCADE)
    authors = models.ManyToManyField(to=‘Author‘)

class Publish(models.Model):
    title = models.CharField(max_length = 30)
    addr = models.CharField(max_length = 30)

class Author(models.Model):
    name = models.CharField(max_length = 30)
    addr = models.CharField(max_length = 30)
    gf = models.OneToOneField(to=‘Gfriend‘,to_field=‘id‘,on_delete=models.CASCADE)

class Gfriend(models.Model):
    name = models.CharField(max_length =30)
    age = models.IntegerField()

class User(models.Model):
    name = models.CharField(max_length = 30)
    pwd = models.IntegerField()
    date = models.DateTimeField()

models

template:(前端界面)

index(显示的主界面):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">

</head>
<body>

<div class="bs-example " data-example-id="inverted-navbar ">
    <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-9" 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 pull-right" id="bs-example-navbar-collapse-9">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#">{{ request.COOKIES.name }}</a></li>
                    <li><a href="#">{{ request.COOKIES.last_time}}</a></li>
                    <li class =‘btn-primary‘><a href="{% url ‘logout‘ %}">注销</a></li>
                </ul>
            </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
    </nav>
</div>

<table class="table table-hover">
    <thead>
    <a href="{% url ‘add‘ %}" class="btn btn-primary ">添加</a>
    <tr>
        <th>序号</th>
        <th>名字</th>
        <th>价格</th>
        <th>出版日期</th>
        <th>出版社</th>
        <th>作者</th>
        <th>操作</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    {% for foo in book_obj %}
        <tr>
            <th scope="row">{{ forloop.counter }}</th>
            {#            {{ forloop.count 是自动为它排序的 }}#}
            <td>{{ foo.name }}</td>
            <td>{{ foo.price }}</td>
            <td>{{ foo.date|date:‘Y-m-d‘ }}</td>
            <td>{{ foo.publish.title }}</td>
            <td>
                {% for i in foo.authors.all %}
                    {#                {% for i in book_author %}#}

                    {% if not forloop.last %}
                        {{ i.name }}{{ ‘|‘ }}
                    {% else %}
                        {{ i.name }}
                    {% endif %}
                {% endfor %}
            </td>
            <td><a href="{% url ‘edit_book‘ foo.id %}" class="tianjia btn btn-warning">编辑</a></td>
            <td><a class="delet btn btn-danger" edit_id="{{ foo.id }}">删除</a></td>
        </tr>
    {% endfor %}
    </tbody>
</table>

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>

{% csrf_token %}
<script>
    $(‘.btn-danger‘).click(function () {
        _this = $(this)
        {#alert(_this.attr(‘edit_id‘));#}
        $.ajax({
            url:{% url ‘d_book‘ %},
            type: ‘post‘,
            data: {
                del_id: _this.attr(‘edit_id‘),
                csrfmiddlewaretoken: $("[name=‘csrfmiddlewaretoken‘]").val()
            },
            success: function (data) {
                console.log(data);
                var data = JSON.parse(data);
                {#    把接收过来的信息反序列化#}
                if (data.status) {
                    _this.parent().parent().remove()
                }

            }
        })
    })

</script>

</body>
</html>

index

add(添加书籍):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
    <style>
        .conten {
            margin-top: 50px;
        }
    </style>
</head>
<body>
<div class="conten">
    <div>
        <div class="container">
            <div class="bs-example" data-example-id="form-validation-states">

                <form method="post" action="{% url ‘add‘ %}">

                    {% csrf_token %}
                    <div class="form-group has-success">

                        <label class="control-label" for="control-label">书籍名称</label>
                        <input type="text" class="form-control" id="control-label" aria-describedby="helpBlock2"
                               name="name">
                    </div>
                    <div class="form-group has-warning">
                        <label class="control-label" for="inputWarning">价格</label>
                        <input type="text" class="form-control" id="inputWarning" name="price">
                    </div>
                    <div class="form-group has-error">
                        <label class="control-label" for="inputError1">出版日期</label>
                        <input type="date" class="form-control" id="inputError1" name="datetime">
                    </div>
                    <div class="form-group has-warning">
                        <label class="control-label" for="inputWarning1">出版社</label>
                        {#        <input type="text" class="form-control" id="inputWarning1" name="publish">#}
                        <select name="publish" id="inputWarning1" class=" form-control">
                            {% for foo in publish_obj %}
                                <option value="{{ foo.id }}">{{ foo.title }}</option>
                            {% endfor %}

                        </select>
                    </div>

                    <div class="form-group has-success">
                        <label class="control-label" for="inputSuccess1">作者</label>
                        {#        <input type="text" class="form-control" id="inputSuccess1" aria-describedby="helpBlock2" name="authors" multiple>#}
                        <select name="authors" id="inputSuccess1" class="form-control" multiple>
                            {% for f in author_obj %}
                                <option value="{{ f.id }}">{{ f.name }}</option>
                            {% endfor %}
                        </select>
                    </div>

                    <input type="submit" value="提交"/>

                </form>
            </div>
        </div>
    </div>
</div>

</body>
</html>

add

编辑:(edit_book)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
    <style>
        .conten {
            margin-top: 50px;
        }
    </style>
</head>
<body>
<div class="conten">
    <div>
        <div class="container">
            <div class="bs-example" data-example-id="form-validation-states">

                <form method="post" action="">

                    {% csrf_token %}
                    <div class="form-group has-success">

                        <label class="control-label" for="control-label">书籍名称</label>
                        <input type="text" class="form-control" id="control-label" aria-describedby="helpBlock2"
                               name="name" value={{ book_obj.name }}>
                    </div>
                    <div class="form-group has-warning">
                        <label class="control-label" for="inputWarning">价格</label>
                        <input type="text" class="form-control" id="inputWarning" name="price" value ={{ book_obj.price }}>
                    </div>
                    <div class="form-group has-error">
                        <label class="control-label" for="inputError1">出版日期</label>
                        <input type="date" class="form-control" id="inputError1" name="datetime" value={{ book_obj.date|date:‘Y-m-d‘ }}>
                    </div>
                    <div class="form-group has-warning">
                        <label class="control-label" for="inputWarning1">出版社</label>
                        {#        <input type="text" class="form-control" id="inputWarning1" name="publish">#}
                        <select name="publish" id="inputWarning1" class=" form-control">
                            {% for foo in publish_obj %}
                                {{% if book_obj.publish == foo %}
                                    <option value="{{ foo.id }}" selected>{{ foo.title }}</option>
                                {% else %}
                                    <option value="{{ foo.id }}">{{ foo.title }}</option>

                                {% endif %}}
{#                                <option value="{{ foo.id }}">{{ foo.title }}</option>#}
                            {% endfor %}

                        </select>
                    </div>

                    <div class="form-group has-success">
                        <label class="control-label" for="inputSuccess1">作者</label>
                        {#        <input type="text" class="form-control" id="inputSuccess1" aria-describedby="helpBlock2" name="authors" multiple>#}
                        <select name="authors" id="inputSuccess1" class="form-control" multiple>
                            {% for f in author_obj %}
                                {% if f in book_obj.authors.all %}
                                     <option value="{{ f.id }}" selected>{{ f.name }}</option>
{#                                    selected是默认选中的意思#}
                                 {% else %}
                                     <option value="{{ f.id }}">{{ f.name }}</option>

                                {% endif %}
{#                                <option value="{{ f.id }}">{{ f.name }}</option>#}
                            {% endfor %}
                        </select>
                    </div>

                    <input type="submit" value="提交"/>

                </form>
            </div>
        </div>
    </div>
</div>

</body>
</html>

edit_book

登陆界面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">

    <style>
      body {
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: #eee;
}

.form-signin {
  max-width: 330px;
  padding: 15px;
  margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
  margin-bottom: 10px;
}
.form-signin .checkbox {
  font-weight: normal;
}
.form-signin .form-control {
  position: relative;
  height: auto;
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
  padding: 10px;
  font-size: 16px;
}
.form-signin .form-control:focus {
  z-index: 2;
}
.form-signin input[type="email"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}

    </style>
</head>
<body>

    <div class="container">

      <form class="form-signin" action="{% url ‘login‘ %}" method="post">
          {% csrf_token %}
        <h2 class="form-signin-heading">Please 登陆</h2>
        <label for="inputEmail" class="sr-only">Email address</label>
        <input type="text" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="" name="user">
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" id="inputPassword" class="form-control" placeholder="Password" required="" name="pwd">
        <div class="checkbox">
          <label>
            <input type="checkbox" value="remember-me"> Remember me
          </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
      </form>

    </div> <!-- /container -->

    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
{#    <script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>#}

</body>
</html>

login

记得不要忘记配置static你所引入的前端样式  还有settings内的数据库配置:

settings:

配置数据库:

DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.mysql‘,
        ‘NAME‘:‘test‘,  # 要连接的数据库,连接前需要创建好
        ‘USER‘:‘root‘, # 连接数据库的用户名
        ‘PASSWORD‘:‘zhaoyun‘,  # 连接数据库的密码
        ‘HOST‘:‘127.0.0.1‘,       # 连接主机,默认本级
        ‘PORT‘:3306    #  端口 默认3306
    }
}

配置static:

STATICFILES = [
    os.path.join(BASE_DIR,‘static‘)
]

原文地址:https://www.cnblogs.com/askzyl/p/9278398.html

时间: 2024-10-01 13:08:16

书籍管理系统 -----没有form组件的相关文章

学生管理系统(用中间件)-------基于FORM组件

x学生管理系统(用中间件)-------基于FORM组件 目的:实现学生,老师,课程的增删改查 models.py from django.db import models # Create your models here. class UserInfo(models.Model): """ 用户表:既有班主任也有老师 """ username = models.CharField(max_length=32) password = model

jsp-servlet(2)响应HTML文档-书籍管理系统

基础知识预备:  目标: 构建一个书籍管理系统,并且部署到GitHub上. 功能: 1 安全注册登录系统 2 图书信息查询,(查) 3 书籍管理:入库.出库(增删改) 4 安全退出系统 一.预备工作 Book{ Id, Name, Price, Author, Pubdate, } 建表: CREATE TABLE `book` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) CHARACTER SET utf8 COLLAT

Python Django 多对多三种创建方式 form组件 cookie和session

一 表中多对多关系三种创建方式 以Book表和Author表多对多关系例 1.第一种方式:全自动(推荐使用):models.ManyToManyField(to='类名') 优点:不需要你手动创建第三张表 缺点:第三张表不是你手动创建的,字段是固定的无法拓展 class Book(models.Model): title = models.CharField(max_length=32) price = models.DecimalField(max_digits=8,decimal_place

Django【十三】form组件。

一.form组件 form组件的功能: 检验功能 前端生成HTML页面 还能保留输入的内容 form组件的用法: from django import forms # Create your views here. # 定义一个类 class Myform(forms.Form): title = forms.CharField( # 通过from表单进行验证的时候,验证输入title字段的数据,参数用于验证 max_length=20, min_length=2, ) # CharField/

原生Form 和 Form组件 Modelform

主要的文件:manage.py,url.py,views.py,settings.py,models.py manage.py:项目管理文件,一般不做修改. url.py:路由系统,配置views.py中函数和对应路径的关系. views.py:添加视图函数,常见的增删查改函数. settings.py:模板配置文件,对TEMPLATES .DATABASES.STATIC_URL 等进行配置. models.py:数据库相关表的类描述. Django基础必备三件套:HttpResponse,

分页器组件与form组件

批量插入数据 bulk_create # 1.往书籍表中插入数据 1000 # for i in range(1000): # 这种插入方式 效率极低 # models.Book.objects.create(title='第%s本书'%i) book_list = [] for i in range(100000): # 时间还是很短 两者差距很大 book_list.append(models.Book(title='第%s本书'%i)) models.Book.objects.bulk_c

Django—分页器与form组件

目录 分页器 现成分页器代码 如何使用 后端 前端 form组件 form 校验组件 使用校验组件与钩子函数 三种渲染方式 正则校验* 分页器 现成分页器代码 只需要会使用即可. 在Django项目下新建utils文件夹,新建一个py文件,放入封装好的分页器代码. class Pagination(object): def __init__(self, current_page, all_count, per_page_num=10, pager_count=11): """

Django 批量插入数据、自定义分页器、多表关系的建立及Form组件(待更新。。。)

目  录 django批量出入数据 自定义分页器 创建多对多表关系的建立 form组件 form组件钩子函数 一.django批量出入数据 视图函数: from app01 import models # 向表中插入1000条数据 def index(request): # 方式1: # for i in range(1000): # models.Book.objects.create(title='第%s本书'%i) # book_Queryset = models.Book.objects

Django框架之Form组件

新手上路 From组件的主要功能: 1,对form表单提交的数据进行校验. 内部基于正则进行匹配 2,from表单提交保存上次提交的数据. 生成HTML标签 初入大荒 1,创建Form类 class StudentForm(Form): #字段名,最好跟数据库内的字段名一样,好操作 #如CharField,内部包含了正则表达式, name = fields.CharField(max_length=12, min_length=2, required=True, widget=widgets.T