關於會議室的增刪改查css
查:html
HTML:jquery
login繼承django自帶的admin用戶認證系統ajax
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <p>姓名 <input type="text" name="user"></p> <p>密碼 <input type="password" name="pwd"></p> <input type="submit"> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css"> <script src="/static/jquery-3.2.1.min.js"></script> <title>會議室</title> <style > .active { background-color: deepskyblue !important; color: black; text-align: center; font-size: 16px; } .td_active { background-color: greenyellow ; } .active_other { background-color: orange !important; color: white; text-align: center; font-size: 16px; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-11"> <h3>會議室預約</h3> <div> <table class="table table-bordered table-striped"> <thead> <tr> <th>會議室</th> {# 時間 時間元組 #} {% for item in time_choices %} <th>{{ item.1 }}</th> {% endfor %} </tr> </thead> <tbody> {{ html|safe }} </tbody> </table> <button class="btn btn-primary pull-right keep">保存</button> </div> </div> </div> </div> <script> </script> </body> </html>
PY:django
from django.db import models # Create your models here. from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class MeetingRoom(models.Model): '''會議室 ''' name = models.CharField(max_length=32,verbose_name="會議室名稱") num = models.IntegerField() # 最大開會人數 def __str__(self): return self.name class UserInfo(AbstractUser): tel=models.CharField(max_length=32) def __str__(self): return self.username class Book(models.Model): '''預約記錄表''' date = models.DateField(verbose_name="預約日期") user = models.ForeignKey(to="UserInfo",verbose_name="預訂用戶") # 關聯用戶 room = models.ForeignKey(to="MeetingRoom",verbose_name="預約房間") # 關聯房間 time1 = ( (1,"8.00"), (2,"9.00"), (3,"10.00"), (4,"11.00"), (5,"12.00"), (6,"13.00"), (7,"14.00"), (8,"15.00"), (9,"16.00"), (10,"17.00"), (11,"18.00"), (12,"19.00"), (13,"20.00"), ) timeline = models.IntegerField(choices=time1,verbose_name="預約時間") # 存的是數字 class Meta: # 聯合惟一,爲何沒有user,由於只有有下面3個字段,即表示有預約了 unique_together = ( ('room','date','timeline'), ) def __str__(self): return str(self.user) + "預約了" + str(self.room)
from django.shortcuts import render,redirect # Create your views here. from .models import * def index(request): # 取到全部的預約信息 book_list = Book.objects.all() # 取全部的房間信息 room_list = MeetingRoom.objects.all() # 房間的時間段 time_choices = Book.time1 # 渲染空的td, 有幾個td,取決於有幾個時間段 html="" for room in room_list: s = "<tr><td>{0}({1})</td>".format(room.name,room.num) for item in time_choices: # 循環全部的時間段單元格 ((1,"8:00"))() flag=False # 標誌有否預約信息 for book in book_list: # 循環每一個預約信息 print(MeetingRoom.pk) if book.room.pk == room.pk and book.timeline == item[0]: flag=True # 經過 break if flag: # 最後循環出來的book是匹配的信息 if request.user.pk != book.user.pk: # 不一樣用戶顯示不一樣的樣式 s += '<td class="active_other item" room_id="{0}" time_id="{1}">{2}</td>'.format(room.pk,item[0],book.user.username) else: s += '<td class="active item" room_id="{0}" time_id="{1}">{2}</td>'.format(room.pk,item[0],book.user.username) else: s += '<td class="item" room_id="{0}" time_id="{1}"></td>'.format(room.pk,item[0]) s += "</tr>" html += s return render(request,"index.html",locals()) from django.contrib import auth def login(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") user = auth.authenticate(username=user, password=pwd) if user: auth.login(request, user) # 註冊session return redirect("/index/") return render(request, "login.html")
關於DATE--轉化-->年月日json
也能夠經過CHOSEN_DATE=new Date().getFullYear()等等,各取出年月日,拼成年月日bootstrap
知識點:jssession
自定義標籤方法app
-------------ide
datetime模塊下有4個類
datetime.date---->年月日
datetime.time----->時分秒
datetime.datetime---->年月日時分秒
datetime.timedelta--->表明兩個時間之間的時間差
日期加減
BUG1
使用時間插件跳轉某日期,因爲ajax,刷新頁面致使date從新賦值 一直是當前日期。
思路:直接取url的值http://127.0.0.1:8000/index/?book_date=2018-03-29
model
from django.db import models # Create your models here. from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class MeetingRoom(models.Model): '''會議室 ''' name = models.CharField(max_length=32,verbose_name="會議室名稱") num = models.IntegerField() # 最大開會人數 def __str__(self): return self.name class UserInfo(AbstractUser): tel=models.CharField(max_length=32) def __str__(self): return self.username class Book(models.Model): '''預約記錄表''' date = models.DateField(verbose_name="預約日期") user = models.ForeignKey(to="UserInfo",verbose_name="預訂用戶") # 關聯用戶 room = models.ForeignKey(to="MeetingRoom",verbose_name="預約房間") # 關聯房間 time1 = ( (1,"8.00"), (2,"9.00"), (3,"10.00"), (4,"11.00"), (5,"12.00"), (6,"13.00"), (7,"14.00"), (8,"15.00"), (9,"16.00"), (10,"17.00"), (11,"18.00"), (12,"19.00"), (13,"20.00"), ) timeline = models.IntegerField(choices=time1,verbose_name="預約時間") # 存的是數字 class Meta: # 聯合惟一,爲何沒有user,由於只有有下面3個字段,即表示有預約了 unique_together = ( ('room','date','timeline'), ) def __str__(self): return str(self.user) + "預約了" + str(self.room)
views
from django.shortcuts import render,redirect # Create your views here. from .models import * def index(request): # 取全部的房間信息 room_list = MeetingRoom.objects.all() # 房間的時間段 time_choices = Book.time1 # 取到當前日期的預約信息 datetime.datetime.now().date() 爲默認值 choice_date = request.GET.get('book_date',datetime.datetime.now().date()) # 判斷當前日期是否爲字符串 datetime.datetime.now().date()爲當前的對象 if isinstance(choice_date,str): choice_date = datetime.datetime.strptime(choice_date,'%Y-%m-%d').date() # 字符串轉爲對象 book_list = Book.objects.filter(date=choice_date) # 渲染空的td, 有幾個td,取決於有幾個時間段 html="" for room in room_list: s = "<tr><td>{0}({1})</td>".format(room.name,room.num) for item in time_choices: # 循環全部的時間段單元格 ((1,"8:00"))() flag=False # 標誌有否預約信息 for book in book_list: # 循環每一個預約信息 if book.room.pk == room.pk and book.timeline == item[0]: flag=True # 經過 break if flag: # 最後循環出來的book是匹配的信息 if request.user.pk != book.user.pk: # 不一樣用戶顯示不一樣的樣式 s += '<td class="active_other item" room_id="{0}" time_id="{1}">{2}</td>'.format(room.pk,item[0],book.user.username) else: s += '<td class="active item" room_id="{0}" time_id="{1}">{2}</td>'.format(room.pk,item[0],book.user.username) else: s += '<td class="item" room_id="{0}" time_id="{1}"></td>'.format(room.pk,item[0]) s += "</tr>" html += s return render(request,"index.html",locals()) from django.contrib import auth def login(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") user = auth.authenticate(username=user, password=pwd) if user: auth.login(request, user) # 註冊session return redirect("/index/") return render(request, "login.html") import datetime import json def book(request): choice_date = request.POST.get('date') choice_date = datetime.datetime.strptime(choice_date,'%Y-%m-%d').date() # 取的日期是字符串 post_data = json.loads(request.POST.get('data')) print(post_data['ADD']) # response:ajax的響應 status:狀態 response = {'status': True, 'msg': None, 'data': None} # 增長預約操做 room_id:會議室id time_list:存時間的id的列表 # 格式:{"2":["1","2"],"3":["1","2","3"]} try: book_obj_list = [] for room_id,time_list in post_data['ADD'].items(): for time_id in time_list: # print(time_id) # 8 9 obj = Book(room_id=room_id,timeline=time_id,user_id=request.user.pk,date=choice_date) book_obj_list.append(obj) # 使用批量處理去綁定 Book.objects.bulk_create(book_obj_list) except Exception as e: response['status'] = False response['msg'] = str(e) from django.http import JsonResponse return JsonResponse(response)
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css"> <script src="/static/jquery-3.2.1.min.js"></script> <script src="/static/datetimepicker/bootstrap-datetimepicker.min.js"></script> <script src="/static/datetimepicker//bootstrap-datetimepicker.zh-CN.js"></script> <title>會議室</title> <style> .active { background-color: deepskyblue !important; color: black; text-align: center; font-size: 16px; } .td_active { background-color: greenyellow; } .active_other { background-color: orange !important; color: white; text-align: center; font-size: 16px; } </style> </head> <body> <h3>會議室預約</h3> <div class="calender pull-right"> <div class='input-group' style="width: 230px;"> <input type='text' class="form-control" id='datetimepicker11' placeholder="請選擇日期"/> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"> </span> </span> </div> </div> <table class="table table-bordered table-striped"> <thead> <tr> <th>會議室/時間</th> {% for item in time_choices %} <th>{{ item.1 }}</th> {% endfor %} </tr> </thead> <tbody> {{ html|safe }} </tbody> </table> <button class="btn btn-primary pull-right keep">保存</button> {% csrf_token %} <script> // Format:咱們添加的方法。 // 自帶Date沒有咱們想要的方法 Date.prototype.Format = function (fmt) { //author: "%Y-%m" var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小時 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; }; {# 自執行函數#} $(function () {// date: $('#datetimepicker11').datetimepicker({ minView: "month", language: "zh-CN", sideBySide: true, format: 'yyyy-mm-dd', startDate: new Date(), bootcssVer: 3, autoclose: true }).on('changeDate', book_query); bindTd() }); // get請求 ev.date:插件選中的當前日期對象(ev 可自定義) function book_query(ev) { CHOSEN_DATE = ev.date.Format('yyyy-MM-dd'); location.href = "/index/?book_date=" + CHOSEN_DATE } {# 用戶提交的數據集合成兩種分 增,刪 --> 整理成{[] } 形式 #} var POST_DATA = { DEL: {}, ADD: {} }; function bindTd() { $(".item").click(function () { {# 判斷是否登陸#} if ("{{ request.user.username }}") { var room_id = $(this).attr('room_id'); var time_id = $(this).attr('time_id'); // 整合數據格式 if ($(this).hasClass("td_active")) { $(this).removeClass("td_active"); POST_DATA.ADD[room_id].pop(time_id) } else { // 預約會議室操做 增的操做 $(this).addClass("td_active"); if (POST_DATA.ADD[room_id]){ // 當已有的房間號,爲添加 POST_DATA.ADD[room_id].push(time_id); } else { // 建立 POST_DATA.ADD[room_id] = [time_id]; } } } else { location.href = "/login/" } }) } // date日期:解決ajax頁面刷新,date賦值問題 if (location.search.slice(11)) { CHOSEN_DATE = location.search.slice(11) } else { CHOSEN_DATE = new Date().Format("yyyy-MM-dd"); // 取到當前的時間對象 } // 給保存按鈕綁定ajax事件 $(".keep").click(function () { $.ajax({ url: "/book/", type: "POST", // 上面的POSTdata缺時間及cs 前面的data是數據部分,後面的date是日期 data: {data: JSON.stringify(POST_DATA), date: CHOSEN_DATE, csrfmiddlewaretoken: '{{ csrf_token }}'}, success: function (data) { if (data.status) { location.href = "" } else { alert("有問題請求") } } }) }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <p>姓名 <input type="text" name="user"></p> <p>密碼 <input type="password" name="pwd"></p> <input type="submit"> </form> </body> </html>