<< home

Djangoでニックネームを用いたユーザー登録機能の実装


前提


ステップ 1: 登録用フォームの作成

# accounts/forms.py

from django import forms
from django.contrib.auth import get_user_model

User = get_user_model()

class CustomUserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label='パスワード', widget=forms.PasswordInput)
    password2 = forms.CharField(label='確認用パスワード', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ['nickname', 'first_name', 'last_name']

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("パスワードが一致しません。")
        return password2

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

ステップ 2: 登録ビューの作成

# accounts/views.py

from django.shortcuts import render, redirect
from .forms import CustomUserCreationForm

def signup_view(request):
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('login')
    else:
        form = CustomUserCreationForm()
    return render(request, 'accounts/signup.html', {'form': form})

ステップ 3: テンプレートの作成

accounts/
└── templates/
    └── accounts/
        └── signup.html
<!-- signup.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>ユーザー登録</title>
</head>
<body>
  <h1>新規ユーザー登録</h1>

  <form method="post">
    
    
    <button type="submit">登録する</button>
  </form>

  <p><a href="{% url 'login' %}">ログインはこちら</a></p>

</body>
</html>

ステップ 4: URLパターンの追加

# accounts/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('signup/', views.signup_view, name='signup'),
    path('login/', views.login_view, name='login'),
    path('logout/', views.logout_view, name='logout'),
    path('', views.home_view, name='home'),
]

ステップ 5: ホームページにリンク追加

<!-- home.html に追加 -->


  <p><a href="{% url 'signup' %}">新規登録はこちら</a></p>
  


ステップ 6: 動作確認

  1. python manage.py runserver で開発サーバー起動
  2. http://127.0.0.1:8000/signup/ にアクセス
  3. ニックネーム、氏名、パスワードを入力してユーザー登録
  4. 登録後ログインページにリダイレクト

補足


次のステップ




<< home