zoukankan      html  css  js  c++  java
  • python的web框架---Django项目

    Django项目之会议室预预订:

    界面效果展示:

    1、创建超级管理员,实现预定界面功能

     

    2、预定界面:

    (一)基于pymysql设计数据表结构,理清前后端与用户交互逻辑。(用户表,会议室表,预定内容存储表)

      1、settings设置默认数据库为mysql

    DATABASES = {
        'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME':'dbname',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
        }
    }

      2、model表设计:

     1 from django.db import models
     2 from django.contrib.auth.models import AbstractUser
     3 # Create your models here.
     4 
     5 
     6 class UserInfo(AbstractUser):
     7     tel = models.CharField(max_length=32)
     8 
     9 class Room(models.Model):
    10     caption = models.CharField(max_length=32)
    11     num = models.IntegerField()     #容纳人数
    12     def __str__(self):
    13         return self.caption
    14 
    15 class Book(models.Model):
    16     user = models.ForeignKey(to="UserInfo",on_delete=models.CASCADE)
    17     room = models.ForeignKey(to="Room",on_delete=models.CASCADE)
    18     date = models.DateField()
    19     time_choice = (
    20         (1, '8:00'),
    21         (2, '9:00'),
    22         (3, '10:00'),
    23         (4, '11:00'),
    24         (5, '12:00'),
    25         (6, '13:00'),
    26         (7, '14:00'),
    27         (8, '15:00'),
    28         (9, '16:00'),
    29         (10, '17:00'),
    30         (11, '18:00'),
    31         (12, '19:00'),
    32         (13, '20:00'),
    33     )
    34     time_id = models.IntegerField(time_choice)
    35 
    36     class Meta:
    37         unique_together = (
    38             ("room","date","time_id"),
    39         )
    40 
    41     def __str__(self):
    42         return "{}预定了{}".format(self.user,self.room)

    2、梳理urls路由系统、利用内置auth验证模块编写用户登录。利用js在后端处理用户操作,ajax技术发送request数据。

     1 from django.shortcuts import render,redirect,HttpResponse
     2 from django.contrib import auth
     3 from app01 import models
     4 import datetime
     5 import json
     6 # Create your views here.
     7 
     8 def login(request):  #设置登录处理函数
     9     if request.method == "POST":
    10 
    11         username = request.POST.get("username")
    12         pwd = request.POST.get("password")
    13         user = auth.authenticate(username=username,password=pwd)
    14         if user:
    15             auth.login(request,user)
    16             return redirect("/index/")
    17 
    18     return render(request,"login.html",locals())
    19 
    20 
    21 date = datetime.datetime.now().date()
    22 
    23 
    24 def index(request):
    25 
    26     if not request.user.is_authenticated:
    27         return redirect("/login/")
    28 
    29 
    30     book_date = request.GET.get("book_date",date)
    31 
    32     time_choice=models.Book.time_choice
    33     room_obj = models.Room.objects.all()
    34     book_obj = models.Book.objects.filter(date=date)
    35 
    36     htmls = ""
    37     for room in room_obj:
    38         htmls += "<tr><td>{}</td>".format(room)
    39 
    40         for time in time_choice:
    41 
    42             is_choose = False
    43 
    44             for book in book_obj:
    45                 if book.time_id == time[0] and book.room_id == room.pk:   #判断是否有人预订
    46                     is_choose = True
    47                     break
    48 
    49             if is_choose:
    50                 if request.user.pk == book.user_id:  #python代码层面处理模板json数据
    51 htmls += "<td class='my_active item' time_id={} room_id={}>{}</td>".format(time[0],room.pk,book.user)
    52 else:
    53                     htmls += "<td class='active item' time_id={} room_id={}>{}</td>".format(time[0],room.pk,book.user)
    54             else:
    55                 htmls += "<td class='item' time_id={} room_id={}></td>".format(time[0],room.pk)
    56 
    57         htmls += "</tr>"
    58 
    59     return render(request,"index.html",locals())
    60 
    61 def manage(request):
    62     if request.method == "POST":
    63         data = json.loads(request.POST.get("post_data"))
    64         print(data)
    65 
    66         for room_id,time_id_list in data["del"].items():
    67             for time_id in time_id_list:
    68                 models.Book.objects.filter(user_id=request.user.pk,room_id=room_id,time_id=time_id,date=date).delete()
    69 
    70         for room_id,time_id_list in data["add"].items():
    71             for time_id in time_id_list:
    72                 models.Book.objects.create(user_id=request.user.pk,room_id=room_id,time_id=time_id,date=date)
    73 
    74 
    75         return HttpResponse(json.dumps("ok"))

    3、编写templates模板,利用bootstrap丰富起始界面,python代码层面处理模板json数据。

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Title</title>
     6     <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
     7     <style>
     8         .my_active{background-color: red}
     9         .active{background-color: silver}
    10         .temp_active{background-color: #2aabd2}
    11     </style>
    12 </head>
    13 <body>
    14 
    15 <h1>会议室预订</h1>
    16 
    17 
    18 
    19 <table class="table table-bordered">
    20     <tr>
    21         <th>会议室/时间</th>
    22         {% for time in time_choice %}
    23             <th>{{ time.1 }}</th>
    24         {% endfor %}
    25     </tr>
    26     {{ htmls|safe }}
    27 </table>
    28 <button>保存</button>
    29 {% csrf_token %}
    30 
    31 
    32 <script src="/static/jquery.js"></script>
    33 <script src="/static/bootstrap/js/bootstrap.js"></script>
    34 <script>
    35 
    36 
    37     var post_data = {"add":{},"del":{}};
    38 
    39     //为td标签绑定点击事件
    40     $(".item").click(function(){
    41 
    42         var time_id = $(this).attr("time_id");
    43         var room_id = $(this).attr("room_id");
    44 
    45         if($(this).hasClass("my_active")){        //如果是登录人预订的时间
    46             $(this).removeClass("my_active");
    47             $(this).text("");
    48 
    49             if(post_data["del"][room_id]){
    50                 post_data["del"][room_id].push(time_id)
    51             }else{
    52                 post_data["del"][room_id] = [time_id,];
    53             }
    54 
    55         }else if($(this).hasClass("active")){        //如果是别人预订的时间
    56             alert("已经被预订!")
    57 
    58         }else if($(this).hasClass("temp_active")){
    59             $(this).removeClass("temp_active")
    60             $(this).text("")
    61             post_data["add"][room_id].splice(jQuery.inArray(time_id,post_data["add"][room_id]),1)
    62 
    63         }else{                                   //如果没人预订
    64             $(this).addClass("temp_active");
    65             $(this).text("{{ request.user.username }}")
    66 
    67             if(post_data["add"][room_id]){
    68                 post_data["add"][room_id].push(time_id)
    69             }else{
    70                 post_data["add"][room_id] = [time_id,];
    71             }
    72         }
    73         console.log(post_data)
    74     })
    75 
    76     var csrf = $("[name='csrfmiddlewaretoken']").val()
    77 
    78     $("button").click(function(){
    79         $.ajax({
    80             url:"/manage/",
    81             type:"post",
    82             data:{
    83                 post_data:JSON.stringify(post_data),
    84                 csrfmiddlewaretoken:csrf,
    85             },
    86             dataType:"json",
    87             success:function(arg){
    88                 console.log(arg)
    89                 location.href = ""
    90 
    91             }
    92         })
    93     })
    94 </script>
    95 </body>
    96 </html>

      

  • 相关阅读:
    程序员最好也要懂的一些沟通说服技巧
    MapFields和并行计算(OpenFOAM)
    Python 调用自己编写的Class
    Ubuntu 图形桌面死机重启(机器不重启)
    Ubuntu 安装 Visual Studio Code
    Ubuntu图形界面和终端界面切换快捷键
    Linux直接在通过终端打开图片文件
    Linux新建环境变量快速切换到文件夹(export)
    Python文件读写(一)
    Dictonary(Python)(一)
  • 原文地址:https://www.cnblogs.com/xuechaojun/p/10877989.html
Copyright © 2011-2022 走看看