10
16

More than 5 years have passed since last update.

Djangoで手短にログイン処理

Last updated at Posted at 2018-02-15

Djangoで手短にログイン処理

djangoにはログイン、ログアウト、パスワード管理のためのビューがあらかじめ備わっています。ただしテンプレートは用意されていないので、自分で用意する必要があります。

公式ドキュメントこちらの記事で紹介されています

本記事ではなるべく手数をかけずにログイン処理をつくるシンプルな手順をまとめます

urls.pyに下記を追記します。

projectname/urls.py
...
from django.urls import include
...

urlpatterns = [
    ...,
    path('accounts/', include('django.contrib.auth.urls')),
]

テンプレートを入れるためのアプリフォルダを用意します。アプリの名前はなんでもいい(whatever)ですが、テンプレートの入るフォルダはregistrationにします

mkdir -p whatever/templates/registration

ディレクトリ構成は下記になります

projectname
  whatever
    templates
      registration

registrationにlogin.htmlをつくります

whatever/templates/registration/login.html
<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
</head>
<body>
  <form action="{% url 'login' %}" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="login" />
    <input type="hidden" name="next" value="{{ next }}" />
</form>
</body>
</html>

アプリを登録します

projectname/settings.py
INSTALLED_APPS = [
     'django.contrib.admin',
     'django.contrib.auth', # <- 登録されているか確認してください
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'whatever', # <- アプリ名を追記
 ]

テスト

python manage.py runserverでテストサーバーを起動し、http://localhost:8000/accounts/login/?next=/にアクセスします。?next=以下はログイン後に移動させたいパスです

Screen Shot 2018-02-16 at 8.03.44.png

まとめ

たったこれだけでログイン処理がつくれる、Djangoすごい!

10
16
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
10
16