1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

django-allauthを使ってログイン機能を5分で実装する方法

Last updated at Posted at 2021-03-04

django-allauthのインストール

$ pip install django-allauth

settings.pyの編集

settings.py

AUTHENTICATION_BACKENDS = [
    ...
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
    ...
]

INSTALLED_APPS = [
    ...
    # 下の4つを追加
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    ...
]

SITE_ID = 1 # 忘れずに!

urls.pyの設定

urls.py
from django.urls import path, include #⇐includeを追加

urlpatterns = [
    ...
    path('accounts/', include('allauth.urls')),
    ...
]

マイグレーションの実行

$ python manage.py migrate

以上です!
accounts/loginがデフォルトのurlになっているのでそこから確認できます。以下のようなページが表示されます。もしtemplates does not existsが出る場合は一度accounts/logoutでログアウトしてから確かめてみてください。ちなみにaccounts/profileのURLが必要ない場合にはsettigns.py
image.png

オススメなオプション

django-allauthは個人の好みによって色々な設定が簡単にできるようにしてくれています。
個人的によく使う設定は以下です。こちらから必要な設定を探せます。

settings.py
LOGIN_REDIRECT_URL = '/' # loginした後にリダイレクトされるところ
ACCOUNT_LOGOUT_REDIRECT_URL = '/' # logoutした後にリダイレクトされるところ
ACCOUNT_SESSION_REMEMBER = True # 自動でアカウントのセッションを保持(いちいちユーザーネームとパスワードを要求しない)
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False # ユーザー登録時にパスワードの要求を一回にする
ACCOUNT_LOGOUT_ON_GET = True #ログアウトをクリックしたらログアウト確認画面を経由しないで直接ログアウト

次やること

  • templatesの見た目の変更

参考サイト

公式ドキュメント

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?