1. 程式人生 > >Django打造在線教育平臺_day_4: 完成用戶登錄功能

Django打造在線教育平臺_day_4: 完成用戶登錄功能

then ews email word import .get cnblogs 個人 在線

1、把功能寫在users/views.py文件中

from django.shortcuts import render
from django.contrib.auth import authenticate, login #倒入驗證輸入是否合法模塊和登錄模塊
# Create your views here.

def user_login(request):
    if request.method == POST:
        user_name = request.POST.get(username, ‘‘)
        pass_word = request.POST.get(
password, ‘‘) # 向數據庫發起驗證請求用戶名和密碼是否正確 # 正確會返回一個對象, 不正確會返回None user = authenticate(username=user_name, password=pass_word) if user is not None: login(request, user) # 登錄 return render(request, index.html) else: return render(request, "
login.html",{‘msg‘: "用戶名或者密碼錯誤"})
  
     elif request.method == GET: return render(request, "login.html", {})

2、修改login.html文件

技術分享

登錄失敗提示:

技術分享

技術分享

3、運行程序輸入用戶密碼,出現以下錯誤,是Django安全機制影響的

技術分享

在login.html文件加入以下代碼

技術分享

重新運行程序

修改index.html達到登錄成功顯示個人中心

技術分享

修改urls.py文件

from users.views import user_login

urlpatterns = [

    url(r
^login/$, user_login, name=login), ]

自定義登錄方式(賬戶郵箱都可以登錄)

在users/views.py添加如下代碼

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from .models import UserProfile
# Create your views here.

class CustomBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username)|Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

配置settings.py添加

AUTHENTICATION_BACKENDS = (
    users.views.CustomBackend,
)

Django打造在線教育平臺_day_4: 完成用戶登錄功能