<repo_name>Kazuki-AK/IKS_SHOP<file_sep>/UserLogin/forms.py
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import ( AuthenticationForm, UserCreationForm, PasswordChangeForm, PasswordResetForm, SetPasswordForm )
from .models import Shop

User = get_user_model()

class LoginForm(AuthenticationForm):
    """ログインフォーム"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = field.label  # placeholderにフィールドのラベルを入れる


class UserUpdateForm(forms.ModelForm):
    """ユーザー情報更新フォーム"""

    class Meta:
        model = User
        fields = ('email',
                  'last_name_representative', 'first_name_representative', 'last_name_representative_kana', 'first_name_representative_kana',
                  'last_name_manager', 'first_name_manager', 'last_name_manager_kana', 'first_name_manager_kana',
                  'tel', 'remarks',)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'


class ShopUpdateForm(forms.ModelForm):
    """ショップ情報更新フォーム"""

    class Meta:
        model = Shop
        fields = ( 'shop_name', 'manager_name', 'email','tel_shop', 'website',
                   'zip_code', 'address1', 'address2', 'address3', 'address4', 'address5',
                   'station1', 'station1_time', 'station2', 'station2_time', 'station3', 'station3_time',
                   'price_basic', 'wheelchair', 'visually', 'hearing', 
                   'remarks_shop', )

        widgets = {
            'zip_code':
            forms.TextInput(
                #attrsでp-postal-codeを指定
                attrs={'class': 'p-postal-code','placeholder': '記入例：8900053',},
            ),
            'address1': forms.TextInput(
                #attrsでp-region/p-region-idを指定
                #attrs={'class': 'p-region','placeholder': '記入例：鹿児島県'},
                attrs={'class': 'p-region-id','placeholder': '記入例：鹿児島県'},
            ),
            'address2': forms.TextInput(
                #attrsでp-locality p-street-address p-extended-addressを指定
                attrs={'class': 'p-locality', 'placeholder': '記入例：鹿児島市'}, 
            ),
            'address3': forms.TextInput(
                #attrsでp-locality p-street-address p-extended-addressを指定
                attrs={'class': 'p-street-address', 'placeholder': '記入例：中央町１０丁目'}, 
            ),
            'address4': forms.TextInput(
                #attrsでp-locality p-street-address p-extended-addressを指定
                attrs={'class': 'p-extended-address', 'placeholder': '記入例：３３－４'}, 
            ),
            'address5': forms.TextInput(
                attrs={'class': '','placeholder': '記入例：トリマビル'},
            ),
            }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'
        self.fields['zip_code'].widget.attrs['class'] = 'form-control p-postal-code'
        self.fields['address1'].widget.attrs['class'] = 'form-control p-region'
        self.fields['address2'].widget.attrs['class'] = 'form-control p-locality'
        self.fields['address3'].widget.attrs['class'] = 'form-control p-street-address'
        self.fields['address4'].widget.attrs['class'] = 'form-control p-extended-address'


class TimeUpdateForm(forms.ModelForm):
    """ユーザー情報更新フォーム"""

    class Meta:
        model = Shop
        fields = ('is_holiday_sunday', 'is_holiday_monday', 'is_holiday_tuesday', 'is_holiday_wednesday', 'is_holiday_thursday', 'is_holiday_friday', 'is_holiday_saturday',
                  'time_open_sunday1', 'time_close_sunday1', 'time_open_sunday2', 'time_close_sunday2',
                  'time_open_monday1', 'time_close_monday1', 'time_open_monday2', 'time_close_monday2',
                  'time_open_tuesday1', 'time_close_tuesday1', 'time_open_tuesday2', 'time_close_tuesday2',
                  'time_open_wednesday1', 'time_close_wednesday1', 'time_open_wednesday2', 'time_close_wednesday2',
                  'time_open_thursday1', 'time_close_thursday1', 'time_open_thursday2', 'time_close_thursday2',
                  'time_open_friday1', 'time_close_friday1', 'time_open_friday2', 'time_close_friday2',
                  'time_open_saturday1', 'time_close_saturday1', 'time_open_saturday2', 'time_close_saturday2', )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'
            self.fields['time_open_sunday1'].widget.attrs['class'] = 'form-control sunday'
            self.fields['time_close_sunday1'].widget.attrs['class'] = 'form-control sunday'
            self.fields['time_open_sunday2'].widget.attrs['class'] = 'form-control sunday'
            self.fields['time_close_sunday2'].widget.attrs['class'] = 'form-control sunday'
            
            self.fields['time_open_monday1'].widget.attrs['class'] = 'form-control monday'
            self.fields['time_close_monday1'].widget.attrs['class'] = 'form-control monday'
            self.fields['time_open_monday2'].widget.attrs['class'] = 'form-control monday'
            self.fields['time_close_monday2'].widget.attrs['class'] = 'form-control monday'
            
            self.fields['time_open_tuesday1'].widget.attrs['class'] = 'form-control tuesday'
            self.fields['time_close_tuesday1'].widget.attrs['class'] = 'form-control tuesday'
            self.fields['time_open_tuesday2'].widget.attrs['class'] = 'form-control tuesday'
            self.fields['time_close_tuesday2'].widget.attrs['class'] = 'form-control tuesday'
            
            self.fields['time_open_wednesday1'].widget.attrs['class'] = 'form-control wednesday'
            self.fields['time_close_wednesday1'].widget.attrs['class'] = 'form-control wednesday'
            self.fields['time_open_wednesday2'].widget.attrs['class'] = 'form-control wednesday'
            self.fields['time_close_wednesday2'].widget.attrs['class'] = 'form-control wednesday'

            self.fields['time_open_thursday1'].widget.attrs['class'] = 'form-control thursday'
            self.fields['time_close_thursday1'].widget.attrs['class'] = 'form-control thursday'
            self.fields['time_open_thursday2'].widget.attrs['class'] = 'form-control thursday'
            self.fields['time_close_thursday2'].widget.attrs['class'] = 'form-control thursday'

            self.fields['time_open_friday1'].widget.attrs['class'] = 'form-control friday'
            self.fields['time_close_friday1'].widget.attrs['class'] = 'form-control friday'
            self.fields['time_open_friday2'].widget.attrs['class'] = 'form-control friday'
            self.fields['time_close_friday2'].widget.attrs['class'] = 'form-control friday'

            self.fields['time_open_saturday1'].widget.attrs['class'] = 'form-control saturday'
            self.fields['time_close_saturday1'].widget.attrs['class'] = 'form-control saturday'
            self.fields['time_open_saturday2'].widget.attrs['class'] = 'form-control saturday'
            self.fields['time_close_saturday2'].widget.attrs['class'] = 'form-control saturday'


class UserCreateForm(UserCreationForm):
    """ユーザー登録用フォーム"""

    class Meta:
        model = User
        fields = ('email',)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'

    def clean_email(self):
        email = self.cleaned_data['email']
        User.objects.filter(email=email, is_active=False).delete()
        return email


class MyPasswordChangeForm(PasswordChangeForm):
    """パスワード変更フォーム"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'


