1. 程式人生 > >authenticate()和login()實現用戶登錄 | Django

authenticate()和login()實現用戶登錄 | Django

邏輯 method 一個 ren short valid att shortcuts view

# authenticate(), login()實現登錄
1.顯示首頁
    from django.views.generic import TemplateView
    # 不需要視圖函數來做業務處理時使用TemplateView,參數:template_name
    urlpatterns = [
        url(r^$, TemplateView.as_view(template_name="index.html"), name="index"),
        # 首頁點擊登錄,跳轉登錄頁面(不需要寫後臺的視圖函數)
        url(r^$, TemplateView.as_view(template_name="
login.html"), name="login") ] 2.登錄的後臺邏輯 views.py # 1.函數式編程 from django.shortcuts import render def user_login(request): if request.method == "POST": # 如果是post請求,從表單獲取input數據 user_name = request.POST.get("username", ""
) pass_word = request.POST.get("password", "") # 將表單提交的數據做認證 # authenticate()方法return的是什麽東西? # If the given credentials are valid, return a User object. # 如果表單提交的認證信息是正確的,就返回一個User模型類的對象 user = authenticate(username=user_name, password=pass_word)
# 認證後的對象做允許登錄的判斷 if user: login(request, user) return render(request, "index.html", {"user": user}) else: return render(request, "login.html", {"msg": "驗證失敗!"}) index.html # 前端要顯示登錄狀態,需要做判斷 # 解釋一下這個"request.user.is_authenticated"? {% if request.user.is_authenticated %} ... 顯示{{user.username}}以及註銷登錄input框 {% else %} ... 正常顯示首頁 {% endif %}

authenticate()和login()實現用戶登錄 | Django