[PYTHON] Implement the ability to reserve what happens regularly in your Django Todo list

・ Create Christmas announcements at the end of the year ・ Preparation of New Year's present ・ Financial statement preparation ・ Payroll processing ・ Disposal of incombustibles

We are creating a function that allows you to create tasks by registering tasks that occur regularly (every day, Wednesday of the second week, XX days) as a Plan and executing the creation process.

Now, I have created a task that can be done once it is registered in the master. The master registration screen seems to need various input controls, so I put it off (laugh)

The models and views look like this.

models.py


from django.db import models
from shisetsu.models import *
from accounts.models import *
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django_currentuser.db.models import CurrentUserField
from django_currentuser.middleware import (
    get_current_user, get_current_authenticated_user)
from django.core.validators import MaxValueValidator, MinValueValidator

#Create a ProxyModel,__str__()Override
class MyUser(User):
    def __str__(self):
           return '%s %s' % (self.last_name, self.first_name)

    class Meta:
        proxy = True

# Create your models here.
class TodoModel(models.Model):
    title = models.CharField(verbose_name='title', max_length=100,  null=True)
    memo = models.TextField(verbose_name='Contents', null=True)
    priority = models.CharField(
        verbose_name='priority',
        max_length=50,
        choices=(('danger','High'),('warning','During ~'),('Light','Low')),
        )
    shisetsu_name = models.ForeignKey(Shisetsu, verbose_name='Facility',on_delete=models.SET_NULL,blank=True, null=True)
    user = models.ForeignKey(MyUser, on_delete=models.CASCADE, verbose_name='Person in charge',blank=True, null=True)
    plants_startdate = models.DateField(verbose_name='Scheduled start date', blank=True, null=True)
    plants_enddate = models.DateField(verbose_name='Expected end date', blank=True, null=True)
    enddate = models.DateField(verbose_name='End date', blank=True, null=True)
    create_date = models.DateTimeField(verbose_name='Registered Date', auto_now_add=True)
    create_user = CurrentUserField(verbose_name='Registered person', editable=False, related_name='todo_create_articles')
    update_date = models.DateTimeField(verbose_name='Update date and time', auto_now=True)
    update_user = CurrentUserField(verbose_name='changer', editable=False, related_name='todo_update_articles')
    def __str__(self):
        return self.title

class Todo_PlanModel(models.Model):
    title = models.CharField(verbose_name='title', max_length=100,  null=True)
    memo = models.TextField(verbose_name='Contents', null=True)
    priority = models.CharField(
        verbose_name='priority',
        max_length=50,
        choices=(('danger','High'),('warning','During ~'),('Light','Low')),
        )
    shisetsu_name = models.ForeignKey(Shisetsu, verbose_name='Facility',on_delete=models.SET_NULL,blank=True, null=True)
    user = models.ForeignKey(MyUser, on_delete=models.CASCADE, verbose_name='Person in charge',blank=True, null=True)
    hyoujijyun = models.IntegerField(verbose_name='Display order',unique=True)
    cycle = models.CharField(
        verbose_name='period',
        max_length=50,
        choices=(('daily','every day'),('everyweek','Weekly'),('monthly','monthly'),('day','time'),('week','Weekday')),
        )
    youbi = models.CharField(
        verbose_name='Day of the week',
        max_length=10,
        blank=True,
        null=True,
        choices=(
            ('0','Month'),
            ('1','fire'),
            ('2','water'),
            ('3','wood'),
            ('4','Money'),
            ('5','soil'),
            ('6','Day')
            ),
        )
    month = models.CharField(
        verbose_name='Month',
        max_length=10,
        blank=True,
        null=True,
        choices=(
            ('1','January'),
            ('2','February'),
            ('3','March'),
            ('4','April'),
            ('5','May'),
            ('6','June'),
            ('7','July'),
            ('8','August'),
            ('9','September'),
            ('10','October'),
            ('11','November'),
            ('12','December')
            ),
        )
    week = models.IntegerField(verbose_name='Week', blank=True, null=True, validators=[MaxValueValidator(5), MinValueValidator(1)])
    day = models.IntegerField(verbose_name='date', blank=True, null=True, validators=[MaxValueValidator(31), MinValueValidator(1)])
    create_date = models.DateTimeField(verbose_name='Registered Date', auto_now_add=True)
    create_user = CurrentUserField(verbose_name='Registered person', editable=False, related_name='todo_plan_create_articles')
    update_date = models.DateTimeField(verbose_name='Update date and time', auto_now=True)
    update_user = CurrentUserField(verbose_name='changer', editable=False, related_name='todo_plan_update_articles')
    
    def __str__(self):
        return self.title

views.py