class MyPasswordResetForm(PasswordResetForm):
    """パスワード忘れたときのフォーム"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'

class MySetPasswordForm(SetPasswordForm):
    """パスワード再設定用フォーム(パスワード忘れて再設定)"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'


class EmailChangeForm(forms.ModelForm):
    """メールアドレス変更フォーム"""

    class Meta:
        model = User
        fields = ('email',)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'

    def clean_email(self):
        email = self.cleaned_data['email']
        User.objects.filter(email=email, is_active=False).delete()
        return email<file_sep>/UserLogin/urls.py
from django.urls import path
from django.conf.urls import include, url
from django.contrib.auth import views as auth_views
from . import views

app_name = 'UserLogin'

urlpatterns = [
    path('', views.Top.as_view(), name='top'),
    path('login/', views.Login.as_view(), name='login'),
    path('logout/', views.Logout.as_view(), name='logout'),
    
    path('user_detail/<int:pk>/', views.UserDetail.as_view(), name='user_detail'),
    path('user_update/<int:pk>/', views.UserUpdate.as_view(), name='user_update'),

    path('shop_detail/<int:pk>/', views.ShopDetail.as_view(), name='shop_detail'),
    path('shop_update/<int:pk>/', views.ShopUpdate.as_view(), name='shop_update'),

    path('time_detail/<int:pk>/', views.TimeDetail.as_view(), name='time_detail'),
    path('time_update/<int:pk>/', views.TimeUpdate.as_view(), name='time_update'),

    path('user_create/', views.UserCreate.as_view(), name='user_create'),
    path('user_create/done', views.UserCreateDone.as_view(), name='user_create_done'),
    path('user_create/complete/<token>/', views.UserCreateComplete.as_view(), name='user_create_complete'),

    path('password_change/', views.PasswordChange.as_view(), name='password_change'),
    path('password_change/done/', views.PasswordChangeDone.as_view(), name='password_change_done'),
    
    path('password_reset/', views.PasswordReset.as_view(), name='password_reset'),
    path('password_reset/done/', views.PasswordResetDone.as_view(), name='password_reset_done'),
    path('password_reset/confirm/<uidb64>/<token>/', views.PasswordResetConfirm.as_view(), name='password_reset_confirm'),
    path('password_reset/complete/', views.PasswordResetComplete.as_view(), name='password_reset_complete'),

    path('email/change/', views.EmailChange.as_view(), name='email_change'),
    path('email/change/done/', views.EmailChangeDone.as_view(), name='email_change_done'),
    path('email/change/complete/<str:token>/', views.EmailChangeComplete.as_view(), name='email_change_complete'),

    path('<int:pk>/', views.ShopPreView.as_view(), name='shop_preview'),
]<file_sep>/Shop/views.py
from django.shortcuts import render
from django.views.generic import TemplateView

from UserLogin.models import *


# Create your views here.

class ShopView(TemplateView):
    template_name = 'shop/infomation.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        if self.request.user.is_authenticated:

            shop_id = self.request.user.shop_number

            if Shop.objects.filter( pk = shop_id ).exists():
                context['shop'] = Shop.objects.get( pk = shop_id )
            else:
                pass
        else:
            pass
        return context<file_sep>/UserLogin/migrations/0001_initial.py
# Generated by Django 2.2.24 on 2021-07-16 15:59

