• 学员练车选课系统


    1.创建学员与教练之间的数据关系

      通过第三张表进行关联

      models.py文件

    from django.db import models
    
    # Create your models here.
    
    
    class Student(models.Model):
        username = models.CharField(max_length=32)
        password = models.CharField(max_length=32)
    
        def __str__(self):
            return self.username
    
    
    class Coach(models.Model):
        name = models.CharField(max_length=32)
    
        def __str__(self):
            return self.name
    
    
    class Book(models.Model):
        students = models.ForeignKey(to='Student')
        coaches = models.ForeignKey(to='Coach')
        date = models.DateField()
        time_choices = (
            (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"),
            (11, "17:00"),
            (12, "18:00"),
        )
        time_id = models.IntegerField(choices=time_choices)
    
        #联合唯一
        class Meta:
            unique_together = (
                ('room', 'date', 'time_id'),
            )
    
        def __str__(self):
            return str(self.students) + "预定了" + str(self.coaches)

    2.   urls.py文件

      login   创建登陆的函数

      index  创建登陆成功页面

      book  Ajax返回的页面

    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url('^login/',views.login),
        url('^index/',views.index),
        url('^book/',views.book)
    ]

    3.views.py

    from django.shortcuts import render, HttpResponse, redirect
    from app01 import models
    
    from django.http import JsonResponse
    # Create your views here.
    def login(request):
        if request.method == 'POST':
            user = request.POST.get('username')
            pwd = request.POST.get('pwd')
            user = models.Student.objects.filter(username=user, password=pwd).first()
            if user:
                request.session['student_pk'] = user.pk
                return redirect('/index/')
        return render(request, 'login.html')
    
    
    import datetime
    
    
    def index(request):
        today = datetime.datetime.now().date()
        book_date = request.GET.get("book_date", today)
        time_choices = models.Book.time_choices
        coaches = models.Coach.objects.all()
        books = models.Book.objects.filter(date=book_date)
        user_pk = request.session.get('student_pk')
        user = models.Student.objects.filter(pk = user_pk).first()
        htmls = ''
        choice_day = models.Book.date
        for coach in coaches:
            htmls += "<tr><td>{}</td>".format(coach)
            for time_choice in time_choices:
                flag = False
                for book in books:
                    if book.time_id == time_choice[0] and book.coaches.pk == coach.pk:
                        flag = True
                        break
                if flag:
                    if user_pk == book.students.pk:
                        htmls += "<td coach_id={0} class= 'active d1'  choice_id={1}>{2}</td>".format(coach.pk, time_choice[0],book.students.username)
                    else:
                        htmls += "<td coach_id={0} class= 'other_active d1'  choice_id={1}>{2}</td>".format(coach.pk, time_choice[0],book.students.username)
                else:
                    htmls += "<td coach_id={0} class='d1' choice_id={1}></td>".format(coach.pk, time_choice[0])
            htmls += "</tr>"
        return render(request, 'index.html', locals())
    
    
    import json
    
    
    def book(request):
        print(request.POST)
        user_pk = request.session.get('student_pk')
        post_data=json.loads(request.POST.get("post_data")) # {"ADD":{"1":["5"],"2":["5","6"]},"DEL":{"3":["9","10"]}}
        print(post_data)
        choose_date=request.POST.get("choose_date")
        print(choose_date)
    
        res={"state":True,"msg":None}
        try:
            # 添加预定
            #post_data["ADD"] : {"1":["5"],"2":["5","6"]}
    
            book_list=[]
    
            for coach_id,choice_id_list in post_data["ADD"].items():
    
                for choice_id in choice_id_list:
                    book_obj=models.Book(students_id=user_pk,coaches_id=coach_id,time_id=choice_id,date=choose_date)
                    book_list.append(book_obj)
    
            models.Book.objects.bulk_create(book_list)       # bulk_create批量插入
    
    
            # 删除预定
            from django.db.models import Q
            # post_data["DEL"]: {"2":["2","3"]}
    
    
            remove_book = Q()
            for coach_id,choice_id_list in post_data["DEL"].items():
                temp = Q()
                for choice_id in choice_id_list:
                    temp.children.append(("coaches_id",coach_id))
                    temp.children.append(("time_id",choice_id))
                    temp.children.append(("students_id",user_pk))
                    temp.children.append(("date",choose_date))
                    remove_book.add(temp)
            if remove_book:
                 models.Book.objects.filter(remove_book).delete()
    
    
    
        except Exception as e:
            res["state"]=False
            res["msg"]=str(e)
    
        # return HttpResponse(json.dumps(res))
        return JsonResponse(res)

    4.登陆页面html

      login.html

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>login</title>
        <meta content="width=device-width, initial-scale=1" name="viewport">
        <link href="../static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="../static/fontawesome/css/font-awesome.min.css">
    </head>
    <body>
    <form action="" method="post">
        {% csrf_token %}
        <h3>学员登陆页面</h3>
        <p> 学员账号:
            <input type="text" name="username">
        </p>
        <p> 密码:
            <input type="password" name="pwd">
        </p>
        <input type="submit" value="登陆">
    </form>
    <script src="../static/jquery-3.3.1.min.js"></script>
    <script src="../static/bootstrap/js/bootstrap.min.js"></script>
    </body>
    </html>
    

    2.登陆成功页面

      index.html

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>index</title>
        <meta content="width=device-width, initial-scale=1" name="viewport">
    
     <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
     <script src="/static/js/jquery-1.12.4.min.js"></script>
    
     <script src="/static/datetimepicker/bootstrap-datetimepicker.min.js"></script>
     <script src="/static/datetimepicker/bootstrap-datetimepicker.zh-CN.js"></script>
    
        <style>
            .active {
                background-color: #a6e1ec !important;
            }
    
            .other_active {
                background-color: darkgrey;
            }
    
            .choiced_active {
                background-color: rosybrown;
            }
        </style>
    </head>
    <body>
    
    <h3>选课页面</h3>
    <div class="calender pull-right">
        <div class='input-group' style=" 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">
        <thead>
        <tr>
            <th>教练/时间</th>
            {% for time_choice in time_choices %}
                <th>{{ time_choice.1 }}</th>
            {% endfor %}
        </tr>
        </thead>
        <tbody>
        {{ htmls|safe }}
        </tbody>
    </table>
    <button class="btn btn-primary pull-right keep" type="submit">确定</button>
    
    <script>
        // 日期格式化方法
        Date.prototype.yuan = function (fmt) { //author: meizz
                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;
            };
    
    
        var Updata = {
            ADD: {},
            DEL: {},
        };
    
        $(".d1").click(function () {
            var coach_id = $(this).attr("coach_id");
            var choice_id = $(this).attr("choice_id");
            if ($(this).hasClass("active")) {
                $(this).removeClass("active").empty();
                if (Updata.DEL[coach_id]) {
                    Updata.DEL[coach_id].push(choice_id)
                } else {
                    Updata.DEL[coach_id] = [choice_id,]
                }
            } else if ($(this).hasClass("choiced_active")) {
                $(this).removeClass("choiced_active")
                Updata.ADD[coach_id].pop()
            } else {
                $(this).addClass("choiced_active");
                if (Updata.ADD[coach_id]) {
                    Updata.ADD[coach_id].push(choice_id)
                } else {
                    Updata.ADD[coach_id] = [choice_id,]
                }
            }
    
        });
    
         // 日期
    
         if (location.search.slice(11)){
               CHOOSE_DATE = location.search.slice(11)
              }
          else {
               CHOOSE_DATE = new Date().yuan('yyyy-MM-dd');
               }
    
    
        // 发送ajax
    
        $(".keep").click(function () {
    
            $.ajax({
                url:"/book/",
                type:"POST",
                data:{
                     choose_date:CHOOSE_DATE,
                     post_data:JSON.stringify(Updata),
                },
                success:function (data) {
                    console.log(data);
    
                    if(data.state){
                        // 预定成功
                        location.href=""
                    }else {
                        location.href=""
                    }
    
            }
    
            })
        });
    
    
        // 日历插件
    
        $('#datetimepicker11').datetimepicker({
                    minView: "month",
                    language: "zh-CN",
                    sideBySide: true,
                    format: 'yyyy-mm-dd',
                    startDate: new Date(),
                    bootcssVer: 3,
                    autoclose: true,
                }).on('changeDate', book_query);
    
         function book_query(e) {
             CHOOSE_DATE=e.date.yuan("yyyy-MM-dd");
             location.href="/index/?book_date="+CHOOSE_DATE;
         }
    
    
    
    
    
    
    </script>
    
    
    </body>
    </html>

    其中静态文件引用了bootstrap,datetimepicker, JS, jequery.

  • 相关阅读:
    Docker 入门指南——Dockerfile 指令
    这个断点可以帮你检查布局约束
    个推你应该这样用的
    网易云直播SDK使用总结
    当微信和支付宝遇上友盟
    环信SDK 头像、昵称、表情自定义和群聊设置的实现 二(附源码)
    环信SDK 头像、昵称、表情自定义和群聊设置的实现 一(附源码)
    事件分发机制
    常用开发技巧系列(一)
    iOS RunTime你知道了总得用一下
  • 原文地址:https://www.cnblogs.com/wm0217/p/11362221.html
Copyright © 2020-2023  润新知