[PYTHON] Django shift table shift data creation function completed

As a result, I noticed after creating the function, but I wondered if it would be impossible for the shift decision maker to make adjustments after the shift was entered by the person himself. Also, it is necessary to check with the user and change the function.

It ’s been a long time, but it ’s Views.

schedule/views.py


from django.shortcuts import render, redirect, HttpResponseRedirect
from shisetsu.models import *
from accounts.models import *
from .models import *
import calendar
import datetime
from datetime import timedelta
from datetime import datetime as dt
from django.db.models import Sum
from django.contrib.auth.models import User
from django.views.generic import FormView, UpdateView, ListView, CreateView, DetailView, DeleteView
from django.urls import reverse_lazy
from .forms import *
from dateutil.relativedelta import relativedelta
from django.contrib.auth.models import User
# Create your views here.

def homeschedule(request):
    from datetime import datetime
    now = datetime.now()
    return HttpResponseRedirect('/schedule/monthschedule/%s/%s/' % (now.year,now.month,))  #Automatically redirect to this month's shift screen

def monthschedulefunc(request,year_num,month_num):
    user_list = User.objects.all()
    profile_list = Profile.objects.select_related().values().order_by('hyoujijyun')
    year, month = int(year_num), int(month_num)
    shisetsu_object = Shisetsu.objects.all()
    shift_object = Shift.objects.all()
    object_list = Schedule.objects.filter(year = year, month = month).order_by('user', 'date')
    month_total = Schedule.objects.select_related('User').filter(year = year, month = month).values("user").order_by("user").annotate(month_total_worktime = Sum("day_total_worktime"))
    #Get the number of days in the shift range
    enddate = datetime.date(year,month,20)
    startdate = enddate + relativedelta(months=-1)
    kaisu = enddate - startdate
    kaisu = int(kaisu.days) 
    kikan = str(startdate) +"~"+ str(enddate)
    
    #Create a list of dates and days of the week
    hiduke = str(startdate)
    date_format = "%Y-%m-%d"
    hiduke = dt.strptime(hiduke, date_format)
    weekdays = ["Month","fire","water","wood","Money","soil","Day"]
    calender_object = []
    youbi_object = []
    for i in range(kaisu):
        hiduke = hiduke + timedelta(days=1)    
        calender_object.append(hiduke)
        youbi = weekdays[hiduke.weekday()] 
        youbi_object.append(youbi)
    
    kaisu = str(kaisu)

    context = {
        'year': year,
        'month': month,
        'kikan': kikan,
        'object_list': object_list,
        'user_list': user_list,
        'shift_object': shift_object,
        'calender_object': calender_object,
        'youbi_object': youbi_object,
        'kaisu': kaisu,
        'shisetsu_object': shisetsu_object,
        'month_total' : month_total,
        'profile_list' : profile_list,
    }
    return render(request,'schedule/month.html', context)

def scheduleUpdatefunc(request,pk):
    Schedule_list = Schedule.objects.get(pk = int(pk))
    User_list = User.objects.get(username = Schedule_list.user)
    shift_object = Shift.objects.all()
    
    if request.method == 'POST':
        form = ScheduleUpdateForm(data=request.POST)
        year = Schedule_list.year
        month = Schedule_list.month
        #Update button processing
        if form.is_valid():
            Schedule_list.shift_name_1 = form.cleaned_data['shift_name_1']
            Schedule_list.shisetsu_name_1 = form.cleaned_data['shisetsu_name_1']
            Schedule_list.shift_name_2 = form.cleaned_data['shift_name_2']
            Schedule_list.shisetsu_name_2 = form.cleaned_data['shisetsu_name_2']
            Schedule_list.shift_name_3 = form.cleaned_data['shift_name_3']
            Schedule_list.shisetsu_name_3 = form.cleaned_data['shisetsu_name_3']
            Schedule_list.shift_name_4 = form.cleaned_data['shift_name_4']
            Schedule_list.shisetsu_name_4 = form.cleaned_data['shisetsu_name_4']
            #Update button
            if "updatebutton" in request.POST:
                Schedule_list.day_total_worktime = form.cleaned_data['day_total_worktime']
            #Calculate from shift and update button
            elif "sumupdatebutton" in request.POST:
                #Calculate total daily work hours from shifts
                sum_work_time = 0
                for shift in shift_object:
                    if str(form.cleaned_data['shift_name_1']) == str(shift.name):
                        sum_work_time = shift.wrok_time + sum_work_time
                    if str(form.cleaned_data['shift_name_2']) == str(shift.name):
                        sum_work_time = shift.wrok_time + sum_work_time
                    if str(form.cleaned_data['shift_name_3']) == str(shift.name):
                        sum_work_time = shift.wrok_time + sum_work_time
                    if str(form.cleaned_data['shift_name_4']) == str(shift.name):
                        sum_work_time = shift.wrok_time + sum_work_time
                
                Schedule_list.day_total_worktime = sum_work_time
        Schedule_list.save()
        return HttpResponseRedirect('/schedule/monthschedule/%s/%s/' % (year,month,))       
    else:
        item = {
            "shift_name_1":Schedule_list.shift_name_1,
            "shisetsu_name_1": Schedule_list.shisetsu_name_1,
            "shift_name_2": Schedule_list.shift_name_2,
            "shisetsu_name_2": Schedule_list.shisetsu_name_2,
            "shift_name_3": Schedule_list.shift_name_3,
            "shisetsu_name_3": Schedule_list.shisetsu_name_3,
            "shift_name_4": Schedule_list.shift_name_4,
            "shisetsu_name_4": Schedule_list.shisetsu_name_4,
            "day_total_worktime": Schedule_list.day_total_worktime,
            }
        form = ScheduleUpdateForm(initial=item)
        context = {
            'form' : form,
            'Schedule_list': Schedule_list,
            'User_list': User_list,
            'shift_object': shift_object,
        }
        return render(request,'schedule/update.html', context )

