会议室预定demo mrbs

2018/03/28 23:49
阅读数 782

关于会议室的增删改查

查:

HTML:

login继承django自带的admin用户认证系统

<!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>
login
<!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>
index.

PY:

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)
model
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")
views

 

关于DATE--转化-->年月日

也可以通过CHOSEN_DATE=new Date().getFullYear()等等,各取出年月日,拼成年月日

知识点:js

自定义标签方法

-------------

 

 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)
models

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)
View

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>
View Code
<!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>
login

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部