0
1

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 1 year has passed since last update.

Djangoメモ -ログイン画面の作成-

0
Last updated at Posted at 2025-10-21

はじめに

今回は簡易的なログイン画面の作成を行っていきます。前回の新規登録画面と少し似ていて、これもviews.pyで多くの条件分岐を扱います。

web制作

1,ログイン画面のもろもろの準備

新規登録画面同様、templatesのhtmlファイルとurls.pyのurlルーティング、views.pyの関数の下準備を行っていきます。

プロジェクト名
├── プロジェクト名
├── アプリ名
├── templates
│   └── login.html
├── manage.py
└── db.sqlite
templates/login.html
<h1>Login Now</h1>

<form action = "login" method = "POST">
    {% csrf_token%}
    <p>Username</p>
    <input type = "text"name = "usrename">
    <p>passwored: </p>
    <input type="password" name = "opassword">
    <iput type="sumit"/>

</form>
アプリ名/urls.py
from django.urls import path 
from . import views 

urlpatterns = [
    path('',views.index,name = 'index'),
    path('counter',views.counter,name='counter'),
    path('register',views.register,name='register'),
    path('login',views.login,name="login"),#←ここが変わった。
]
アプリ名/views.py
def login(request):
    return render(request,'login.html')

2,ログインの関数定義

次は、前回と同様がっつりコードを書いていきます。自身のある人は前回の新規登録画面を参考にして、自分で考えてやってみて下さい。

アプリ名/views.py
def login(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']

        user = auth.authenticate(username = username, password = password)#usernameとpasswordに一致するuserをuser変数に入れる

        if user is not None:#ユーザーがいないことがなければ
            auth.login(request, user)#ログインを行う
            return redirect('/')
        else:
            messages.info(request,'Credentials Invalid')
            return redirect('login')

    else:
        return render(request,'login.html')

なかなかコンパクトで良い感じに収まりましたね。
また、templatesのlogin.htmlも以下のように書き換えてください。

template/login.html
<h1>Login Now</h1>
<style>
h5{
    color:red;
}
</style>
{% for message in messages %}
<h5>{{message}}</h5>
{% endfor %}
<form action = "login" method = "POST">
    {% csrf_token%}
    <p>Username</p>
    <input type = "text"name = "username">
    <p>passwored: </p>
    <input type="password" name = "password">
    <input type="submit"/>

</form>

3,ログイン後の変数渡し

先ほどのviews.pyのloginコードはloginすると、一番最初のwebサイトに戻るようにンっています。その際に、loginできていれば、usernameを載せた変数を使った文字列を出力し、逆にloginしていなければもともとあった文字列を出力するということをお行っていきます。

templates/index.html
<div class="container">
        <div class="row justify-content-center" data-aos="zoom-out">
          <div class="col-xl-7 col-lg-9 text-center">
            {% if user.is_authenticated %}<!--ユーザーがloginしてたなら-->
            <h1>Welcome,{{user.username}}</h1><!--ここを表示する。-->
            {% else %}
            <h1>One Page Bootstrap Website Template</h1>
            {% endif %}
            <p>We are team of talented designers making websites with Bootstrap</p>
          </div>
        </div>

93行目あたりです。
こちらかけたら、先ほど作成したログインページからスーパーユーザーでログインしてみてください。"welcome <ユーザー名>"が出てくれば成功です。

4,ログアウト、新規登録画面への遷移ボタンの作成

まずは、htmlファイルにログインしているときはlogoutボタンを、してないときは新規登録またはログイン画面に遷移するボタンを作成します。下記のように書き換えてください。

templates/index.html
    {% if user.is_authenticated %}  
      <a class="btn-getstarted" href="logout">logout</a>
      {% else %}
      <a class="btn-getstarted" href="login">sign up or login</a>
      {% endif %}
    </div>

80行目あたりです。できましたら、次はlogoutのurlのpathとviews.pyで関数を定義していきます。以下の項目を追加してください。

アプリ名/urls.py
urlpatterns = [
    path('',views.index,name = 'index'),
    path('counter',views.counter,name='counter'),
    path('register',views.register,name='register'),
    path('login',views.login,name="login"),
    path('logout',views.logout,name="logout"),#←ここ
]
アプリ名/views.py
def logout(request):
    auth.logout(request)#logoutする。
    return redirect('/')#前の画面に強制遷移

できましたら、実際にlogoutしたりloginしたりしてエラーが起きないか確認してみてください。特にエラーが出なければ完成です。

終わりに

今回は前回に引き続きログインページの作成を行いました。簡易的なものなので、世に出回っているよう華やかさはありませんが確かに動くものを完成させることができました。華やかにする人の仕事はフロントエンド側の人なのでそちらに興味がある方はぜひフロントエンド側の勉強をしてみてください。次回は、url自体に変数を入れて動的にしていくことをしていきます。乞うご期待!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?