import UserLogin.models
from django.conf import settings
from django.db import migrations, models
import django.utils.timezone


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('auth', '0011_update_proxy_permissions'),
    ]

    operations = [
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('password', models.CharField(max_length=128, verbose_name='password')),
                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
                ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
                ('shop_number', models.PositiveSmallIntegerField(default=0, verbose_name='店舗ID')),
                ('email', models.EmailField(max_length=255, unique=True, verbose_name='メールアドレス')),
                ('first_name_representative', models.CharField(blank=True, help_text='代表者の方の「名」', max_length=30, verbose_name='代表者「名」')),
                ('last_name_representative', models.CharField(blank=True, help_text='代表者の方の「姓」', max_length=30, verbose_name='代表者「姓」')),
                ('first_name_representative_kana', models.CharField(blank=True, help_text='代表者の方の「メイ」(フリガナ)', max_length=30, verbose_name='代表者「メイ」')),
                ('last_name_representative_kana', models.CharField(blank=True, help_text='代表者の方の「セイ」(フリガナ)', max_length=30, verbose_name='代表者「セイ」')),
                ('first_name_manager', models.CharField(blank=True, help_text='管理者の方の「名」', max_length=30, verbose_name='管理者「名」')),
                ('last_name_manager', models.CharField(blank=True, help_text='管理者の方の「姓」', max_length=30, verbose_name='管理者「姓」')),
                ('first_name_manager_kana', models.CharField(blank=True, help_text='管理者の方の「メイ」(フリガナ)', max_length=30, verbose_name='管理者「メイ」')),
                ('last_name_manager_kana', models.CharField(blank=True, help_text='管理者の方の「セイ」(フリガナ)', max_length=30, verbose_name='管理者「セイ」')),
                ('tel', models.CharField(blank=True, max_length=15, verbose_name='電話番号')),
                ('remarks', models.TextField(blank=True, max_length=150, verbose_name='備考')),
                ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
                ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
                ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
                ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
                ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
            ],
            options={
                'verbose_name': '会員',
                'verbose_name_plural': '会員',
            },
            managers=[
                ('objects', UserLogin.models.CustomUserManager()),
            ],
        ),
        migrations.CreateModel(
            name='Shop',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('shop_name', models.CharField(default='SHOP', max_length=20, verbose_name='店名')),
                ('shop_name_kana', models.CharField(default='ショップ', max_length=30, verbose_name='テンメイ')),
                ('manager_name', models.CharField(default='CHIEF', max_length=15, verbose_name='管理者')),
                ('email', models.EmailField(max_length=255, verbose_name='お客様用メールアドレス')),
                ('tel_shop', models.CharField(blank=True, max_length=15, verbose_name='電話番号')),
                ('website', models.CharField(default='http://www.', max_length=100, verbose_name='サイトURL')),
                ('zip_code', models.CharField(blank=True, max_length=8, verbose_name='郵便番号')),
                ('address1', models.CharField(blank=True, max_length=40, verbose_name='都道府県')),
                ('address2', models.CharField(blank=True, max_length=40, verbose_name='市区町村')),
                ('address3', models.CharField(blank=True, max_length=40, verbose_name='丁目')),
                ('address4', models.CharField(blank=True, max_length=40, verbose_name='番地以降')),
                ('address5', models.CharField(blank=True, max_length=40, verbose_name='建物名・部屋番号等')),
                ('station1', models.CharField(blank=True, max_length=15, verbose_name='付近の駅・バス停１')),
                ('station1_time', models.PositiveSmallIntegerField(default=0, verbose_name='駅・バス停１からの所要時間')),
                ('station2', models.CharField(blank=True, max_length=15, verbose_name='付近の駅・バス停２')),
                ('station2_time', models.PositiveSmallIntegerField(default=0, verbose_name='駅・バス停２からの所要時間')),
                ('station3', models.CharField(blank=True, max_length=15, verbose_name='付近の駅・バス停３')),
                ('station3_time', models.PositiveSmallIntegerField(default=0, verbose_name='駅・バス停３からの所要時間')),
                ('is_holiday_sunday', models.BooleanField(default='False', verbose_name='日曜日')),
                ('is_holiday_monday', models.BooleanField(default='False', verbose_name='月曜日')),
                ('is_holiday_tuesday', models.BooleanField(default='False', verbose_name='火曜日')),
                ('is_holiday_wednesday', models.BooleanField(default='False', verbose_name='水曜日')),
                ('is_holiday_thursday', models.BooleanField(default='False', verbose_name='木曜日')),
                ('is_holiday_friday', models.BooleanField(default='False', verbose_name='金曜日')),
                ('is_holiday_saturday', models.BooleanField(default='False', verbose_name='土曜日')),
                ('point', models.IntegerField(default=0, verbose_name='店舗ID')),
                ('remarks_shop', models.TextField(blank=True, max_length=150, verbose_name='備考')),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('manager_account', models.ForeignKey(null=True, on_delete='models.DO_NOTHING', related_name='ManagerAccount', to=settings.AUTH_USER_MODEL, to_field='email', verbose_name='管理者アカウント')),
            ],
            options={
                'verbose_name': '店舗情報',
                'verbose_name_plural': '店舗情報',
            },
        ),
    ]
<file_sep>/templates/registration/shop_detail.html
{% extends "base.html" %}

