Django之会议室预预订
model表设计:
from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class UserInfo(AbstractUser): tel = models.CharField(max_length=32) class Room(models.Model): caption = models.CharField(max_length=32) num = models.IntegerField() #容纳人数 def __str__(self): return self.caption class Book(models.Model): user = models.ForeignKey(to="UserInfo",on_delete=models.CASCADE) room = models.ForeignKey(to="Room",on_delete=models.CASCADE) date = models.DateField() time_choice = ( (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'), ) time_id = models.IntegerField(time_choice) class Meta: unique_together = ( ("room","date","time_id"), ) def __str__(self): return "{}预定了{}".format(self.user,self.room)
views视图函数:
from django.shortcuts import render,redirect,HttpResponse from django.contrib import auth from app01 import models import datetime import json # Create your views here. def login(request): if request.method == "POST": username = request.POST.get("username") pwd = request.POST.get("password") user = auth.authenticate(username=username,password=pwd) if user: auth.login(request,user) return redirect("/index/") return render(request,"login.html",locals()) date = datetime.datetime.now().date() def index(request): if not request.user.is_authenticated: return redirect("/login/") book_date = request.GET.get("book_date",date) time_choice=models.Book.time_choice room_obj = models.Room.objects.all() book_obj = models.Book.objects.filter(date=date) htmls = "" for room in room_obj: htmls += "<tr><td>{}</td>".format(room) for time in time_choice: is_choose = False for book in book_obj: if book.time_id == time[0] and book.room_id == room.pk: #判断是否有人预订 is_choose = True break if is_choose: if request.user.pk == book.user_id: htmls += "<td class='my_active item' time_id={} room_id={}>{}</td>".format(time[0],room.pk,book.user) else: htmls += "<td class='active item' time_id={} room_id={}>{}</td>".format(time[0],room.pk,book.user) else: htmls += "<td class='item' time_id={} room_id={}></td>".format(time[0],room.pk) htmls += "</tr>" return render(request,"index.html",locals()) def manage(request): if request.method == "POST": data = json.loads(request.POST.get("post_data")) print(data) for room_id,time_id_list in data["del"].items(): for time_id in time_id_list: models.Book.objects.filter(user_id=request.user.pk,room_id=room_id,time_id=time_id,date=date).delete() for room_id,time_id_list in data["add"].items(): for time_id in time_id_list: models.Book.objects.create(user_id=request.user.pk,room_id=room_id,time_id=time_id,date=date) return HttpResponse(json.dumps("ok"))
templates模板部分:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css"> <style> .my_active{background-color: red} .active{background-color: silver} .temp_active{background-color: #2aabd2} </style> </head> <body> <h1>会议室预订</h1> <table class="table table-bordered"> <tr> <th>会议室/时间</th> {% for time in time_choice %} <th>{{ time.1 }}</th> {% endfor %} </tr> {{ htmls|safe }} </table> <button>保存</button> {% csrf_token %} <script src="/static/jquery.js"></script> <script src="/static/bootstrap/js/bootstrap.js"></script> <script> var post_data = {"add":{},"del":{}}; //为td标签绑定点击事件 $(".item").click(function(){ var time_id = $(this).attr("time_id"); var room_id = $(this).attr("room_id"); if($(this).hasClass("my_active")){ //如果是登录人预订的时间 $(this).removeClass("my_active"); $(this).text(""); if(post_data["del"][room_id]){ post_data["del"][room_id].push(time_id) }else{ post_data["del"][room_id] = [time_id,]; } }else if($(this).hasClass("active")){ //如果是别人预订的时间 alert("已经被预订!") }else if($(this).hasClass("temp_active")){ $(this).removeClass("temp_active") $(this).text("") post_data["add"][room_id].splice(jQuery.inArray(time_id,post_data["add"][room_id]),1) }else{ //如果没人预订 $(this).addClass("temp_active"); $(this).text("{{ request.user.username }}") if(post_data["add"][room_id]){ post_data["add"][room_id].push(time_id) }else{ post_data["add"][room_id] = [time_id,]; } } console.log(post_data) }) var csrf = $("[name='csrfmiddlewaretoken']").val() $("button").click(function(){ $.ajax({ url:"/manage/", type:"post", data:{ post_data:JSON.stringify(post_data), csrfmiddlewaretoken:csrf, }, dataType:"json", success:function(arg){ console.log(arg) location.href = "" } }) }) </script> </body> </html>