def schedulecreatefunc(request,year_num,month_num):
    year, month = int(year_num), int(month_num)
    #Delete all schedules of the target year and month
    Schedule.objects.filter(year = year, month = month).delete()
    #Get the number of days in the shift range
    enddate = datetime.date(year,month,20)
    startdate = enddate + relativedelta(months=-1)
    #Extract the hope of the target period from the desired shift
    kiboushift_list = KibouShift.objects.filter(date__range=[startdate, enddate])
    kiboushift_list = list(kiboushift_list)
    shift_list = Shift.objects.all()
    
    #Reflect the desired shift
    for kibou in kiboushift_list:
        sum_work_time = 0
        for shift in shift_list:
                if str(kibou.shift_name_1) == str(shift.name):
                    sum_work_time = shift.wrok_time + sum_work_time
                if str(kibou.shift_name_2) == str(shift.name):
                    sum_work_time = shift.wrok_time + sum_work_time
                if str(kibou.shift_name_3) == str(shift.name):
                    sum_work_time = shift.wrok_time + sum_work_time
                if str(kibou.shift_name_4) == str(shift.name):
                    sum_work_time = shift.wrok_time + sum_work_time
        new_object = Schedule(
            user = kibou.user,
            date = kibou.date, 
            year = year,
            month = month,
            shift_name_1 = kibou.shift_name_1, 
            shisetsu_name_1 = kibou.shisetsu_name_1,
            shift_name_2 = kibou.shift_name_2, 
            shisetsu_name_2 = kibou.shisetsu_name_2,
            shift_name_3 = kibou.shift_name_3, 
            shisetsu_name_3 = kibou.shisetsu_name_3,
            shift_name_4 = kibou.shift_name_4, 
            shisetsu_name_4 = kibou.shisetsu_name_4,
            day_total_worktime = sum_work_time,
            )
        new_object.save()
    
    #Create other than desired shift
    user_list = User.objects.all()
    #Get the number of days in the shift range
    enddate = datetime.date(year,month,20)
    startdate = enddate + relativedelta(months=-1)
    kaisu = enddate - startdate
    kaisu = int(kaisu.days) 
    #last month
    if month != 1 :
        zengetsu = month - 1
    else:
        zengetsu = 12
        year = year - 1
    #Process for each user
    for user in user_list:
        kongetsu_list = Schedule.objects.filter(year = year, month = month, user = user.id).order_by('date')
        zengetsu_list = Schedule.objects.filter(year = year, month = zengetsu, user = user.id).order_by('date')
        sakusei_date = startdate
        shift_list = Shift.objects.all()
        for new_shift in range(kaisu):
            sakusei_date = sakusei_date + timedelta(days=1)
            if kongetsu_list.filter(user = user.id, date = sakusei_date).exists():
                print("ok")                       
            else:
                hukushadate = sakusei_date + relativedelta(months=-1)
                hukusha_list = zengetsu_list.filter(date = hukushadate, user = user.id)
                if zengetsu_list.filter(date = hukushadate, user = user.id).exists():
                    for hukusha in hukusha_list:
                    #Calculate total daily work hours from shifts
                        sum_work_time = 0
                        for shift in shift_list:
                            if str(hukusha.shift_name_1) == str(shift.name):
                                sum_work_time = shift.wrok_time + sum_work_time
                            if str(hukusha.shift_name_2) == str(shift.name):
                                sum_work_time = shift.wrok_time + sum_work_time
                            if str(hukusha.shift_name_3) == str(shift.name):
                                sum_work_time = shift.wrok_time + sum_work_time
                            if str(hukusha.shift_name_4) == str(shift.name):
                                sum_work_time = shift.wrok_time + sum_work_time

                        new_object=Schedule(
                            user = hukusha.user,
                            date = sakusei_date,
                            year = year,
                            month = month,
                            shift_name_1 = hukusha.shift_name_1, 
                            shisetsu_name_1 = hukusha.shisetsu_name_1,
                            shift_name_2 = hukusha.shift_name_2, 
                            shisetsu_name_2 = hukusha.shisetsu_name_2,
                            shift_name_3 = hukusha.shift_name_3, 
                            shisetsu_name_3 = hukusha.shisetsu_name_3,
                            shift_name_4 = hukusha.shift_name_4, 
                            shisetsu_name_4 = hukusha.shisetsu_name_4,
                            day_total_worktime = sum_work_time,
                            )
                        new_object.save()
                else:
                    useradd = User.objects.get(id=user.id)
                    shiftadd = Shift.objects.get(id=2)
                    new_object=Schedule(
                    user = useradd,
                    date = sakusei_date,
                    year = year,
                    month = month,
                    shift_name_1 = shiftadd, 
                    shisetsu_name_1 = None,
                    shift_name_2 = None, 
                    shisetsu_name_2 = None,
                    shift_name_3 = None, 
                    shisetsu_name_3 = None,
                    shift_name_4 = None, 
                    shisetsu_name_4 = None,
                    day_total_worktime = 0,
                    )
                    new_object.save()
    return HttpResponseRedirect('/schedule/monthschedule/%s/%s/' % (year,month,))
            