def todoplancreatefunc(request):
    if request.method == 'GET':
        return render(request,'todo/todoplancreate.html')
    else:
        yearmonth = request.POST['yearmonth']
        year = int(yearmonth[0:4])
        month= int(yearmonth[5:7])
        lastday = calendar.monthrange(year, month)[1]

        #Process the set amount every day
        todo_plan = Todo_PlanModel.objects.filter(cycle="daily").order_by("hyoujijyun")
        for todoplan in todo_plan:
            for i in range(lastday):
                sakuseiday = datetime.date(year,month,i + 1)
                new_object = TodoModel(
                    title = todoplan.title,
                    memo = todoplan.memo,
                    priority = todoplan.priority,
                    shisetsu_name = todoplan.shisetsu_name,
                    user = todoplan.user,
                    plants_startdate = sakuseiday,
                    plants_enddate = sakuseiday,
                    )
                new_object.save()

        #Process weekly
        todo_plan = Todo_PlanModel.objects.filter(cycle="everyweek").order_by("hyoujijyun")
        for todoplan in todo_plan:
            for i in range(5):
                day = get_day_of_nth_dow(year, month, i + 1, int(todoplan.youbi))
                if day != None:
                    sakuseiday = datetime.date(year, month, day)
                    new_object = TodoModel(
                        title = todoplan.title,
                        memo = todoplan.memo,
                        priority = todoplan.priority,
                        shisetsu_name = todoplan.shisetsu_name,
                        user = todoplan.user,
                        plants_startdate = sakuseiday,
                        plants_enddate = sakuseiday,
                    )
                    new_object.save()

        #Process monthly
        todo_plan = Todo_PlanModel.objects.filter(cycle="monthly").order_by("hyoujijyun")
        for todoplan in todo_plan:
            #Get the end of the target month
            lastday = calendar.monthrange(year, month)[1]
            #Replace if the specified date is greater than the date at the end of the month
            if todoplan.day > lastday:
                day = lastday
            else:
                day = todoplan.day
            sakuseiday = datetime.date(year, month, day)
            new_object = TodoModel(
                title = todoplan.title,
                memo = todoplan.memo,
                priority = todoplan.priority,
                shisetsu_name = todoplan.shisetsu_name,
                user = todoplan.user,
                plants_startdate = sakuseiday,
                plants_enddate = sakuseiday,
                )
            new_object.save()

        #Process month / date specification
        todo_plan = Todo_PlanModel.objects.filter(cycle="day").order_by("hyoujijyun")
        for todoplan in todo_plan:
            #Get the end of the target month
            lastday = calendar.monthrange(year, int(todoplan.month))[1]
            #Replace if the specified date is greater than the date at the end of the month
            if todoplan.day > lastday:
                day = lastday
            else:
                day = todoplan.day
            sakuseiday = datetime.date(year, int(todoplan.month), day)
            print(sakuseiday)
            new_object = TodoModel(
                title = todoplan.title,
                memo = todoplan.memo,
                priority = todoplan.priority,
                shisetsu_name = todoplan.shisetsu_name,
                user = todoplan.user,
                plants_startdate = sakuseiday,
                plants_enddate = sakuseiday,
                )
            new_object.save()

        #Designated on weekdays
        todo_plan = Todo_PlanModel.objects.filter(cycle="week").order_by("hyoujijyun")
        for todoplan in todo_plan:
            day = get_day_of_nth_dow(year, month, todoplan.week, int(todoplan.youbi))
            if day == None:
                day = lastday = calendar.monthrange(year, month)[1]
            sakuseiday = datetime.date(year, month, day)
            new_object = TodoModel(
                title = todoplan.title,
                memo = todoplan.memo,
                priority = todoplan.priority,
                shisetsu_name = todoplan.shisetsu_name,
                user = todoplan.user,
                plants_startdate = sakuseiday,
                plants_enddate = sakuseiday,
            )
            new_object.save()        


        messages = 'Processing is finished'

        context = {
            'messages': messages,
            }
        return render(request,'todo/todoplancreate.html', context)

This would access the database a lot, so I'd like to improve it, but I'm a little reluctant to modify what works. The cause is that I made it while watching the processing work correctly one by one ... First of all, I made it with the feeling that every day would work, so it is the result of thinking one by one (laugh)

First of all, I think that it is ideal to change the form that gets everything from the Plan table in order, add it to the object if possible, and finally save it at once.

Register the master.

image.png

Before creating a recurring task

image.png

I deleted all the records so there is nothing left

image.png

Execute the process on the creation screen

image.png

image.png

The task was created as the second Thursday of November!

Recommended Posts

Implement the ability to reserve what happens regularly in your Django Todo list
How to implement Rails helper-like functionality in Django
How to run some script regularly in Django
Specify the view URL in your Django template
How to find the first element that matches your criteria in a Python list
Set the form DateField to type = date in Django
[Python] How to output the list values in order
Steps to change table and column names in your Django model at the same time
Create Django Todo list
How to write custom validations in the Django REST Framework
Set the DateTime type output format in your Django template
How to generate a query using the IN operator in Django
How to get the last (last) value in a list in Python
Display the time in Django according to the user's region (UTC)
I tried to implement the mail sending function in Python
I can't log in to the admin page with Django3
What to do when "Invalid HTTP_HOST header" appears in Django
I want to make the Dictionary type in the List unique
In Django, how to abbreviate the long displayed string as ....
Implement an add form button in your Django inline form set
The problem with having to specify SameSite = None in chrome80, what are all django users doing?