ログイン機能 - Django

フォルダ構成

  • pythonApp
    • login
      • include
      • Lib
      • login
        • hello
          • migrations
            • ...
          • static
            • hello
              • css
                • style.css
              • javascripts
                • script.js
          • templates
            • hello
              • base.html
              • home.html
              • login.html
              • logout_view.html
              • public.html
              • top.html
          • __init__.py
          • admin.py
          • apps.py
          • forms.py
          • models.py
          • tests.py
          • views.py
        • login
          • __pycache__
          • __init__.py
          • asgi.py
          • settings.py
          • urls.py
          • wsgi.py
        • manage.py
      • Scripts
      • pyenv.cfg

ファイルの内容

templates

pythonApp\login\login\hello\templates\hello\base.html

{% load static %}
<!doctype html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="{% static 'hello/css/style.css' %}">
    <script src="{% static 'hello/javascripts/script.js' %}"></script>
    <title>Document</title>
  </head>
  <body>
    {% block content %}{% endblock %}
  </body>
</html>

pythonApp\login\login\hello\templates\hello\home.html

{% extends "hello/base.html" %}
{% block title %}ホーム{% endblock %}

{% block content %}
<div class="container">
  <p>{{ user.username }}さん、こんにちは。</p>
  {% if user.is_superuser %}
  <p>Admin</p>
  {% elif user.is_staff %}
  <p>Staff</p>
  {% endif %}
  <form action="{% url 'hello:logout_view' %}" method="post">
    {% csrf_token %}
    <button type="submit" class="logout-link">ログアウト</button>
  </form>
</div>
{% endblock %}

pythonApp\login\login\hello\templates\hello\login.html

{% extends "hello/base.html" %}
{% block title %}ログイン{% endblock %}

{% block content %}
<div class="container">
  <h1>ログイン</h1>
  <form action="" method="POST" novalidate>
    {% csrf_token %}
    {{ form.non_field_errors }}

    {% for field in form %}
      <div>
        <p>{{ field.label }}<br>{{ field }}</p>
        <div>
          {% for error in field.errors %}
            {{error}}
          {% endfor %}
        </div>
      </div>
    {% endfor %}
    <p><button type="submit">ログイン</button></p>
  </form>
</div>
{% endblock %}

pythonApp\login\login\hello\templates\hello\logout_view.html

{% extends "hello/base.html" %}
{% block title %}ログアウト{% endblock %}

{% block content %}
<h1>Logout</h1>
  <p>ログアウトしました。</p>
  <p><a href="{% url 'hello:top' %}">トップページ</a></p>
{% endblock %}

pythonApp\login\login\hello\templates\hello\public.html

{% extends "hello/base.html" %}
{% block title %}パブリックページ{% endblock %}

{% block content %}
<h1>hello/public</h1>
{% if user.is_authenticated %}
<p>ログイン:{{ user.username }}</p>  
{% endif %}
<p>誰でも閲覧可能です</p>
{% endblock %}

pythonApp\login\login\hello\templates\hello\top.html

{% extends "hello/base.html" %}

{% block title %}トップ{% endblock %}

{% block content %}
<div class="container">
  <h1>Top 画面</h1>
  <a href="{% url 'hello:login' %}">ログイン</a>
</div>
{% endblock %}
urls

pythonApp\login\login\hello\urls.py

from django.urls import path
from . import views

app_name = 'hello'

urlpatterns = [
    path("", views.TopView.as_view(), name="top"),
    path("home/", views.HomeView.as_view(), name="home"),
    path("login/", views.LoginView.as_view(), name="login"),
    path("logout_view/", views.LogoutView.as_view(), name="logout_view"),
    path("public/", views.PublicView.as_view(), name="public"),
]

pythonApp\login\login\login\urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/', include('hello.urls')),
]
views

pythonApp\login\login\hello\views.py

from django.contrib.auth.views import LoginView, LogoutView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
from . import forms

class TopView(TemplateView):
  template_name = "hello/top.html"

class HomeView(LoginRequiredMixin, TemplateView):
  template_name = "hello/home.html"

class LoginView(LoginView):
  form_class = forms.LoginForm
  template_name = "hello/login.html"

class LogoutView(LoginRequiredMixin, LogoutView):
  template_name = "hello/logout_view.html"

class PublicView(TemplateView):
  template_name = "hello/public.html"
from

pythonApp\login\login\hello\forms.py

from django.contrib.auth.forms import AuthenticationForm

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

pythonApp\login\login\login\settings.py

"""
Django settings for login project.

Generated by 'django-admin startproject' using Django 5.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-_h!cq96=bm!z9+bvs6njgd=yg^nppbub*&fpfzy*7(c1hp)8u+'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello', # +
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'login.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'login.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'login',
        'USER': '', # 自身の環境データベースのユーザー名
        'PASSWORD': '', # 自身の環境データベースのパスワード
        'HOST': '127.0.0.1', # 自身の環境データベースのホスト名など
        'PORT': '3306' # 自身の環境データベースのポート番号
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE = 'ja' # +

TIME_ZONE = 'Asia/Tokyo' # +

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

LOGIN_URL = "hello:login" # +
LOGIN_REDIRECT_URL = "hello:home" # +
LOGOUT_REDIRECT_URL = "hello:logout_view" # +
css

pythonApp\login\login\hello\static\hello\css\style.css

.logout-link {
  background: none;
  border: none;
  padding: 0;
  color: #0d6efd;
  text-decoration: underline;
  cursor: pointer;
}
admin

pythonApp\auth\auth\hello\admin.py

from django.contrib import admin
from .models import Hello

# Register your models here.
admin.site.register(Hello)

準備

cd d:
mkdir pythonApp
cd pythonApp

# 開発環境の作成
python -m venv login

cd login

# 開発環境の起動
.\Scripts\activate

pip install django
pip install mysqlclient

# プロジェクトの作成
django-admin startproject login

cd login
python manage.py runserver

「 hello 」アプリを作成します。

python manage.py startapp hello

「 MySQL 」でデータベースを作成しておきます。

CREATE DATABASE login;

マイグレーションを実行します。

python manage.py migrate

管理ユーザーを作成します。

python manage.py createsuperuser