[PYTHON] Web App Development Practice: Create a Shift Creation Page with Django! (Authentication system processing)

It's been a while since previous post, but I'll continue.

Actually, the work itself has proceeded quite freely and it seems that I was not just posting, so from this time on, let's take a small amount of them.

First of all, lightly, from the processing of the authentication system. Implemented by referring to Past posts I did.

owner/views.py

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


def log_in(req):

	if req.user.is_authenticated():
		return redirect('/')  #If authenticated, redirect to the top page (not touched this time)

	error_msg = ""  #Define an error message and bring it to the template

	if req.method == 'POST':
		posted = req.POST
		name,password = posted['name'],posted['password']

		user = authenticate(username=name,password=password)

		if user is not None:
			if user.is_active:
				login(req,user)

				return redirect('/')
			else:
				error_msg = "This account is not active..."
		else:
			error_msg = "Log in failed...."
				
	return render(req,'owner/log_in.html',{'error_msg':error_msg}) 


def log_out(req):
	logout(req)

	return redirect('/login/')  #After logging out, return to the login screen


def new_owner(req):  #A page to create a new User. I'm the owner of the shift

	error_msg = ""

	if req.method == 'POST':
		posted = req.POST
		name,password = posted['name'],posted['password']

		if password != posted['pass_check']:  #Check your password by typing twice as is often the case
			error_msg = "Password check is failed!"
		else:
			if len(password) < 6:  #Password must be at least 6 characters
				error_msg = "Password need over 6 letters!"
			else:
				from django.db import IntegrityError
				from django.contrib.auth.models import User
				try:
					owner = User.objects.create_user(username=name,password=password)
					return redirect('/')
				except IntegrityError:  #If the user name is already used, this error will be thrown, so take measures
					error_msg = "You can not use this name!"

	return render(req,'owner/new_owner.html',{'error_msg':error_msg,})


@login_required  #A convenient decorator for logging in (LOGIN in settings)_You need to set the URL. After that, you can put your login page at that URL (OK)
def edit_groupschedule(req):  #It feels like deciding the shift setting, so it may be easier to understand if you use shift setting
	from django.contrib.auth.models import Group
	from owner.models import GroupSchedule
	
	try:  #If the accessing user does not have a Group Schedule yet, create a new one, if it already has one, edit it.
		groupschedule = GroupSchedule.objects.get(owner=req.user)
		group = groupschedule.group
	except GroupSchedule.DoesNotExist:
		groupschedule = GroupSchedule(owner=req.user)
		group = Group()

	if req.method == 'POST':
		posted = req.POST

		group.name = posted['name']
		group.save()

		groupschedule.group = group
		groupschedule.start_point = int(posted['start_point'])
		groupschedule.save()

		return redirect('/')  #Jump to the top after saving

	return render(req,'owner/edit_groupschedule.html',{
		'group_name':group.name,
		'start_point':groupschedule.start_point,
		'select_choices':(1,5,10,15,20,25,),  #Candidates for monthly shift start dates
	})

Next is the template. I'm using Bootstrap, but it's a bit annoying to write `<div>` every time I make a form part, so the parts that are likely to be used repeatedly are ** templates / app ** Create a directory called ** parts ** below. You can then use the ** include ** template tag to pull it in. Is the image that ** extends is the foundation and include is the part **?

For example, like this.

parts/input.html

<div class="form-group">
	<label>{{ label }}
		<input type="{{ type }}" name="{{ name }}" class="form-control {{ class }}" value="{{ value }}">
	</label>
</div>

The rest should be made appropriately. Since you can put a value in each variable when reading a part, you can also add classes. In addition, I made a part for the application based on this, so I will use it.

templates/owner/log_in.html

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

{% block title %}Log in{% endblock %}

{% block form %}
<h1>Log in<small>{{ error_msg }}</small></h1>  <!--Message display if there is an error-->
	{% include 'owner/parts/name_input.html' %}
	{% include 'owner/parts/pass_input.html' %}

	{% include 'parts/submit.html' with class='btn-lg btn-primary' value='Log in!' %}  {#You can put a value in a variable with with#}
	<a href="/owner/new">Create New User</a>
{% endblock form %}

The rest is almost the same.

..../new_user.html

{% extends 'owner/bases/base_form.html' %}

{% block title %}new Owner!{% endblock %}

{% block form %}
<h1>new Owner!<small>{{ error_msg }}</small></h1>
	{% include 'owner/parts/name_input.html' %}
	{% include 'owner/parts/pass_input.html' %}
	{% include 'owner/parts/pass_input2.html' %}

	{% include 'parts/submit.html' with value="Create new owner!" %}
{% endblock form %}

..../edit_groupschedule.html

{% extends 'owner/bases/base_form.html' %}

{% block title %}new Schedule!{% endblock %}

{% block form %}
	{% include 'owner/parts/name_input.html' with value=group_name %}  {#initial value. views.Feeling to pass the variables brought from py to the parts#}
	{% include 'owner/parts/select_number.html' with start_point=start_point select_choices=select_choices %}  {#Candidates for selection#}
	{% include 'owner/parts/submit.html' with value='Create your Schedule!' %}
{% endblock form %}

It doesn't matter if it doesn't matter, but when I left a blank, I realized how difficult it was to understand my code (some classes and function names don't make sense). It's embarrassing, so I don't feel like posting so much, and if I think "OK" and proceed on my own, it will become more and more messy. I'll post up to the point where I did it for the time being, but I feel that it would be better to recreate it from scratch.

Recommended Posts

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! (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! (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 Todo app with the Django REST framework
Create a Todo app with Django ⑤ Create a task editing function
Create a homepage with django
Web application creation with Django
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
Create a web app that can be easily visualized with Plotly Dash
"Trash classification by image!" App creation diary day3 ~ Web application 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 a star system with Blender 2.80 script
WEB application development using Django [Request processing]
Create your first app with Django startproject
Create a web service with Docker + Flask
I made a WEB application with Django
Try creating a web application with Vue.js and Django (Mac)-(1) Environment construction, application creation
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
Deploy a Python 3.6 / Django / Postgres web app on Azure
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! # 2 [Translation function]
[Practice] Make a Watson app with Python! # 1 [Language discrimination]
Create APIs around user authentication with Django REST Framework
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
Articles that enable system development with Django (Python) _Introduction
Create a django environment with docker-compose (MariaDB + Nginx + uWSGI)
Deploy a web app created with Streamlit to Heroku