The web framework of python -- Django project

Conference room reservation for Django project:

Interface effect display:

1. Create super administrator to realize the function of predetermined interface

 

 

2. Scheduled interface:

 

(1) design data table structure based on pymysql, and clarify the interaction logic between front and back end and user. (user table, meeting room table, scheduled content storage table)

1. settings: the default database is mysql

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

2. model table design:

 

 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()     #Accommodating population
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 "{}Booked{}".format(self.user,self.room)

 

 

 

2. Comb the urls routing system and write the user login using the built-in auth authentication module. js is used to process user operation in the back end, and ajax technology sends request data.

 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):  #Set login processing function
 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:   #Determine if there is a reservation
46                     is_choose = True
47                     break
48 
49             if is_choose:
50                 if request.user.pk == book.user_id:  #staypython Code level processing template json data
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. Write templates, use bootstrap to enrich the starting interface, and process the template json data at the python code level.

 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>Conference room reservation</h1>
16 
17 
18 
19 <table class="table table-bordered">
20     <tr>
21         <th>Conference Room/time</th>
22         {% for time in time_choice %}
23             <th>{{ time.1 }}</th>
24         {% endfor %}
25     </tr>
26     {{ htmls|safe }}
27 </table>
28 <button>Preservation</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     //by td Tag binding click event
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")){        //If the time is reserved by the login
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")){        //If it's someone else's time
56             alert("Already booked!")
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{                                   //If no one makes a reservation
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>

Tags: Python JSON Django MySQL JQuery

Posted on Sat, 09 Nov 2019 15:21:18 -0500 by TwistedLogix