LoginSignup
5
10

djangoのログイン機能+新規アカウント追加

Last updated at Posted at 2024-04-29

djangoの構築

構築は既に完了しているものとする

1. loginのページの追加を行う

setting.py
import os #新しく追加
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],   #新しく追加
        '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',
            ],
        },
    },
]
└── yourappname/
    ├── templates/          # 新しいディレクトリを作成
    |   └── login_home.html      # テンプレートファイルをここに配置
    |   └── login_creat.html      # テンプレートファイルをここに配置

2. データベース

データベースのGUIとしてTablePlusを使用する.https://tableplus.com

ソフトウェアを開き上部の+ボタンを押しSQLiteを選択する

image.png

Nameに任意の名前を付け
SQLite fileにdjangoのdb.sqlite3のファイルを選択する

コマンドプロンプト以下を実行

python manage.py migrate

3. 通常のログイン機能の実装

views.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib import messages
from django.contrib.auth.models import User

# ログイン後に表示するページ
def home_page(request):
    return render(request, 'home.html')

# ログイン時に表示するページとログイン機能
def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        # ユーザー認証
        user = authenticate(request, username=username, password=password)

        if user is not None:
            # ログイン成功
            login(request, user)
            return redirect('home')
        else:
            # ログイン失敗
            messages.error(request, 'ユーザー名またはパスワードが間違っています。')

    return render(request, 'login_home.html')
urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
    path('home', views.home_page, name='home'),
    path('', views.user_login, name='title'),
]
login_home.html
<!DOCTYPE html>
<html lang="ja">

    <head>
        <meta charset="UTF-8">
        <title>Login</title>
    </head>
    
    <body>
            {% if messages %}
            <ul>
                {% for message in messages %}
                <li>{{ message }}</li>
                {% endfor %}
            </ul>
            {% endif %}
        
            <form method="post" action="{% url 'title' %}">
                {% csrf_token %}
                <label for="username">ユーザー名:</label>
                <input type="text" id="username" name="username">
                <br>
                <label for="userpassword">パスワード教えろ:</label>
                <input type="password" id="userpassword" name="password">
                <br>
                <button type="submit">ログイン</button>
                
            </form>
    </body>
</html>
home.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    loginできたよ!!!!
</body>
</html>

ココでいったん確認したい人用
コマンド プロンプトで以下を実行

python manage.py createsuperuser

username,email,passwordを好きなように入力

passwordはセキュリティーで入力したものが見えなくなってるよ

ここまでで通常のログインだけは完成

4. ログインの新規アカウント追加

views.py
#先ほどの下に追加
#新規アカウントの追加ページ
def user_create(request):
    if request.method == 'POST':
        new_username = request.POST.get('new_username')
        new_password = request.POST.get('new_password')
        try:
            # 新しいユーザーオブジェクトを作成し、ユーザー名とパスワードを設定
            user = User.objects.create_user(username=new_username, password=new_password)
        except Exception as e:
            # ユーザ作成失敗
            messages.error(request, 'ユーザーの作成に失敗しました。エラー: {}'.format(str(e)))

        # ログイン処理
        user = authenticate(request, username=new_username, password=new_password)
        if user is not None:
            # ログイン成功
            messages.error(request, 'ログインに成功しました。')
            login(request, user)
            return redirect('home')
        else:
            # ログイン失敗
            messages.error(request, 'ユーザー名またはパスワードが間違っています。ユーザー名: {}'.format(new_password))


    return render(request, 'login_create.html')
urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
    path('home', views.home_page, name='home'),
    path('', views.user_login, name='title'),
    path('create', views.user_create, name='create'), # この行を追加
]
login_create.html
<!DOCTYPE html>
<html lang="ja">

    <head>
        <meta charset="UTF-8">
        <title>Login</title>
    </head>
    
    <body>
            {% if messages %}
            <ul>
                {% for message in messages %}
                <li>{{ message }}</li>
                {% endfor %}
            </ul>
            {% endif %}
        
            <form method="post" action="{% url 'create' %}">
                {% csrf_token %}
                <label for="username">ユーザー名:</label>
                <input type="text" id="username" name="new_username">
                <br>
                <label for="userpassword">パスワード教えろ:</label>
                <input type="password" id="userpassword" name="new_password">
                <br>
                <button type="submit">ログイン</button>
                
            </form>
    </body>
</html>
login_home.html
<!DOCTYPE html>
<html lang="ja">

    <head>
        <meta charset="UTF-8">
        <title>Login</title>
    </head>
    
    <body>
            {% if messages %}
            <ul>
                {% for message in messages %}
                <li>{{ message }}</li>
                {% endfor %}
            </ul>
            {% endif %}
        
            <form method="post" action="{% url 'title' %}">
                {% csrf_token %}
                <label for="username">ユーザー名:</label>
                <input type="text" id="username" name="username">
                <br>
                <label for="userpassword">パスワード教えろ:</label>
                <input type="password" id="userpassword" name="password">
                <br>
                <button type="submit">ログイン</button>  
            </form>
            <a href="{% url 'create' %}">新規アカウント作成</a> # 追加
    </body>
</html>

5. 参考

データベースの構築
https://qiita.com/tarakokko3233/items/297ebe4f2bf7a7ea543a

5
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
10