タイトル: ログイン機能
                        SEOタイトル: 【django】ログイン機能
                    
        
        概要
djangoは標準で認証機能が搭載されている。
今回はそちらを利用する。
認証系テーブルの作成
マイグレーションを実行することで認証系テーブルが作成される。
| python manage.py migrate | 
URLの定義
認証機能を有効化させるにはurl.pyに以下の記述を追加する。
| urlpatterns = [ | 
url群の内容は以下の通りです。(参考までに)
| accounts/login/ [name='login'] | 
ユーザー登録機能の作成
予め定義されているものを出来るだけ使用するので最低限の実装で済む。
まずは登録画面に遷移するaタグをどこか適当なテンプレートに記述する。
| <a href="{% url 'signup' %}">ユーザー登録</a> | 
url.pyに以下の記述を追加する。
| from common.views.signup import SignupView urlpatterns = [ .... path('signup/', SignupView.as_view(), name='signup'), ] | 
上記の様に適当なビューを用意する。
次にビュー自体の定義をする。
登録画面を開くだけなので簡単な実装とする。
| class SignupView(CreateView): form_class = UserCreationForm template_name = "signup.html" success_url = reverse_lazy('login') | 
form_classには事前定義されているUserCreationFormを必ず指定すること。
success_urlはユーザー作成後のリダイレクト先を指定する。
次に上記でtemplate_nameに指定したテンプレートの定義をして終わり。
| {% extends "base.html" %} {% block content %} <form method="post" action=""> {{ form.as_p }}     <input type="submit"> {% endblock %} | 
ログインテンプレートの定義
ログイン画面のテンプレートを用意します。
以下、公式サイトから引用した簡単なログイン画面です。
templates/registration/login.html
| {% extends "common/base.html" %} {% block content %} {% if form.errors %} {% if next %} <form method="post" action="{% url 'login' %}"> <input type="submit" value="login"> {# Assumes you setup the password_reset view in your URLconf #} {% endblock %} | 
呼び出し元のリンクは以下の様に記述します。
| <a href="{% url 'login' %}">ログイン</a> | 
ログイン後のリダイレクト先
setting.pyに以下の記述をすることでログイン後のリダイレクト先を設定することが出来る。
| LOGIN_REDIRECT_URL = '/' | 
 
 
            