{% block title %}
	登録情報確認ページ
{% endblock %}

{% block content %}
<table class="table">
    <tbody>
		<tr>
            <th>店名</th>
            <td>{{ shop.shop_name }}</td>
        </tr>
        <tr>
            <th>管理者</th>
            <td>{{ shop.manager_name }}</td>	
        </tr>
		<tr>
            <th>お客様用メールアドレス</th>
            <td>{{ shop.email }}</td>	
        </tr>
        <tr>
            <th>電話番号</th>
            <td>{{ shop.tel_shop }}</td>	
        </tr>
		<tr>
            <th>サイトURL</th>
            <td>{{ shop.website }}</td>	
        </tr>
        <tr>
            <th>郵便番号</th>
            <td>{{ shop.zip_code }}</td>	
        </tr>
        <tr>
            <th>都道府県</th>
            <td>{{ shop.address1 }}</td>	
        </tr>
        <tr>
            <th>市区町村</th>
            <td>{{ shop.address2 }}</td>	
        </tr>
        <tr>
            <th>丁目</th>
            <td>{{ shop.address3 }}</td>	
        </tr>
        <tr>
            <th>番地以降</th>
            <td>{{ shop.address4 }}</td>	
        </tr>
        <tr>
            <th>建物名・部屋番号等</th>
            <td>{{ shop.address5 }}</td>	
        </tr>
		<tr>
			<th>付近の駅・バス停１</th>
            <td>{{ shop.station1 }}</td>
        </tr>
		<tr>
			<th>駅・バス停１からの所要時間</th>
            <td>{{ shop.station1_time }}</td>
        </tr>
		<tr>
			<th>付近の駅・バス停２</th>
            <td>{{ shop.station2 }}</td>
        </tr>
		<tr>
			<th>駅・バス停２からの所要時間</th>
            <td>{{ shop.station2_time }}</td>
        </tr>
		<tr>
			<th>付近の駅・バス停３</th>
            <td>{{ shop.station3 }}</td>
        </tr>
		<tr>
			<th>駅・バス停３からの所要時間</th>
            <td>{{ shop.station3_time }}</td>
        </tr>
		<tr>
			<th>基本料金</th>
            <td>{{ shop.price_basic }}</td>
        </tr>
		<tr>
			<th>車イス対応</th>
            <td>{{ shop.wheelchair }}</td>
        </tr>
		<tr>
			<th>視覚障碍対応</th>
            <td>{{ shop.visually }}</td>
        </tr>
		<tr>
			<th>聴覚障碍対応</th>
            <td>{{ shop.hearing }}</td>
        </tr>
		<tr>
			<th>備考</th>
            <td>{{ shop.remarks_shop }}</td>
        </tr>
    </tbody>
        <tbody>
            {% for field in form %}
                <tr>
                    <th><label for="{{ field.id_for_label }}">{{ field.label }}</label></th>
                    <td>{{ field }} {{ field.errors }}</td>
                </tr>
            {% endfor %}
        </tbody>	
</table>
{% endblock %}<file_sep>/Shop/urls.py
from django.urls import path
from Shop.views import ShopView

app_name = 'Shop'

urlpatterns = [
    path('<int:pk>/', ShopView.as_view(), name='shop_info'),
]<file_sep>/UserLogin/migrations/0007_auto_20210718_2353.py
# Generated by Django 2.2.24 on 2021-07-18 14:53

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('UserLogin', '0006_auto_20210718_1346'),
    ]

    operations = [
        migrations.AddField(
            model_name='shop',
            name='hearing',
            field=models.IntegerField(choices=[(0, ''), (1, '可'), (2, '応相談')], default=0, verbose_name='聴覚障碍対応'),
        ),
        migrations.AddField(
            model_name='shop',
            name='price_basic',
            field=models.PositiveSmallIntegerField(default=0, verbose_name='基本料金'),
        ),
        migrations.AddField(
            model_name='shop',
            name='visually',
            field=models.IntegerField(choices=[(0, ''), (1, '可'), (2, '応相談')], default=0, verbose_name='視覚障碍対応'),
        ),
        migrations.AddField(
            model_name='shop',
            name='wheelchair',
            field=models.IntegerField(choices=[(0, ''), (1, '可'), (2, '応相談')], default=0, verbose_name='車イス対応'),
        ),
    ]
<file_sep>/IKS_Beauty_Shop/__init__.py
"""
Package for IKS_Beauty_Shop.
"""
<file_sep>/UserLogin/migrations/0008_auto_20210719_2320.py
# Generated by Django 2.2.24 on 2021-07-19 14:20

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('UserLogin', '0007_auto_20210718_2353'),
    ]

    operations = [
        migrations.AlterField(
            model_name='shop',
            name='is_holiday_sunday',
            field=models.BooleanField(default='False', help_text='sunday', verbose_name='日曜日'),
        ),
    ]
<file_sep>/Top/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView

# Create your views here.

