[PYTHON] Transit to the update screen with the Django a tag

We will implement transitioning from the schedule being edited to the update screen and returning to the variant screen.

First of all, I will link with the time of the day in the schedule table as the a tag

schedule/month.html


{% extends 'schedule/base.html' %}
{% block header %}
{% endblock header %}

{% block content %}
<table class="table table-striped table-bordered">
<thead>
    <tr align="center" class="info">    <!--date-->
        <th rowspan="2"></th>
        {% for item in calender_object %}
                <th class="day_{{ item.date }}">{{ item.date | date:"d" }}</th>
        {% endfor %}
    <tr align="center" class="info">   <!--Day of the week-->
        {% for item in youbi_object %}
            <th class="day_{{ item.date }}">{{ item }}</th>
        {% endfor %}
    </tr>
</thead>
<tbody>
{% for staff in user_list %}
    <tr align="center">
    <th rowspan="1" class="staff_name" staff_id="{{ staff.staff_id }}" width="200" >{{ staff.last_name }} {{ staff.first_name }}</th>  <!--staff_id element used in js-->
            {% for item in object_list %} 
                {% if item.user|stringformat:"s" == staff.username|stringformat:"s" %}<!--If the username is the same-->
                    <td class="day" id="s{{ staff.id }}d{{ item.date }}"> 
                        {% if item.shift_name_1 != None %}
                            {% if item.shift_name_1|stringformat:"s" == "Yes" or item.shift_name_1|stringformat:"s" == "Closed" %}
                                {{ item.shift_name_1 }}
                            {% else %}
                                {% for shisetsu in shisetsu_object %}
                                    {% if item.shisetsu_name_1|stringformat:"s" == shisetsu.name|stringformat:"s" %}                          
                                        <span style="background-color:{{ shisetsu.color }}">{{ item.shift_name_1 }}</span>
                                    {% endif %}
                                {% endfor %} 
                            {% endif %}    
                        {% endif %}
                {% if item.shift_name_2 != None %}
                    {% if item.shift_name_2|stringformat:"s" == "Yes" or item.shift_name_2|stringformat:"s" == "Closed" %}
                        {{ item.shift_name_2 }}
                    {% else %}
                        {% for shisetsu in shisetsu_object %}
                            {% if item.shisetsu_name_2|stringformat:"s" == shisetsu.name|stringformat:"s" %}                          
                                    <span style="background-color:{{ shisetsu.color }}">{{ item.shift_name_2 }}</span>
                            {% endif %}
                        {% endfor %} 
                    {% endif %}    
                {% endif %}
                {% if item.shift_name_3 != None %}
                    {% if item.shift_name_3|stringformat:"s" == "Yes" or item.shift_name_3|stringformat:"s" == "Closed" %}
                        {{ item.shift_name_3 }}
                    {% else %}
                        {% for shisetsu in shisetsu_object %}
                            {% if item.shisetsu_name_3|stringformat:"s" == shisetsu.name|stringformat:"s" %}                          
                                <span style="background-color:{{ shisetsu.color }}">{{ item.shift_name_3 }}</span>
                            {% endif %}
                        {% endfor %} 
                    {% endif %}    
                {% endif %}
                {% if item.shift_name_4 != None %}
                    {% if item.shift_name_4|stringformat:"s" == "Yes" or item.shift_name_4|stringformat:"s" == "Closed" %}
                        {{ item.shift_name_4 }}
                    {% else %}
                        {% for shisetsu in shisetsu_object %}
                            {% if item.shisetsu_name_4|stringformat:"s" == shisetsu.name|stringformat:"s" %}                          
                                <span style="background-color:{{ shisetsu.color }}">{{ item.shift_name_4 }}</span>
                            {% endif %}
                        {% endfor %} 
                    {% endif %}    
                {% endif %}                   
            {% endif %}            
        {% endfor %}
        </td>

        <tr align="center">
            {% for month in month_total %} 
                {% if month.user ==  staff.id %}<!--If the username is the same-->
                    <td><b>{{ month.month_total_worktime }}</b></td>
                {% endif %}
            {% endfor %}
            {% for item in object_list %} 
                {% if item.user|stringformat:"s" == staff.username|stringformat:"s" %}<!--If the username is the same-->
                    <td class="day" id="s{{ staff.id }}d{{ item.date }}">
                        <a href="{% url 'schedule:update' item.pk %}">{{ item.day_total_worktime }} </a>
                    </td>
            {% endif %}            
        {% endfor %}
    </tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}



