1、用户通过用户名密码登陆图书管理页面
2、在管理页面可进行添加、编辑、删除书籍
3、前端进行增删改时,数据库需同步进行操作
4、可随时注销用户,退出登陆并清除cookie缓存
用户通过指定用户名密码登陆后,发起session会话,浏览器存储session_id
在管理页面用户可进行增删改
views.py:
from django.shortcuts import render,HttpResponse,redirect
from app01 import models
# Create your views here.
def Book(request):
ret=models.Book.objects.all()
return render(request,'primary_page.html',{'ret':ret})
def delete(request,n):
models.Book.objects.get(id=n).delete()
return redirect('/book/')
def editpg(request,n):
ret=models.Book.objects.filter(id=n)
return render(request,'editpage.html',{'ret':ret})
def edit(request,n):
if request.method == 'POST':
title=request.POST.get('title')
price=request.POST.get('price')
date=request.POST.get('date')
publish=request.POST.get('publish')
author = request.POST.getlist('author')
author_table = {'Lsir':1,'Jsir':2,'Zsir':3,'Ysir':4,'Wsir':5}
author_id=[]
for i in author:
value=str(author_table[i])
author_id.append(value)
publish_id=None
if publish == "人民出版社":
publish_id = 1
elif publish == "清华出版社":
publish_id = 2
elif publish == "天一出版社":
publish_id = 3
models.Book.objects.filter(id=n).update(
title=title,
price=price,
publishDate=date,
publish_id=publish_id,
)
ret=models.Book.objects.get(id=n)
ret.authors.set(author_id)
home=redirect('/book/')
return home
def addpg(request):
if request.method == 'POST':
title=request.POST.get('title')
price=request.POST.get('price')
date=request.POST.get('date')
publish=request.POST.get('publish')
publish_id = None
if publish == "人民出版社":
publish_id = 1
elif publish == "清华出版社":
publish_id = 2
elif publish == "天一出版社":
publish_id = 3
author=request.POST.getlist('author')
author_table={'Lsir':1,'Jsir':2,'Zsir':3,'Ysir':4,'Wsir':5}
author_id=[]
for i in author:
value=author_table[i]
author_id.append(value)
models.Book.objects.create(
title=title,
price=price,
publishDate=date,
publish_id=publish_id
)
book_id=models.Book.objects.filter(title=title).values('id')
obj=models.Book.objects.get(id=book_id)
obj.authors.add(*author_id)
home=redirect('/book/')
return home
else:
page=render(request,'addpage.html')
return page
def login(request):
if request.method == 'GET':
home=render(request,'login.html')
return home
else:
if request.POST.get('username') == 'root' and request.POST.get('password') == 'password':
request.session['is_login']=True
sign=HttpResponse('ok')
return sign
else:
sign = HttpResponse('error')
return sign
def loginout(request):
request.session.flush()
res = HttpResponse('ok')
return res
models.py文件:
from django.db import models
# Create your models here.
class Author(models.Model):
name=models.CharField(max_length=32)
age=models.IntegerField()
ad=models.OneToOneField(to='AuthorDetail',to_field='id',on_delete=models.CASCADE)
class AuthorDetail(models.Model):
birthday=models.DateField(auto_now=True)
telephone=models.CharField(max_length=32)
addr=models.CharField(max_length=32)
class Publishs(models.Model):
name=models.CharField(max_length=32)
city=models.CharField(max_length=32)
class Book(models.Model):
title=models.CharField(max_length=32)
publishDate=models.DateField(auto_now=True)
price=models.DecimalField(max_digits=5,decimal_places=2)
publish=models.ForeignKey(to='Publishs')
authors=models.ManyToManyField(to='Author')
urls.py路由配置:
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^book/',views.Book),
url(r'^delete/(\d+)/',views.delete),
url(r'^editpg/(\d+)/',views.editpg),
url(r'^edit/(\d+)/',views.edit),
url(r'^addpg/',views.addpg),
url(r'^login/',views.login),
url(r'^loginout/',views.loginout)
]
自定义中间件cookie_middleware.py文件:
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
class Cookie(MiddlewareMixin):
white_list=['/login/',]
def process_request(self,request):
path=request.path
if path not in self.white_list:
ret=request.session.get('is_login')
if ret != True:
home=redirect('/login/')
return home
配置文件settings.py:
"""
Django settings for library_tables project.
Generated by 'django-admin startproject' using Django 1.11.29.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'nvgephc5onq!pgtz5=77rgr75j3iwu*!%(^(v6r&-o9brp84q('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'app01.middleware.cookie_middleware.Cookie'
]
ROOT_URLCONF = 'library_tables.urls'
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 = 'library_tables.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'library_tables',
'HOST': '10.211.55.9',
'PORT': 3306,
'USER': 'wenzy',
'PASSWORD': 'password'
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
登陆页面及css文件:
login.html文件:
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/5.13.0/css/all.css">
<link rel="stylesheet" href="{% static 'css/login.css' %}">
head>
<body>
<div id="login_box">
<h2>图书管理系统 h2>
<div id="form">
<div id="input_box">
<i class="fa fa-user" aria-hidden="true">i>
<input class="in" type="text" placeholder="Username" id="uname">
div>
<div id="input_box">
<i class="fa fa-key" aria-hidden="true">i>
<input class="in" type="password" placeholder="Password" id="pwd">
div>
div>
<button id="btn">Sign inbutton><br>
<p>
<span id="error" style="color:red;font-size: 15px">span>
p>
div>
body>
<script src="{% static 'js/jquery.js' %}">script>
<script>
$('#btn').click(function () {
var uname = $('#uname').val();
var pwd =$('#pwd').val();
$.ajax({
url:'/login/',
type:'post',
data:{username:uname,password:pwd,csrfmiddlewaretoken:'{{ csrf_token }}'},
success:function (res) {
console.log(res);
if (res === 'ok'){
location.href='/book/'
}
else{
$("#error").text("用户名或密码错误")
}
}
})
})
script>
html>
login.css文件:
body{
background-image:url('http://inews.gtimg.com/newsapp_ls/0/11535311052/0');
background-size: cover;
background-repeat: no-repeat;
}
#login_box{
width: 20%;
height: 400px;
background:#00000040;
margin:auto;
margin-top: 10%;
text-align: center;
border-radius: 10px;
padding: 50px 50px;
}
#login_box h2{
color: #e8e7b730;
margin-top: 5%;
}
#login_box #form #input_box{
margin-top: 5%;
}
#login_box #form #input_box i{
color: #e8e7b730;
}
#login_box #form #input_box input{
border:0;
width: 60%;
font-size: 15px;
color: #fff;
background: #ffffff00;
border-bottom: 2px solid#eacda950;
padding: 5px 10px;
margin-top: 10px;
}
#login_box button{
margin-top: 50px;
width: 40%;
height: 30px;
border-radius: 10px;
border: 0;
color: #fff;
font-size: 15px;
background-image: linear-gradient(to top, #30324d 0%, #5f6298 100%);
}
#login_box #Sign{
margin-top: 45%;
margin-left: 60%;
}
#login_box #Sign a{
color: #d1c2d8;
}
管理页面primary_page.html:
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link rel="stylesheet" href="{% static 'plugins/bootstrap.min.css' %}">
<style>
.c1 {
margin-left: 300px;
margin-right: 50px;
}
.op{
display: inline;
}
#d1{
background: url("{% static 'img/2B.jpg' %}");
background-repeat:no-repeat ;
background-size: cover;
!important;
}
style>
head>
<body id="d1">
<div class="container-fluid" >
<h2>查看书籍h2>
<button class="btn btn-default" type="submit" style="float: right;margin-right: 50px" id="loginout">
注销
button>
<div class="c1">
<form action="/addpg/">
<input type="submit" class="btn btn-primary" value="添加书籍">
form>
<table class="table table-striped">
<thead>
<tr>
<th>编号th>
<th>书籍名称th>
<th>价格th>
<th>出版日期th>
<th>出版社th>
<th>作者名th>
<th>操作th>
tr>
thead>
<tbody class="info">
{% for i in ret %}
<tr class="c2">
<td>{{ forloop.counter }}td>
<td>{{ i.title }}td>
<td>{{ i.price }}td>
<td>{{ i.publishDate|date:"Y-m-d" }}td>
<td>{{ i.publish.name }}td>
<td>
{% for n in i.authors.all %}
{% if forloop.last %}
{{ n.name }}
{% else %}
{{ n.name }},
{% endif %}
{% endfor %}
td>
<td>
<form action="/editpg/{{ i.id }}" class="op">
<input type="submit" class="btn btn-warning" value="编辑">
form>
<form action="/delete/{{ i.id }}" class="op">
<input type="submit" class="btn btn-danger" value="删除">
form>
td>
tr>
{% endfor %}
tbody>
table>
div>
div>
body>
<script src="{% static 'js/jquery.js' %}">script>
<script src="{% static 'plugins/bootstrap.min.js' %}">script>
<script>
$('#loginout').click(function () {
$.ajax({
url:'/loginout/',
type:'get',
success:function (res) {
if (res === 'ok'){
location.href='/login/'
}
}
})
})
script>
html>
新增及编辑页面模版md.html:
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link rel="stylesheet" href="../static/plugins/bootstrap.min.css">
<style>
.c1 {
margin-left: 300px;
margin-right: 50px;
}
.c2{
width:70%
}
#d1{
margin-left: 690px;
}
#md{
background: url("{% static 'img/201515-158211451517f1.jpg' %}");
background-repeat:no-repeat ;
background-size: cover;
!important;
}
style>
head>
<body id="md">
<div class="container-fluid">
<h2>书籍操作h2>
<div class="c1">
{% block form %}
{% endblock %}
div>
div>
body>
<script src="../static/plugins/bootstrap.min.js">script>
html>
添加书籍页面addpage.html:
{% extends 'md.html' %}
{% block form %}
{# {% for i in ret %}#}
<form action="/addpg/" method="post">
{% csrf_token %}
<p>
<span>书籍名称span>
<br>
<input type="text" class="c2" name="title" placeholder="例:我的世界">
p>
<p>
<span>价格span>
<br>
<input type="text" class="c2" name="price" placeholder="例:50">
p>
<p>
<span>出版日期span>
<br>
<input type="date" class="c2" name="date">
p>
<p>
<span>出版社span>
<br>
<select name="publish" class="c2">
<option value='清华出版社'>清华出版社option>
<option value='人民出版社'>人民出版社option>
<option value='天一出版社'>天一出版社option>
select>
p>
<p>
<span>作者span>
<br>
<select name="author" multiple="multiple" class="c2">
<option value="Lsir">Lsiroption>
<option value="Jsir">Jsiroption>
<option value="Zsir">Zsiroption>
<option value="Ysir">Ysiroption>
<option value="Wsir">Wsiroption>
select>
p>
<input type="submit" class="btn btn-success" id="d1" value="提交">
form>
{# {% endfor %}#}
{% endblock %}
编辑书籍信息页面editpage.html
{% extends 'md.html' %}
{% block form %}
{% for i in ret %}
<form action="/edit/{{ i.id }}/" method="post">
{% csrf_token %}
<p>
<span>书籍名称span>
<br>
<input type="text" class="c2" name="title" placeholder={{ i.title }}>
p>
<p>
<span>价格span>
<br>
<input type="text" class="c2" name="price" placeholder={{ i.price }}>
p>
<p>
<span>出版日期span>
<br>
<input type="date" class="c2" name="date">
p>
<p>
<span>出版社span>
<br>
<select name="publish" class="c2">
<option value='清华出版社'>清华出版社option>
<option value='人民出版社'>人民出版社option>
<option value='天一出版社'>天一出版社option>
select>
p>
<p>
<span>作者span>
<br>
<select multiple="multiple" name="author" class="c2">
<option value="Lsir">Lsiroption>
<option value="Jsir">Jsiroption>
<option value="Zsir">Zsiroption>
<option value="Ysir">Ysiroption>
<option value="Wsir">Wsiroption>
select>
p>
<input type="submit" class="btn btn-success" id="d1" value="提交">
<button type="button" class="btn btn-warning" id="back">返回button>
form>
{% endfor %}
{% endblock %}