图书管理系统 基于form组件

 

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()
    email = models.EmailField()
models

 

settings配置:

配置数据库

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









配置静态文件



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

 

 

 

init:

import pymysql
pymysql.install_as_MySQLdb()

 

 

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('add_book/',views.add_book,name='add_book'),

    re_path('del_book/',views.del_book ,name='del_book'),

    re_path('edit_book/(\d+)/',views.edit_book,name = 'edit_book'),


    path('login/',views.login_session,name='login'),

    path('logout/',views.logout,name = 'logout'),
    path('register/',views.register, name = 'register'),
    path('hint/',views.hint,name = 'hint') #这个是你的 跳转注册的界面


]
urls

 

views:

from django.shortcuts import render,redirect,reverse,HttpResponse
import json,datetime

from first.models import Book,Author,Publish,User

from first .form import U_ser
# Create your views here.

#定义一个装饰器  然后所有的 函数都用装饰器进行封装
def wrapper(func):
    def inner(*args,**kwargs):
        request = args[0]
        # if request.COOKIES.get('is_login'):
        if request.session.get('is_login'):

            return func(*args,**kwargs)
        else:
            return redirect(reverse('login'))

    return inner



#登陆函数  cookie
# def login(request):
#     print('11111111111111111')
#     if request.method == 'POST':
#         name = request.POST.get('user')
#         pwd = request.POST.get('pwd')
#         print(name,pwd)
#         log_obj = User.objects.filter(name = name ,pwd=pwd).first()
#         if log_obj:  #登陆成功
#             ret = redirect(reverse('index'))
#             ret.set_cookie('name',name)
#             ret.set_cookie('pwd',pwd)
#             ret.set_cookie('is_login',True)
#             ret.set_cookie('last_time',log_obj.date)
#             log_obj.date = datetime.datetime.now()
#             log_obj.save()
#
#             return ret
#     # return redirect(reverse('login'))
#     return render(request,'login.html')


@wrapper
#主界面
def index(request):
    book_list = Book.objects.all()
    publish_list = Publish.objects.all()
    author_list = Author.objects.all()


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

@wrapper
def add_book(request):
    '''
    这是对书籍的信息进行增加的函数
    :param request:
    :return:
    '''
    book_list = Book.objects.all()
    publish_list = Publish.objects.all()
    author_list = Author.objects.all()

    if request.method == 'POST':
        name = request.POST.get('name')
        price = request.POST.get('price')
        date = request.POST.get('date')
        publish = request.POST.get('publish')
        author = request.POST.getlist('author')
        print(author)
        book = Book.objects.create(name = name,price = price, date = date ,publish_id=publish)
        book .authors.set(author)  #给你的这个书籍对象 添加作者

        return redirect(reverse('index'))  #添加完之后就重新定向到主界面

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


@wrapper
def del_book(request):  #删除函数
    deid = request.POST.get('deid')
    print(deid)
    del_book = Book.objects.filter(id = deid)  #获取你前端点击的那个id的书籍对象
    del_book.delete()
    print(111*100)
    return HttpResponse(json.dumps({'status':1}))

@wrapper
def edit_book(request ,edid):
    # print('___________________________')
    book_list = Book.objects.filter(id=edid).first()
    publish_list = Publish.objects.all()
    author_list = Author.objects.all()
    print(book_list)
    print(6666666666666)
    if request.method =='POST':
        print(2222222222)

        name = request.POST.get('name')
        price = request.POST.get('price')
        date = request.POST.get('date')
        publish = request.POST.get('publish')
        author = request.POST.getlist('author')
        # bk_bj =Book.objects.filter(id=edid).update(name=name, price=price, date=date, publish=publish)
        # bk_bj.author.set(author)
        print(3333333333333)
        book_list.name = name
        book_list.price = price
        book_list.publish_id = publish
        book_list.authors.set(author)
        book_list.save()
        return redirect(reverse('index'))
    print(55555555555555)
    return render(request,'edit_book.html',locals())


@wrapper
def logout(request): #注销
    ret = redirect(reverse('login'))
    # ret.delete_cookie('name')
    # ret.set_cookie('last_time')
    # ret.delete_cookie('pwd')
    request.session.flush()
    return ret






#这个使用session
def login_session(request):
    print(request.POST)
    if request.method == 'POST':
        name = request.POST.get('user','')

        pwd = request.POST.get('pwd','')

        user_obj = User.objects.filter(name=name ,pwd =pwd).first()

        if user_obj:
            ret = redirect(reverse('index'))
            request.session['is_login'] = True
            request.session['name'] = name
            request.session['pwd'] = pwd
            request.session['last_time'] = str(user_obj.date)  # 你去出的是一个date兑现 但是要存起来就要用 str
            user_obj.date = datetime.datetime.now()
            user_obj.save()
            return ret
        # else:  #这一步是你输入的账号和密码不对的时候
            # return HttpResponse('您输入用户名不对')
        return redirect(reverse('hint'))
    return render(request,'login.html')