The html is long, but I modified it by repeating the process with Saigo for. By displaying the time with the primary key in itm.pk with schedule: update with the a tag, it is now possible to transition to the edit screen for the target record.

image.png

Since it became a link, it is now displayed in light blue. Next, I also modified update.html so that I can return when I press the back button without updating from the update screen.

schedule/update.html


{% extends 'schedule/base.html' %}

{% block header %}
{% endblock header %}

{% block content %}
<form action="" method="POST">{% csrf_token %}
    <P >Employee name: {{ User_list.last_name }} {{ User_list.first_name }}</P>
    <p>date: {{ Schedule_list.date }}</p>
    {{ form.as_p }}
    {% csrf_token %}
    <input class="btn btn-primary" type="submit" value="update">
    <a href="{% url 'schedule:monthschedule' Schedule_list.year Schedule_list.month %}" class="btn-secondary btn active">Return</a>
</form>
{% endblock content %}

Now that the basics of editing are complete, I'd like to implement a function to create the next month, such as when there is still little information when people see it, or to calculate the total from shift symbols.

As I was working on it, I found that it didn't work when moving from December to January. In order to deal with this, it seems that you can easily calculate the month by installing relativedelta, so install it.

terminal


pip install python-dateutil

schedule.Viewspy


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
from django.urls import reverse_lazy
from .forms import *
from dateutil.relativedelta import relativedelta
# 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()
    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,
    }
    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
        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']
            Schedule_list.day_total_worktime = form.cleaned_data['day_total_worktime']
            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,
            }
        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 )


I did some extra things, so I fixed it a little.

Recommended Posts

Transit to the update screen with the Django a tag
Creating a login screen with Django allauth
Create an update screen with Django Updateview
Create a REST API to operate dynamodb with the Django REST Framework
The story of failing to update "calendar.day_abbr" on the admin screen of django
[Django] I made a field to enter the date with 4 digit numbers
The easiest way to get started with Django
Recreate the django staff registration screen with class
How to develop a cart app with Django
A story about implementing a login screen with django
update django version 1.11.1 to 2.2
I failed to install django with pip, so a reminder of the solution
I tried to create a table only with Django
How to create a submenu with the [Blender] plugin
Create a Todo app with the Django REST framework
Display / update the graph according to the input with PySimpleGui
Create a homepage with django
How to update with SQLAlchemy?
Create a Django login screen
Finding a solution to the N-Queen problem with a genetic algorithm (2)
I want to make a blog editor with django admin
Probably the easiest way to create a pdf with Python3
The first step to creating a serverless application with Zappa
How to generate a query using the IN operator in Django
A story about how to deal with the CORS problem
I can't log in to the admin page with Django3
The usual way to add a Kernel with Jupyter Notebook
[Python] The first step to making a game with Pyxel
DJango Memo: From the beginning (more edits to the management screen)
Finding a solution to the N-Queen problem with a genetic algorithm (1)
[Python] Create a screen for HTTP status code 403/404/500 with Django
How to register the same data multiple times with one input on the Django management screen
[Django Learned with the Devil's Blade] How to get a query set for forward / reverse reference
Steps to develop Django with VSCode
[Introduction to Python] How to split a character string with the split function
Deploy a Django application with Docker
Common html to rent with Django
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
How to make a command to read the configuration file with pyramid
Rails users try to create a simple blog engine with Django
Django Tips-Create a ranking site with Django-
Here's a brief summary of how to get started with Django
How to get started with Django
Build a web application with Django
I wanted to solve the ABC164 A ~ D problem with Python
Write a script to calculate the distance with Elasticsearch 5 system painless
Deploy the Django tutorial to IIS ①
Update applications running on Django 1.7 to Django 1.8
I compared while reading the documentation to use Jinja2 with Django
How to send a request to the DMM (FANZA) API with python
Create a file uploader with Django
How to authenticate with Django Part 2
How to authenticate with Django Part 3
Upload data to s3 of aws with a command and update it, and delete the used data (on the way)
[EC2] How to take a screen capture of your smartphone with selenium
A memo to simply use the illuminance sensor TSL2561 with Raspberry Pi 2
[Django 2.2] Add a New badge to new posts with a date using a template filter
Think about how to write a filter with the Shotgun API-Contact Versions
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
[Python] Explains how to use the range function with a concrete example
[Introduction to Python] How to sort the contents of a list efficiently with list sort