[PYTHON] Web App Development Practice: Create a Shift Creation Page with Django! (Shift creation page)

I will make the main page (By the way, my head got messed up from here and there).

By the way, the screen at the moment looks like this.

出来上がった画面

URL settings

First of all, from the URLconf settings. This time, make a URL like ** http: // shift-maker / 2014/5/15 / shift / **, incorporate the year and month numbers, and bring the numbers to the view function to connect to the data. I want to make it feel like this.

url.py

#...
month_url = r'(?P<year_num>\d+)\-(?P<month_num>\d+)'  #I had a feeling that it would be reused, so I defined it as a variable. Year and month numbers_num,month_views as num.You can take it to py.

urlpatterns += patterns('schedule.views',
    url(r'^$', 'home', name="Home"),  #By the way, I don't understand the meaning of this name attribute (although I have set it for the time being).
	url(r'^%s/shift/$' % (month_url,),'a_month_shift',name="MonthShift"),
)
#...

I set the homepage as a bonus without thinking deeply.

2. View function

When creating a monthly shift production page, you have to get the contents of the month (date, day of the week, etc.), but in Python [a convenient module called calendar](http://qiita.com/juniskw/ There are items / e2d42c2f457e4b49b8b5), so I am using it. This time, it is written as a function called get_calendar in the GroupSchedule model of owner / models.py.

schedule/views.py

from django.contrib.auth.decorators import login_required
from django.shortcuts import render,redirect


@login_required
def home(req):
	from datetime import datetime
	
	now = datetime.now()

	return redirect( '/%s-%s/shift/' % (now.year,now.month,) )  #Automatically redirect to this month's shift screen

@login_required
def a_month_shift(req,year_num,month_num):
	from owner.models import GroupSchedule
	from schedule.models import WorkTime,MonthShift,StaffSchedule,NgShift,GuestSchedule
	from datetime import date

	year,month = int(year_num),int(month_num)

	try:
		groupschedule = GroupSchedule.objects.get(owner=req.user)
	except GroupSchedule.DoesNotExist:  #If you can't set the shift
		return redirect('/owner/schedule/edit')  #To the setting screen

    monthshift,created = groupschedule.monthshift_set.get_or_create(year=year,month=month,groupschedule=req.user.groupschedule)  # get_or_create is a convenient shortcut that eliminates the need to write a try statement each time. Note that there are two left sides (what the second is is unknown at this time)

	if req.method == 'POST':
		posted = req.POST
		s_year,s_month,s_day = int(posted['year']),int(posted['month']),int(posted['day'])  # s_Because the staff schedule_Abbreviation for. Receive date information from POST data ...
		s_date = date( year=s_year,month=s_month,day=s_day )  #Variable as date object

		try:  #Whether to get the Staff Schedule from the POSTed date and staff information ...
			s_schedule = StaffSchedule.objects.get( date=s_date,staff=int(posted['staff']) )
		except StaffSchedule.DoesNotExist:  #Create if not
			from staff.models import Staff
			s_schedule = StaffSchedule(date=s_date)
			s_schedule.staff = Staff.objects.get( id=int(posted['staff']) )

		s_schedule.monthshift = monthshift

		s_schedule.worktime = WorkTime.objects.get( id=int(posted['shift']) )  #Confirm the Work Time of the Staff Schedule ...

		s_schedule.save()  #Save

	month_cal = groupschedule.get_calendar(year,month)  #Get defined in the GroupSchedule model_Get month information from calendar

	return render(req,'schedule/a_month_shift.html',{
		'year':year_num,  #Use it as it is for page titles, etc.
		'month':month_num,  #Same as above
		'month_cal':month_cal,  #Calendar information
		'monthshift':monthshift,  #I haven't used it yet
		'weekdays':['Month','fire','water','wood','Money','soil','Day',],  # 曜Dayの表示方法(デフォルトだとSundayとかになるので馴染みづらい)
		'staffs':groupschedule.staff_set.order_by('id'),
		'worktimes':groupschedule.worktime_set.order_by('id'),
	})

template

After that, write a template like that. First, I created a base for the application (but it's subtle if I needed to separate it).

templates/schedule/bases/base_a_month.html

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

{% block title %} {{ year_num }}-{{ month_num }} {% endblock %}

{% block main %}
<!--from here-->
<a href="/logout">Log out</a>
<a href="/staff/new"><button class="btn btn-success">Add New Staff</button></a>
<!--The layout is rattling because I put it in the texto so far-->

<ul class="pager">
	<li class="previous">
		{% ifnotequal month '1' %}
		<a href="/{{ year }}-{{ month|add:'-1' }}/shift">last month</a>
		{% else %}
		<a href="/{{ year|add:'-1' }}-12/shift">last month</a>
		{% endifnotequal %}
	</li>
	<li class="next">
		{% ifnotequal month '12' %}
		<a href="/{{ year }}-{{ month|add:"1" }}/shift">Next month</a>
		{% else %}
		<a href="/{{ year|add:'1' }}-1/shift">Next month</a>
		{% endifnotequal %}
	</li>
</ul>

<h1><small>{{ year }}-</small>{{ month }}</h1>	<!--Heading. What year and month?-->

<table class="table table-bordered {% block t_class %}{% endblock %}">

	{% block t_main %}
        <!--Put the main content here-->
	{% endblock %}

</table>
{% endblock main %}

And the following is the main content.

templates/schedule/a_month_shift.html

{% extends "schedule/bases/base_a_month.html"  %}

{% block title %} Shift:{{ year }}/{{ month }}-{{ month|add:1 }} {% endblock %}

{% block t_main %}
<script type="text/javascript" src="{{ STATIC_URL }}js/a_month_shift.js"></script>
<link type="text/css" rel="stylesheet" href="{{ STATIC_URL }}css/a_month_shift.css">  <!--I haven't made it at the moment-->
				
	{% load schedule_controler %}  {#Loading your own filter#}

<thead>
	<tr align="center" class="info">	<!--date-->
		<th rowspan="2"></th>
	{% for cal in month_cal %}  {#Display calendar day by day#}
		<th class="day_{{ cal.day }}">{{ cal.day }}</th>
	{% endfor %}

	{% for worktime in worktimes %}  {#Display registered WorkTimes one by one (Heading for statistics for each working hour)#}
		<th rowspan="2">{{ worktime.title }}</th>
	{% endfor %}
	</tr>

	<tr class="info">	<!--Day of the week-->
	{% for cal in month_cal %}

		<th class="day_{{ cal.day }}">{{ weekdays|index_is:cal.weekday }}</th>  {# index_is a self-made filter#}

	{% endfor %}
	</tr>
</thead>
<tbody>
	{% for staff in staffs %}
	<tr align="center">
		<th class="info" staff_id="{{ staff.id }}">{{ staff }}</th>  <!--staff_id element used in js-->
		{% for cal in month_cal %}
		<td class="day_{{ cal.day }}" id="s{{ staff.id }}d{{ cal.day }}">
			{% include 'schedule/parts/dropdown.html' %}  {#Since the WorkTime selection part in the dropdown is created as a part in a separate file, it feels like reading it here#}
		</td>
		{% endfor %}

		{% for worktime in worktimes %}
		<td>
			{% with staff.staffschedule_set|worktime_filter:worktime as worktime_set %}  {# worktime_With filter ...#}
				{% with worktime_set|monthshift_filter:monthshift as month_worktime_set %}  {# monthshift_I also made my own filter#}
					{{ month_worktime_set.count }}  {#count is a built-in convenience method, used here for statistics by WorkTime.#}
				{% endwith %}
			{% endwith %}
		</td>
		{% endfor %}
	</tr>

	{% endfor %}
</tbody>
{% endblock t_main %}

I use my own filter in some places, but this can be called by creating a new directory called ** templatetags ** directly under the application directory and creating it there. Reference: http://docs.djangoproject.jp/en/latest/howto/custom-template-tags.html

** schedule_controler.py **, ** a_month_shift.js **, ** dropdown.html **, etc. that wrote those self-made filters are likely to be long, so I will try it next time.

Recommended Posts

Web App Development Practice: Create a Shift Creation Page with Django! (Shift creation page)
Web App Development Practice: Create a Shift Creation Page with Django! (Introduction)
Web App Development Practice: Create a Shift Creation Page with Django! (Write a base template)
Web App Development Practice: Create a Shift Creation Page with Django! (Authentication system processing)
Web App Development Practice: Create a Shift Creation Page with Django! (Experiment on admin page)
Web App Development Practice: Create a Shift Creation Page with Django! (Design of database model)
Create a Todo app with Django ③ Create a task list page
Create a simple web app with flask
Create a Todo app with Django ④ Implement folder and task creation functions
Create a Todo app with Django REST Framework + Angular
Create a homepage with django
Create a Todo app with the Django REST framework
Web application creation with Django
Create a Todo app with Django ⑤ Create a task editing function
Create a web API that can deliver images with Django
Create a Todo app with Django ① Build an environment with Docker
Build a web application with Django
Create a file uploader with Django
Play like a web app with ipywidgets
Create a GUI app with Python's Tkinter
Daemonize a Python web app with Supervisor
Create your first app with Django startproject
Create a web service with Docker + Flask
I made a WEB application with Django
"Trash classification by image!" App creation diary day3 ~ Web application with Django ~
Django Tutorial (Blog App Creation) ① --Preparation, Top Page Creation
How to develop a cart app with Django
WEB application development using Django [Admin screen creation]
Create a PDF file with a random page size
Create a page that loads infinitely with python
[Python] Build a Django development environment with Docker
Create a dashboard for Network devices with Django!
Build a Django development environment with Doker Toolbox
Create a new page in confluence with Python
How to create a multi-platform app with kivy
Create a one-file hello world application with django
Until you create a new app in Django
Extract data from a web page with Python
Try creating a web application with Vue.js and Django (Mac)-(1) Environment construction, application creation
Deploy a Python 3.6 / Django / Postgres web app on Azure
Development digest with Django
Create a Django schedule
I tried to create a table only with Django
Looking back on creating a web service with Django 1
What is a dog? Django App Creation Start Volume--startapp
Create a native GUI app with Py2app and Tkinter
[Practice] Make a Watson app with Python! # 1 [Language discrimination]
Django shift creation feature
Create a python development environment with vagrant + ansible + fabric
Looking back on creating a web service with Django 2
What is a dog? Django App Creation Start Volume--startproject
Deploy a Django app made with PTVS on Azure
To myself as a Django beginner (1) --Create a project app--
To myself as a Django beginner (4) --Create a memo app--
Build a development environment with Poetry Django Docker Pycharm
Deploy a real-time web app with swampdragon x apache
Create a django environment with docker-compose (MariaDB + Nginx + uWSGI)
Deploy a web app created with Streamlit to Heroku
How to deploy a web app made with Flask to Heroku
[Practice] Make a Watson app with Python! # 3 [Natural language classification]
Create a web application that recognizes numbers with a neural network