2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Djangoでユーザー登録後に自動ログインさせる方法

Posted at

はじめに

Djangoでユーザー登録機能(SignUp)を実装した際、
「登録後に自動的にログイン状態にしたい」と思ったことはありませんか?
この記事では、CreateView を継承してユーザー登録後に自動ログインを行う方法を解説します。
UX向上や実務での実装にも応用できるので、初学者にもおすすめです。

実現したいこと

Djangoのユーザー登録後、自動ログイン状態にする。
ユーザーに「ログインし直す」手間をかけさせない。
CreateView + login() を活用したシンプルな実装。

実装コード

🔹フォーム(例:CustomUserCreationForm)

UserCreationFormを継承したCustomUserCreationFormにユーザー新規登録用のフォームを実装する。
fieldsに新規登録時の入力項目を設定する。(ここでの入力内容は、ユーザー名、メールアドレス、パスワード、パスワード(確認用)である。)

users/forms.py
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class CustomUserCreationForm(UserCreationForm):
    email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={"class": "form-control"}))

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")  # 必要に応じて変更
        widgets = {
            "username": forms.TextInput(attrs={"class": "form-control"}),
            "password1": forms.PasswordInput(attrs={"class": "form-control"}),
            "password2": forms.PasswordInput(attrs={"class": "form-control"}),
        }

🔹ビュー(form_valid() でログイン処理を追加)

上記で設定したフォームについて、SignUpViewで呼び出している。
template_nameに新規登録用フォームのあるhtmlファイルが存在するパスを記載する。
self.object = form.save()でユーザー登録し、loginでログインの処理を行っている。
ログイン成功後、get_success_urlに記載のページに遷移する。

users/views.py
from django.contrib.auth import login
from django.urls import reverse
from django.views.generic.edit import CreateView
from django.contrib.auth.models import User
from .forms import CustomUserCreationForm

class SignUpView(CreateView):
    model = User
    form_class = CustomUserCreationForm
    template_name = 'registration/signup.html'

    def form_valid(self, form):
        self.object = form.save()  # ユーザー登録
        response = super().form_valid(form)
        login(self.request, self.object)  # 自動ログイン
        return response

    def get_success_url(self):
        # 登録後に遷移するページを指定(ここではタスク一覧画面)
        return reverse('todos:index')

自動ログインが重要な理由

ユーザー新規登録後、すぐログイン状態になるため、ユーザーが使いやすくなるためです。
新規登録→ログインの流れだと、ユーザーの手間をかけさせることになってしまいます。

まとめ

Djangoでは CreateView を拡張し、form_valid() 内で login() を呼ぶことで簡単に自動ログインを実現できます。
get_success_url() を適切に設定することで、ユーザー導線もコントロール可能です。

終わりに

初投稿なので、改善点やご指摘などあればぜひコメントいただけると嬉しいです!

備考

Djangoバージョン:4.x系想定
テンプレートエンジン:Django標準
Bootstrap 5 使用(UI整備済み)

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?