#定义一个注册用户的函数
def register(request):

    if request.method == 'POST':

        form = U_ser(request.POST)  #把前端的信息和form组件对比判断
        if form.is_valid():#正确
            name = request.POST.get('name')
            pwd = request.POST.get('pwd')
            date = request.POST.get('date')
            email = request.POST.get('email')
            User.objects.create(name = name ,pwd = pwd,date = date,email = email)

            return redirect(reverse('login'))  #注册成功就去登陆界面
        else:

            g_error = form.errors.get('__all__')  #获取所有的错误
            if g_error:
                g_error = g_error[0]
            print(locals())
            return render(request,'register.html',locals())

    form = U_ser()
    print(55555555555555)
    return render(request,'register.html',locals())



def hint(request):
    return render(request,'hint.html')
views

 

 

templates:

 

登陆界面:login

<!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' novalidate>
          {% csrf_token %}
        <h2 class="form-signin-heading">Please </h2>
        <label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" 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>
{#          <button class="btn btn-lg btn-info btn-block" type="submit">Register</button>#}
          <a href="{% url 'register' %}" class="btn btn-lg btn-info btn-block" >Register</a>
      </form>

    </div>

</body>
</html>
login

 

注册:register

<!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>
        .container {
            margin-top: 80px;

        }

        {#body {#}
        {#    background-color: darkslategray;#}
        .nide{
            margin-top: 10px;
        }
    </style>
</head>
<body>


{#<div class="container col-md-3 col-md-offset-4">#}
{#    <div>#}
{#        <div>#}
{#            <div class="bs-example" data-example-id="form-validation-states">#}
{#    <form>#}
{#      <div class="form-group has-success">#}
{#        <label class="control-label" for="inputSuccess1">请输入用户名</label>#}
{#        <input type="text" class="form-control" id="inputSuccess1" aria-describedby="helpBlock2">#}
{##}
{#      </div>#}
{#      <div class="form-group has-warning">#}
{#        <label class="control-label" for="inputWarning1">请输入密码</label>#}
{#        <input type="text" class="form-control" id="inputWarning1">#}
{#      </div>#}
{#      <div class="form-group has-error">#}
{#        <label class="control-label" for="inputError1">请确认密码</label>#}
{#        <input type="text" class="form-control" id="inputError1">#}
{#      </div>#}
{#        <div class="has-warning form-group">#}
{#            <input type="submit" value="提交" class="btn btn-info pull-right">#}
{##}
{#        </div>#}
{##}
{##}
{##}
{#    </form>#}
{#  </div>#}
{#        </div>#}
{#    </div>#}
{#</div>#}


<div class="container col-md-5 col-md-offset-3">
    <div >
        <div>
            <form action="" method='post' novalidate>
                {% csrf_token %}

                {% for foo in form %}
{#                    循环你的 报错的信息#}
                    <div class="form-group">
                        <label for="">{{ foo.label }}</label>
                        {{ foo }}
                        <span class="pull-right">{{ foo.errors.0 }}</span>
                        {% if foo.label == 'R pwd' %}
                            <span class="pull-right">{{ g_error|default_if_none:'' }}</span>
                        {% endif %}


                    </div>

                {% endfor %}

                <div class="nide">
                    <input type="submit" value = '提交' class="pull-right btn btn-info">
                </div>

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

</body>
</html>
注册

 

主界面: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" id="bs-example-navbar-collapse-9">
          <ul class="nav navbar-nav pull-right" >
{#            <li class="active"><a href="#">{{ request.COOKIES.name }}</a></li>#}
{#            <li><a href="#">{{ request.COOKIES.last_time }}</a></li>#}
              <li class="active"><a href="#">{{ request.session.name }}</a></li>
            <li><a href="#">{{ request.session.last_time }}</a></li>
            <li><a href="{% url 'logout' %}">注销</a></li>
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>
  </div>






<div class="bs-example" data-example-id="contextual-table">

    <a href="{% url 'add_book' %}" class="btn btn-info pull-right">添加书籍</a>
    <table class="table">
      <thead>

        <tr>
          <th >序号</th>
          <th class="info">名字</th>
          <th>价格</th>
          <th class="warning">出版时间</th>
            <th>出版社</th>
            <th class="success">作者</th>
            <th>操作</th>
            <th>操作</th>
        </tr>
      </thead>

      <tbody>
       {% for book in book_list %}

        <tr class="active">
          <th scope="row">{{ forloop.counter }}</th>
          <td class="info">{{ book.name }}</td>
          <td class="danger">{{book.price}}</td>
          <td class="success">{{ book.date|date:'Y-m-d' }}</td>
        <td class="active"> {{ book.publish.title }}</td>
        <td class="warning">
            {% for author  in book.authors.all %}
                {% if not forloop.last %}
                    {{ author.name }}{{ '|' }}
                {% else %}
                    {{ author.name }}
                {% endif %}
            {% endfor %}

        </td>
           <td><a href="{% url 'edit_book' book.id %}" class="danger  btn btn-info">编辑</a></td>

        <td><a  edid = '{{ book.id }}' class='  btn btn-danger'>删除</a></td>
{#        让这个删除按钮获取要删除的书籍id#}

        </tr>

      </tbody>

        {% endfor %}
    </table>
  </div>
{% csrf_token %}
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    $('.btn-danger').click(function(){
        _this = $(this);
        console.log(111,_this)
        $.ajax({
            url:{% url 'del_book' %},
            type:'post',
            data:{
                deid:_this.attr('edid'),
                {#当你点击的时候获取你点击的那个对象的id传送到后台#}
            csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val()
            },
            success: function (data){
                var data = JSON.parse(data);
                if(data.status){
                    _this.parent().parent().remove()
                }
            }
        })
    })
</script>


</body>
</html>
index

 

编辑: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>
        .container{
            margin-top: 80px;
        }
    </style>
</head>
<body>


<div class="container">
    <div>
        <div>
            <div class="bs-example" data-example-id="form-validation-states">
                <form action="{% url 'edit_book' book_list.id %}}" method="post">
                {% csrf_token %}
                    <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="name"  value="{{ book_list.name }}">

                    </div>
                    <div class="form-group has-warning">
                        <label class="control-label" for="inputWarning1">价格</label>
                        <input type="text" class="form-control" id="inputWarning1" name="price" value = {{ book_list.price }}>
                    </div>
                    <div class="form-group has-error">
                        <label class="control-label" for="inputError1">出版时间</label>
                        <input type="date" class="form-control" id="inputError1" name="date" value="{{ book_list.date|date:'Y-n-d:x' }}">
                    </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="">#}
{##}
{#                    </div>#}

                    <div class="form-group has-error">
                        <label class="control-label" for="inputError1" >出版社</label>
{#                        <input type="text" class="form-control" id="inputError1" name="publish">#}
                        <select name="publish" id="inputError1" class="form-control" >
                            {% for pub in publish_list %}
                                {% if book_list.publish == pub %}
                                    <option value="{{ pub.id }}" selected>{{ pub.title }}</option>
                                 {% else %}
                                    <option value="{{ pub.id }}" >{{ pub.title }}</option>
                                
                                {% endif %}

                            {% endfor %}

                        </select>
                    </div>

                    <div class="form-group has-warning">
                        <label class="control-label" for="inputWarning1">作者</label>
{#                        <input type="text" class="form-control" id="inputWarning1" name="author">#}
                        <select name="author" id="" multiple class="form-control">
                            {% for author in author_list %}
                                {% if author in book_list.authors.all %}
                                    <option value="{{ author.id }}" selected >{{ author.name }}</option>
                                 {% else %}
                                    <option value="{{ author.id }}" >{{ author.name }}</option>

                                {% endif %}

                            {% endfor %}

                        </select>
                    </div>

                    <input type="submit" value="提交" class="btn btn-info    pull-right">
                </form>
            </div>
        </div>
    </div>
</div>

</body>
</html>
编辑

 

 

添加:add_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>
        .container{
            margin-top: 80px;
        }
    </style>
</head>
<body>


<div class="container">
    <div>
        <div>
            <div class="bs-example" data-example-id="form-validation-states">
                <form action="{% url 'add_book' %}" method="post">
                {% csrf_token %}
                    <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="name" value = {{ book_list.name }} >

                    </div>
                    <div class="form-group has-warning">
                        <label class="control-label" for="inputWarning1">价格</label>
                        <input type="text" class="form-control" id="inputWarning1" 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="date">
                    </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="">#}
{##}
{#                    </div>#}

                    <div class="form-group has-error">
                        <label class="control-label" for="inputError1">出版社</label>
{#                        <input type="text" class="form-control" id="inputError1" name="publish">#}
                        <select name="publish" id="inputError1" class="form-control" selected>
                            {% for publish in publish_list %}
                                <option value="{{ publish.id }}">{{ publish.title }}</option>
                            {% endfor %}

                        </select>
                    </div>

                    <div class="form-group has-warning">
                        <label class="control-label" for="inputWarning1">作者</label>
{#                        <input type="text" class="form-control" id="inputWarning1" name="author">#}
                        <select name="author" id="" multiple class="form-control" multiple>
                            {% for author in author_list.all %}
                                <option value="{{ author.id }}" >{{ author.name }}</option>
                            {% endfor %}

                        </select>
                    </div>

                    <input type="submit" value="提交" class="btn btn-info    pull-right">
                </form>
            </div>
        </div>
    </div>
</div>

</body>
</html>
add_book

 

 

跳转 hint

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .container{
            margin-top: 80px;
        }
    </style>
</head>
<body>


<script type="text/javascript">
        alert('您输入的用户名不存在 请去注册');
    setTimeout()


    </script>

<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">

<div class="container">
    <div>
        <div>
             <a href="{% url 'register' %}" class="btn btn-lg btn-info btn-block" >Register</a>
        </div>
    </div>
</div>




</body>
</html>
hint

 

posted @ 2018-07-10 10:47  可爱的红领巾  阅读(356)  评论(0编辑  收藏  举报