def top(request):
  template_name = "top.html"
  return render(request,template_name)<file_sep>/UserLogin/views.py
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.views import ( LoginView, LogoutView, PasswordChangeView, PasswordChangeDoneView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView )
from django.contrib.sites.shortcuts import get_current_site
from django.core.signing import BadSignature, SignatureExpired, loads, dumps
from django.http import HttpResponse, HttpResponseBadRequest, Http404
from django.shortcuts import render, redirect, resolve_url
from django.template.loader import render_to_string
from django.urls import reverse_lazy
from django.views import generic
from django.views.generic import TemplateView
from .forms import ( LoginForm, UserCreateForm, UserUpdateForm, ShopUpdateForm, TimeUpdateForm, MyPasswordChangeForm, MyPasswordResetForm, MySetPasswordForm, EmailChangeForm )

from .models import ( User, Shop )

# Create your views here.

User = get_user_model()

class Top(generic.TemplateView):

    template_name = 'top.html'

    def get_context_data(self, **kwargs):
        # 継承元のメソッド呼び出し
        context = super().get_context_data(**kwargs)

        if self.request.user.is_authenticated:

            shop_id = self.request.user.shop_number

            if Shop.objects.filter( pk = shop_id ).exists():
                context['shop'] = Shop.objects.get( pk = shop_id ).shop_name
            else:
                context['shop'] = '未登録'
        else:
            pass
        return context


class Login(LoginView):
    """ログインページ"""
    form_class = LoginForm
    template_name = 'registration/login.html'


class Logout(LogoutView):
    """ログアウトページ"""
    template_name = 'registration/logout.html'


class OnlyYouMixin(UserPassesTestMixin):
    raise_exception = True

    def test_func(self):
        # 「ログイン中のユーザーのpkと、そのユーザー情報ページのpkが同じ」or「ログイン中のユーザーがスーパーユーザー」なら許可
        user = self.request.user
        return user.pk == self.kwargs['pk'] or user.is_superuser


class UserDetail(OnlyYouMixin, generic.DetailView):
    model = User
    template_name = 'registration/user_detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        if self.request.user.is_authenticated:

            shop_id = self.request.user.shop_number

            if Shop.objects.filter( pk = shop_id ).exists():
                context['shop'] = Shop.objects.get( pk = shop_id ).shop_name
            else:
                context['shop'] = '未登録'
        else:
            pass
        return context

class UserUpdate(OnlyYouMixin, generic.UpdateView):
    model = User
    form_class = UserUpdateForm
    template_name = 'registration/user_form.html'

    def get_success_url(self):
        return resolve_url('UserLogin:user_detail', pk=self.kwargs['pk'])


class ShopDetail(OnlyYouMixin, generic.DetailView):
    model = Shop
    template_name = 'registration/shop_detail.html'

class ShopUpdate(OnlyYouMixin, generic.UpdateView):
    model = Shop
    form_class = ShopUpdateForm
    template_name = 'registration/shop_form.html'

    def get_success_url(self):
        return resolve_url('UserLogin:shop_detail', pk=self.kwargs['pk'])


class TimeDetail(OnlyYouMixin, generic.DetailView):
    model = Shop
    template_name = 'registration/time_detail.html'

class TimeUpdate(OnlyYouMixin, generic.UpdateView):
    model = Shop
    form_class = TimeUpdateForm
    template_name = 'registration/time_form.html'

    def get_success_url(self):
        return resolve_url('UserLogin:time_detail', pk=self.kwargs['pk'])


class UserCreate(generic.CreateView):
    """ユーザー仮登録"""
    template_name = 'registration/user_create.html'
    form_class = UserCreateForm

    def form_valid(self, form):
        """仮登録と本登録用メールの発行."""
        # 仮登録と本登録の切り替えは、is_active属性を使うと簡単です。
        # 退会処理も、is_activeをFalseにするだけにしておくと捗ります。
        user = form.save(commit=False)
        user.is_active = False
        user.save()

        # アクティベーションURLの送付
        current_site = get_current_site(self.request)
        domain = current_site.domain
        context = {
            'protocol': self.request.scheme,
            'domain': domain,
            'token': dumps(user.pk),
            'user': user,
        }

        subject = render_to_string('registration/mail_template/create/subject.txt', context)
        message = render_to_string('registration/mail_template/create/message.txt', context)

        user.email_user(subject, message)
        return redirect('UserLogin:user_create_done')


class UserCreateDone(generic.TemplateView):
    """ユーザー仮登録したよ"""
    template_name = 'registration/user_create_done.html'


class UserCreateComplete(generic.TemplateView):
    """メール内URLアクセス後のユーザー本登録"""
    template_name = 'registration/user_create_complete.html'
    timeout_seconds = getattr(settings, 'ACTIVATION_TIMEOUT_SECONDS', 60*60*24)  # デフォルトでは1日以内

    def get(self, request, **kwargs):
        """tokenが正しければ本登録."""
        token = kwargs.get('token')
        try:
            user_pk = loads(token, max_age=self.timeout_seconds)

        # 期限切れ
        except SignatureExpired:
            return HttpResponseBadRequest()

        # tokenが間違っている
        except BadSignature:
            return HttpResponseBadRequest()

        # tokenは問題なし
        else:
            try:
                user = User.objects.get(pk=user_pk)
            except User.DoesNotExist:
                return HttpResponseBadRequest()
            else:
                if not user.is_active:
                    # 問題なければ本登録とする
                    user.is_active = True
                    user.save()

                    login(request, user, backend='django.contrib.auth.backends.ModelBackend')   #登録後にそのままログインする場合の処理

                    return super().get(request, **kwargs)

        return HttpResponseBadRequest()