def kiboulistfunc(request):
    KibouShift_list = KibouShift.objects.all().order_by('-date')
    User_list = User.objects.all()
    shift_object = Shift.objects.all()
    context = {
        'KibouShift_list': KibouShift_list,
        'User_list': User_list,
        'shift_object': shift_object,
        }

    return render(request,'schedule/kiboushift/list.html', context )
        
class KibouCreate(CreateView):
    template_name = 'schedule/kiboushift/create.html'
    model = KibouShift
    fields = ('user', 'date', 'shift_name_1', 'shisetsu_name_1', 'shift_name_2', 'shisetsu_name_2', 'shift_name_3', 'shisetsu_name_3', 'shift_name_4', 'shisetsu_name_4')
    success_url = reverse_lazy('schedule:KibouList')

class KibouUpdate(UpdateView):
    template_name = 'schedule/kiboushift/update.html'
    model = KibouShift
    fields = ('user', 'date', 'shift_name_1', 'shisetsu_name_1', 'shift_name_2', 'shisetsu_name_2', 'shift_name_3', 'shisetsu_name_3', 'shift_name_4', 'shisetsu_name_4')
    success_url = reverse_lazy('schedule:KibouList')

class KibouDelete(DeleteView):
    template_name = 'schedule/kiboushift/delete.html'
    model = KibouShift
    fields = ('user', 'date', 'shift_name_1', 'shisetsu_name_1', 'shift_name_2', 'shisetsu_name_2', 'shift_name_3', 'shisetsu_name_3', 'shift_name_4', 'shisetsu_name_4')
    success_url = reverse_lazy('schedule:KibouList')

This completes the creation function. After creating the desired shift data, the other days are created on the same day of the previous month.

I wanted to call the same process (calculate working hours from the shift name) with a function and return the value, but I don't know yet, so I wrote them separately. From now on, I would like to remember that and keep the code shorter.

image.png

If there is no previous month, I try to create it during the holidays.

Next, we may have to step into the still unknown world of css and js ... (laughs) Actually, nearly 20 people are registered, so when you display the whole, it is difficult to see unless you fix the header of the table ... Like this

image.png

It will be a shift of some day ...

I want to change it so that it is easy to see on my smartphone. I don't know if smartphone support is still possible, but I would like to implement fixed display.

Recommended Posts

Django shift table shift data creation function completed
django table creation
Django Python shift table
Django shift creation feature
Django Tutorial (Blog App Creation) ⑤ --Article Creation Function
Edit Django shift table HTML and CSS
Added a function to register desired shifts in the Django shift table
Django shift creation function Added basic work shift registration function for days of the week
Display the Django shift table! Supports 20-day closing
I want to scroll the Django shift table, but ...
[Django] Perform Truncate Table (delete all data in the table)
[Django] Added new question creation function to polls app