🔖 Day4 - Custom Login Page and Logout

2018 - 06 - 26
🔖 Day4 - Custom Login Page and Logout
1. [Custom Login Page] Django有自己的built-in authentication 認證用戶: django.contrib.auth 。 而且有自己的built-in models (database)儲存users資料: django.contrib.auth.models.User。 全都在 django.contrib.auth 裡面,預設在INSTALLED APPS。
2. [Set url] 要建Login Page,先到urls.py:
from <app_name>.views import login
from django.urls import path

urlpatterns = [
...
    path(r’login/’, login, name=’login’)
]


3. [Set view function] 再到blog.views.py,新增function:
from django.contrib.auth import authenticate, login

def login(request):
 if request.user.is_authenticated:
  redirect(‘blog’)

 if request.method == ‘POST’: 
  username = request.POST.get(‘username’)
  password = request.POST.get(‘password’)
  user = authenticate(username=username, password=password)

  if user:
   login(request, user)
   loginstatus = True
   returnapp_index(request)
  else:
   loginstatus = False
   return render(request, ‘account/login.html’)

 else:
  loginstatus = None
  return render(request, ‘account/login.html’)

要留意is_authenticated()在Django2.0已改成沒有()
4. [create html template] 然後新增一頁login.html。e.g. ,templates/account/login.html 頁面內以POST 形式回傳input form輸入的資料:
<form method="POST">
{% csrf_token %}
<label for="username">Username:</label>
<input type="text" name="username">
<label for="password">Password:</label>
<input type="text" name="password">
<input type="submit" value="Login">
{% if loginstatus == False %}
 <span>Your username/password is wrong.</span>
{% endif %}


5. [Redirect to index] 還沒完,因為在Step 3,我們把Login完的動作改為
return app_index(request)

回傳到blog首頁,希望在成功登入後把menu bar 的Login字,改為Logout, 可以在base.html的menu位置增加if condition
{% if request.user.is_authenticated %}
    <a href="{% url 'logout' %}">Logout</a>
{% else %}
    <a href="{% url 'login' %}">Login</a>

這樣login後的連結會變成logout。
6. [Logout] Logout的做法跟login大致相同,而且更為單簡。 只需在views.py增加function:
from django.contrib.auth import logout

def logout(request):
 logout(request)
 return app_index(request)

然後在urls.py新增regex:
from <app_name>.views import logout

urlpatterns = [
 ...
 ...
 url(r'^logout/$', logout, name='logout'),
]

這次不用新增templates,因為在views.py return 的是app_index() 。

Comments

There is no comment yet

New Comment

Please Login to comment