class PasswordChange(PasswordChangeView):
    """パスワード変更ビュー"""
    form_class = MyPasswordChangeForm
    success_url = reverse_lazy('UserLogin:password_change_done')
    template_name = 'registration/password_change.html'


class PasswordChangeDone(PasswordChangeDoneView):
    """パスワード変更しました"""
    template_name = 'registration/password_change_done.html'


class PasswordReset(PasswordResetView):
    """パスワード変更用URLの送付ページ"""
    subject_template_name = 'registration/mail_template/password_reset/subject.txt'
    email_template_name = 'registration/mail_template/password_reset/message.txt'
    template_name = 'registration/password_reset_form.html'
    form_class = MyPasswordResetForm
    success_url = reverse_lazy('UserLogin:password_reset_done')


class PasswordResetDone(PasswordResetDoneView):
    """パスワード変更用URLを送りましたページ"""
    template_name = 'registration/password_reset_done.html'

class PasswordResetConfirm(PasswordResetConfirmView):
    """新パスワード入力ページ"""
    form_class = MySetPasswordForm
    success_url = reverse_lazy('UserLogin:password_reset_complete')
    template_name = 'registration/password_reset_confirm.html'

class PasswordResetComplete(PasswordResetCompleteView):
    """新パスワード設定しましたページ"""
    template_name = 'registration/password_reset_complete.html'


class EmailChange(LoginRequiredMixin, generic.FormView):
    """メールアドレスの変更"""
    template_name = 'registration/email_change_form.html'
    form_class = EmailChangeForm

    def form_valid(self, form):
        user = self.request.user
        new_email = form.cleaned_data['email']

        # URLの送付
        current_site = get_current_site(self.request)
        domain = current_site.domain
        context = {
            'protocol': 'https' if self.request.is_secure() else 'http',
            'domain': domain,
            'token': dumps(new_email),
            'user': user,
        }

        subject = render_to_string('registration/mail_template/email_change/subject.txt', context)
        message = render_to_string('registration/mail_template/email_change/message.txt', context)
        send_mail(subject, message, None, [new_email])

        return redirect('registration:email_change_done')


class EmailChangeDone(LoginRequiredMixin, generic.TemplateView):
    """メールアドレスの変更メールを送ったよ"""
    template_name = 'registration/email_change_done.html'


class EmailChangeComplete(LoginRequiredMixin, generic.TemplateView):
    """リンクを踏んだ後に呼ばれるメアド変更ビュー"""
    template_name = 'registration/email_change_complete.html'
    timeout_seconds = getattr(settings, 'ACTIVATION_TIMEOUT_SECONDS', 60*60*24)  # デフォルトでは1日以内

    def get(self, request, **kwargs):
        token = kwargs.get('token')
        try:
            new_email = loads(token, max_age=self.timeout_seconds)

        # 期限切れ
        except SignatureExpired:
            return HttpResponseBadRequest()

        # tokenが間違っている
        except BadSignature:
            return HttpResponseBadRequest()

        # tokenは問題なし
        else:
            User.objects.filter(email=new_email, is_active=False).delete()
            request.user.email = new_email
            request.user.save()
            return super().get(request, **kwargs)


class ShopPreView(TemplateView):
    template_name = 'shop/infomation.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        if self.request.user.is_authenticated:

            shop_id = self.request.user.shop_number

            if Shop.objects.filter( pk = shop_id ).exists():
                context['shop'] = Shop.objects.get( pk = shop_id )
            else:
                pass
        else:
            pass
        return context<file_sep>/UserLogin/models.py
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.base_user import ( AbstractBaseUser, BaseUserManager )
from django.contrib.auth.models import ( PermissionsMixin, UserManager )
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _


# Create your models here.

class CustomUserManager(UserManager):
    """ユーザーマネージャー"""
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Smf jki8h０９；ｍｋuperuser must have is_superuser=True.')
        return self._create_user(email, password, **extra_fields)


class User(AbstractBaseUser, PermissionsMixin):
    """カスタムユーザーモデル."""

    shop_number = models.PositiveSmallIntegerField( verbose_name='店舗ID', default=0, )

    email = models.EmailField( verbose_name='メールアドレス', max_length=255, unique=True, )

    first_name_representative = models.CharField( verbose_name='代表者「名」', max_length=30, blank=True, help_text='代表者の方の「名」' , )
    last_name_representative = models.CharField( verbose_name='代表者「姓」', max_length=30, blank=True, help_text='代表者の方の「姓」' , )
    first_name_representative_kana = models.CharField( verbose_name='代表者「メイ」', max_length=30, blank=True, help_text='代表者の方の「メイ」(フリガナ)' , )
    last_name_representative_kana = models.CharField( verbose_name='代表者「セイ」', max_length=30, blank=True, help_text='代表者の方の「セイ」(フリガナ)' , )

    first_name_manager = models.CharField( verbose_name='管理者「名」', max_length=30, blank=True, help_text='管理者の方の「名」' , )
    last_name_manager = models.CharField( verbose_name='管理者「姓」', max_length=30, blank=True, help_text='管理者の方の「姓」'  )
    first_name_manager_kana = models.CharField( verbose_name='管理者「メイ」', max_length=30, blank=True, help_text='管理者の方の「メイ」(フリガナ)' , )
    last_name_manager_kana = models.CharField( verbose_name='管理者「セイ」', max_length=30, blank=True, help_text='管理者の方の「セイ」(フリガナ)' , )

    tel = models.CharField( verbose_name='電話番号', max_length=15, blank=True, )

    remarks = models.TextField( verbose_name='備考', max_length=150, blank=True, )


    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_(
            'Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = CustomUserManager()

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = _('会員')
        verbose_name_plural = _('会員')

    def get_full_name(self):
        """Return the first_name plus the last_name, with a space in
        between."""
        full_name = '%s %s' % (self.first_name_manager, self.last_name_manager)
        return full_name.strip()

    def get_short_name(self):
        """Return the short name for the user."""
    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)

    @property
    def username(self):
        """username属性のゲッター

        他アプリケーションが、username属性にアクセスした場合に備えて定義
        メールアドレスを返す
        """
        return self.email



