欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python的web框架---Django项目

程序员文章站 2022-12-26 07:54:33
Django项目之会议室预预订: 界面效果展示: 1、创建超级管理员,实现预定界面功能 2、预定界面: (一)基于pymysql设计数据表结构,理清前后端与用户交互逻辑。(用户表,会议室表,预定内容存储表) 1、settings设置默认数据库为mysql 2、model表设计: 2、梳理urls路由 ......

django项目之会议室预预订:

界面效果展示:

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

python的web框架---Django项目

 

 python的web框架---Django项目

2、预定界面:

python的web框架---Django项目

 

(一)基于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>