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

时间:2022-07-01 03:29:14

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')
]