管理員登入與登出

開啟專案的路徑規則檔規則:

urlpatterns = [ path('admin/', admin.site.urls), path('log/', include('log.urls')), path('', RedirectView.as_view(url='log/')), path('accounts/', include('django.contrib.auth.urls')), ]

修改專案設定檔 repair/repair/settings.py

# Redirect to home URL after login (Default redirects to /accounts/profile/) LOGIN_REDIRECT_URL = '/'

頁面範本

新增資料夾 repair/log/templates/registration

使用者登入

新增登入頁面範本 repair/log/templates/registration/login.html

{% extends "base.html" %} {% block content %} {% if form.errors %} <p class="alert alert-danger">帳號或密碼不符合,請再試一次。</p> {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <div class="h3 mb5">請輸入您的帳號密碼</div> <div class="form-inline"> <input name="username" autofocus="" required="" id="id_username" maxlength="254" type="text" class="form-control mr-2" placeholder="帳號"> <input name="password" required="" id="id_password" type="password" class="form-control mr-2" placeholder="密碼"> <input type="submit" value="login" class="form-control btn-primary"/> </div> </form> {% endblock %}

登出

新增登出頁面範本檔案 repair/log/templates/registration/logged_out.html

{% extends "base.html" %} {% block content %} <p class="alert alert-info">您已登出!!</p> <a href="{% url 'login'%}" class="btn btn-primary">請按此處重新<i class="fas fa-sign-in-alt"></i> 登入</a> {% endblock %}

導覽列新增登入/登出連結

修改導覽列範本檔 repair/log/templates/navbar.html

<!-- Navbar begin //--> <nav class="navbar navbar-expand-sm navbar-light bg-light mb-4 shadow-sm"> <!-- 網站標誌 --> <div class="navbar-brand"> <i class="fas fa-wrench"></i> 線上報修系統 </div> <!-- 在小螢幕的設備上顯示可展開/收合導覽選單的按鈕 --> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <!-- 導覽列選單內容(可收合) --> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ml-auto nav-pills"> <li class="nav-item"> <a href="{% url 'log_list' %}" class="nav-link"> <i class="fas fa-list-alt"></i> 報修記錄 </a> </li> <li class="nav-item"> <a href="{% url 'log_create' %}" class="nav-link"> <i class="fas fa-edit"></i> 我要報修 </a> </li> {% if user.is_authenticated %} <li class="nav-item"> <a href="{% url 'logout' %}" class="nav-link"> <i class="fas fa-sign-out-alt"></i> 登出 {{ user.username }} </a> </li> {% else %} <li class="nav-item"> <a href="{% url 'login' %}" class="nav-link"> <i class="fas fa-sign-in-alt"></i> 登入 </a> </li> {% endif %} </ul> </div> </nav> <!-- Navbar end //-->