实例介绍
【实例简介】简单的会议室预定,选中会议室以后,点击保存即可看到如下图效果
【运行步骤】
下载解压源码后,cd到 manage.py 目录,运行命令 python manage.py runserver
打开浏览器访问 http://localhost:8000/login 即可进行登陆操作
【实例截图】
【核心代码】使用的 django
import json
import datetime
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from . import models
from django.forms import Form
from django.forms import fields
from django.forms import widgets
from django.db.models import Q
from django.db.utils import IntegrityError
class LoginForm(Form):
name = fields.CharField(
required=True,
error_messages={'required': '用户名不能为空'},
widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': '用户名', 'id': 'name'})
)
password = fields.CharField(
required=True,
error_messages={'required': '密码不能为空'},
widget=widgets.PasswordInput(attrs={'class': 'form-control', 'placeholder': '密码', 'id': 'password'})
)
rmb = fields.BooleanField(required=False, widget=widgets.CheckboxInput(attrs={'value': 1}))
def md5(val):
import hashlib
m = hashlib.md5()
m.update(val.encode('utf-8'))
return m.hexdigest()
def auth(func):
def inner(request, *args, **kwargs):
user_info = request.session.get('user_info')
if not user_info:
return redirect('/login/')
return func(request, *args, **kwargs)
return inner
def auth_json(func):
def inner(request, *args, **kwargs):
user_info = request.session.get('user_info')
if not user_info:
return JsonResponse({'status': False, 'msg': '用户未登录'})
return func(request, *args, **kwargs)
return inner
def login(request):
"""
用户登录
"""
if request.method == "GET":
form = LoginForm()
return render(request, 'login.html', {'form': form})
else:
form = LoginForm(request.POST)
if form.is_valid():
rmb = form.cleaned_data.pop('rmb')
form.cleaned_data['password'] = md5(form.cleaned_data['password'])
user = models.UserInfo.objects.filter(**form.cleaned_data).first()
if user:
request.session['user_info'] = {'id': user.id, 'name': user.name}
if rmb:
request.session.set_expiry(60 * 60 * 24 * 30)
return redirect('/index/')
else:
form.add_error('password', '密码错误')
return render(request, 'login.html', {'form': form})
else:
return render(request, 'login.html', {'form': form})
@auth
def index(request):
"""
会议室预定首页
:param request:
:return:
"""
time_choices = models.Booking.time_choices
return render(request, 'index.html', {'time_choices': time_choices})
@auth_json
def booking(request):
"""
获取会议室预定情况以及预定会议室
:param request:
:param date:
:return:
"""
ret = {'code': 1000, 'msg': None, 'data': None}
current_date = datetime.datetime.now().date()
if request.method == "GET":
try:
fetch_date = request.GET.get('date')
fetch_date = datetime.datetime.strptime(fetch_date, '%Y-%m-%d').date()
if fetch_date < current_date:
raise Exception('查询时间不能是以前的时间')
booking_list = models.Booking.objects.filter(booking_date=fetch_date).select_related('user',
'room').order_by(
'booking_time')
booking_dict = {}
for item in booking_list:
if item.room_id not in booking_dict:
booking_dict[item.room_id] = {item.booking_time: {'name': item.user.name, 'id': item.user.id}}
else:
if item.booking_time not in booking_dict[item.room_id]:
booking_dict[item.room_id][item.booking_time] = {'name': item.user.name, 'id': item.user.id}
"""
{
room_id:{
time_id:{''},
time_id:{''},
time_id:{''},
}
}
"""
room_list = models.MeetingRoom.objects.all()
booking_info = []
for room in room_list:
temp = [{'text': room.title, 'attrs': {'rid': room.id}, 'chosen': False}]
for choice in models.Booking.time_choices:
v = {'text': '', 'attrs': {'time-id': choice[0], 'room-id': room.id}, 'chosen': False}
if room.id in booking_dict and choice[0] in booking_dict[room.id]:
v['text'] = booking_dict[room.id][choice[0]]['name']
v['chosen'] = True
if booking_dict[room.id][choice[0]]['id'] != request.session['user_info']['id']:
v['attrs']['disable'] = 'true'
temp.append(v)
booking_info.append(temp)
ret['data'] = booking_info
except Exception as e:
ret['code'] = 1001
ret['msg'] = str(e)
return JsonResponse(ret)
else:
try:
booking_date = request.POST.get('date')
booking_date = datetime.datetime.strptime(booking_date, '%Y-%m-%d').date()
if booking_date < current_date:
raise Exception('查询时间不能是以前的时间')
booking_info = json.loads(request.POST.get('data'))
for room_id, time_id_list in booking_info['add'].items():
if room_id not in booking_info['del']:
continue
for time_id in list(time_id_list):
if time_id in booking_info['del'][room_id]:
booking_info['del'][room_id].remove(time_id)
booking_info['add'][room_id].remove(time_id)
add_booking_list = []
for room_id, time_id_list in booking_info['add'].items():
for time_id in time_id_list:
obj = models.Booking(
user_id=request.session['user_info']['id'],
room_id=room_id,
booking_time=time_id,
booking_date=booking_date
)
add_booking_list.append(obj)
models.Booking.objects.bulk_create(add_booking_list)
remove_booking = Q()
for room_id, time_id_list in booking_info['del'].items():
for time_id in time_id_list:
temp = Q()
temp.connector = 'AND'
temp.children.append(('user_id', request.session['user_info']['id'],))
temp.children.append(('booking_date', booking_date,))
temp.children.append(('room_id', room_id,))
temp.children.append(('booking_time', time_id,))
remove_booking.add(temp, 'OR')
if remove_booking:
models.Booking.objects.filter(remove_booking).delete()
except IntegrityError as e:
ret['code'] = 1011
ret['msg'] = '会议室已被预定'
except Exception as e:
ret['code'] = 1012
ret['msg'] = '预定失败:%s' % str(e)
return JsonResponse(ret)
相关软件
网友评论
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


支持(0) 盖楼(回复)
支持(0) 盖楼(回复)
支持(0) 盖楼(回复)