class Shop(models.Model):
    shop_name = models.CharField( verbose_name='店名', default='SHOP', max_length=20, )
    shop_name_kana = models.CharField( verbose_name='テンメイ', default='ショップ', max_length=30, )

    manager_name = models.CharField( verbose_name='管理者', default='CHIEF', max_length=15, )
    manager_account = models.ForeignKey('User', verbose_name='管理者アカウント', to_field='email', related_name='ManagerAccount', on_delete='models.DO_NOTHING', null=True, )

    #連絡用
    email = models.EmailField( verbose_name='お客様用メールアドレス', max_length=255, blank = True, null = True )
    tel_shop = models.CharField( verbose_name='電話番号', max_length=15, blank=True, )
    website = models.CharField( verbose_name='サイトURL', default='http://www.', max_length=100, )

    #アクセス情報
    zip_code = models.CharField(
        verbose_name='郵便番号',max_length=8,blank=True,
    )

    address1 = models.CharField(
        verbose_name='都道府県',max_length=40,blank=True,
    )
    
    address2 = models.CharField(
        verbose_name='市区町村',max_length=40,blank=True,
    )
    
    address3 = models.CharField(
        verbose_name='丁目',max_length=40,blank=True,
    )
    address4 = models.CharField(
        verbose_name='番地以降',max_length=40,blank=True,
    )
    
    address5 = models.CharField(
        verbose_name='建物名・部屋番号等',max_length=40,blank=True,
    )

    station1 = models.CharField( verbose_name='付近の駅・バス停１', max_length=15, blank=True, )
    station1_time = models.PositiveSmallIntegerField( verbose_name='駅・バス停１からの所要時間', default=0, )

    station2 = models.CharField( verbose_name='付近の駅・バス停２', max_length=15, blank=True, )
    station2_time = models.PositiveSmallIntegerField( verbose_name='駅・バス停２からの所要時間', default=0, )

    station3 = models.CharField( verbose_name='付近の駅・バス停３', max_length=15, blank=True, )
    station3_time = models.PositiveSmallIntegerField( verbose_name='駅・バス停３からの所要時間', default=0, )

    #サービス内容
    price_basic = models.PositiveSmallIntegerField( verbose_name='基本料金', default=0, )

    support_list = ( (0,''), (1,'可'), (2,'応相談'), )

    wheelchair = models.IntegerField( verbose_name='車イス対応',choices=support_list, default=0, )
    visually = models.IntegerField( verbose_name='視覚障碍対応',choices=support_list, default=0, )
    hearing = models.IntegerField( verbose_name='聴覚障碍対応',choices=support_list, default=0, ) 



    #営業時間
    is_holiday_sunday = models.BooleanField( verbose_name='日曜日', default='False', )
    is_holiday_monday = models.BooleanField( verbose_name='月曜日', default='False')
    is_holiday_tuesday = models.BooleanField( verbose_name='火曜日', default='False')
    is_holiday_wednesday = models.BooleanField( verbose_name='水曜日', default='False')
    is_holiday_thursday = models.BooleanField( verbose_name='木曜日', default='False')
    is_holiday_friday = models.BooleanField( verbose_name='金曜日', default='False')
    is_holiday_saturday = models.BooleanField( verbose_name='土曜日', default='False')

    time_list = ( (00,'00:00'),  (1,'00:30'), (2,'01:00'),  (3,'01:30'), (4,'02:00'),  (5,'02:30'), (6,'03:00'),  (7,'03:30'), (8,'04:00'),  (9,'04:30'), (10,'05:00'), (11,'05:30'),
                  (12,'06:00'), (13,'06:30'),(14,'07:00'), (15,'07:30'),(16,'08:00'), (17,'08:30'),(18,'09:00'), (19,'09:30'),(20,'10:00'), (21,'10:30'), (22,'11:00'), (23,'11:30'),
                  (24,'12:00'), (25,'12:30'),(26,'13:00'), (27,'13:30'),(28,'14:00'), (29,'14:30'),(30,'15:00'), (31,'15:30'),(32,'16:00'), (33,'16:30'), (34,'17:00'), (35,'17:30'),
                  (36,'18:00'), (37,'18:30'),(38,'19:00'), (39,'19:30'),(40,'20:00'), (41,'20:30'),(42,'21:00'), (43,'21:30'),(44,'22:00'), (45,'22:30'), (46,'23:00'), (47,'23:30'), (48,'24:00'), )

    time_open_sunday1 = models.IntegerField( verbose_name='【日曜日】開店時刻１',choices=time_list, default=0, help_text='sunday', )
    time_close_sunday1 = models.IntegerField( verbose_name='【日曜日】閉店時刻１',choices=time_list, default=0, help_text='sunday', )
    time_open_sunday2 = models.IntegerField( verbose_name='【日曜日】開店時刻２',choices=time_list, default=0, help_text='sunday', )
    time_close_sunday2 = models.IntegerField( verbose_name='【日曜日】閉店時刻２',choices=time_list, default=0, help_text='sunday', )

    time_open_monday1 = models.IntegerField( verbose_name='【月曜日】開店時刻１',choices=time_list, default=0, help_text='monday', )
    time_close_monday1 = models.IntegerField( verbose_name='【月曜日】閉店時刻１',choices=time_list, default=0, help_text='monday', )
    time_open_monday2 = models.IntegerField( verbose_name='【月曜日】開店時刻２',choices=time_list, default=0, help_text='monday', )
    time_close_monday2 = models.IntegerField( verbose_name='【月曜日】閉店時刻２',choices=time_list, default=0, help_text='monday', )

    time_open_tuesday1 = models.IntegerField( verbose_name='【火曜日】開店時刻１',choices=time_list, default=0, help_text='tuesday', )
    time_close_tuesday1 = models.IntegerField( verbose_name='【火曜日】閉店時刻１',choices=time_list, default=0, help_text='tuesday', )
    time_open_tuesday2 = models.IntegerField( verbose_name='【火曜日】開店時刻２',choices=time_list, default=0, help_text='tuesday', )
    time_close_tuesday2 = models.IntegerField( verbose_name='【火曜日】閉店時刻２',choices=time_list, default=0, help_text='tuesday', )

    time_open_wednesday1 = models.IntegerField( verbose_name='【水曜日】開店時刻１',choices=time_list, default=0, help_text='wednesday', )
    time_close_wednesday1 = models.IntegerField( verbose_name='【水曜日】閉店時刻１',choices=time_list, default=0, help_text='wednesday', )
    time_open_wednesday2 = models.IntegerField( verbose_name='【水曜日】開店時刻２',choices=time_list, default=0, help_text='wednesday', )
    time_close_wednesday2 = models.IntegerField( verbose_name='【水曜日】閉店時刻２',choices=time_list, default=0, help_text='wednesday', )

    time_open_thursday1 = models.IntegerField( verbose_name='【木曜日】開店時刻１',choices=time_list, default=0, help_text='thursday', )
    time_close_thursday1 = models.IntegerField( verbose_name='【木曜日】閉店時刻１',choices=time_list, default=0, help_text='thursday', )
    time_open_thursday2 = models.IntegerField( verbose_name='【木曜日】開店時刻２',choices=time_list, default=0, help_text='thursday', )
    time_close_thursday2 = models.IntegerField( verbose_name='【木曜日】閉店時刻２',choices=time_list, default=0, help_text='thursday', )

    time_open_friday1 = models.IntegerField( verbose_name='【金曜日】開店時刻１',choices=time_list, default=0, help_text='friday', )
    time_close_friday1 = models.IntegerField( verbose_name='【金曜日】閉店時刻１',choices=time_list, default=0, help_text='friday', )
    time_open_friday2 = models.IntegerField( verbose_name='【金曜日】開店時刻２',choices=time_list, default=0, help_text='friday', )
    time_close_friday2 = models.IntegerField( verbose_name='【金曜日】閉店時刻２',choices=time_list, default=0, help_text='friday', )

    time_open_saturday1 = models.IntegerField( verbose_name='【土曜日】開店時刻１',choices=time_list, default=0, help_text='saturday', )
    time_close_saturday1 = models.IntegerField( verbose_name='【土曜日】閉店時刻１',choices=time_list, default=0, help_text='saturday', )
    time_open_saturday2 = models.IntegerField( verbose_name='【土曜日】開店時刻２',choices=time_list, default=0, help_text='saturday', )
    time_close_saturday2 = models.IntegerField( verbose_name='【土曜日】閉店時刻２',choices=time_list, default=0, help_text='saturday', )


    #評価用
    point = models.IntegerField( verbose_name='店舗ID', default=0, )

    remarks_shop = models.TextField( verbose_name='備考', max_length=150, blank=True, )

    created_at = models.DateTimeField( auto_now_add=True, )
    updated_at = models.DateTimeField( auto_now=True, )

    class Meta:
        verbose_name = _('店舗情報')
        verbose_name_plural = _('店舗情報')

    def __str__(self):
        return self.shop_name<file_sep>/UserLogin/migrations/0004_auto_20210717_1520.py
# Generated by Django 2.2.24 on 2021-07-17 06:20

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('UserLogin', '0003_shop_time_cloae_sunday1'),
    ]

    operations = [
        migrations.RenameField(
            model_name='shop',
            old_name='time_cloae_sunday1',
            new_name='time_close_sunday1',
        ),
    ]
