
簡介:
Python下有許多款不同的 Web 框架。Django是重量級選手中最有代表性的一位。許多成功的網站和APP都基于Django。
Django是一個開放源代碼的Web應用框架,由Python寫成。
Django遵守BSD版權,初次發布于2005年7月, 并于2008年9月發布了第一個正式版本1.0 。
Django采用了MVC的軟件設計模式,即模型M,視圖V和控制器C。
用戶名密碼登陸實現:
在apps.users下找到views.py文件:
以下代碼重寫了authenticate()方法,方便用戶擴展功能,比如郵箱驗證登陸等。
在setting.py中重載一個變量:
AUTHENTICATION_BACKENDS = ('users.views.CustomBackend',)
from django.contrib.auth import authenticate, loginfrom django.contrib.auth.backends import ModelBackendfrom django.db.models import Q# 繼承View 實現基于類的用戶登陸from django.views.generic.base import View from .models import UserProfile# 重寫 authenticate 登陸驗證方法class CustomBackend(ModelBackend): def authenticate(self, username=None, password=None, **kwargs): try: # 驗證用戶名或郵箱, Q提供了一個對象間的或(與&)運算 user=UserProfile.objects.get(Q(username=username) | Q(email=username)) # 后臺密碼為暗文,傳入的密碼為明文, 所以需要使用check_password()方法驗證密碼 if user.check_password(password): # 驗證成功返回user對象 return user # 登陸失敗返回None except Exception as e: return None
繼承django.views.generic.base中的View類,根據method的不同,對應實現GET和POST的不同處理,一般POST為驗證用戶登陸,在此基礎上還可以添加form處理,減少錯誤提交,減少對服務器的訪問次數。
# 基于類實現用戶登陸class LoginView(View): # 會根據 method 調用 post或者get方法 def get(self, request): # 如果method為 GET 重新返回登陸頁面 return render(request, "login.html", {}) def post(self, request): # 驗證每個字段是否合法 login_form = LoginForm(request.POST) # 對每個字段進行預處理,如果不合法,直接提示錯誤信息 pre_check = login_form.is_valid() # 如果合法 if pre_check: # 從POST中取出用戶名和密碼 user_name = request.POST.get("username", "") if UserProfile.objects.filter(email=user_name): return render(request, "register.html", {"register_form": register_form, "msg": "用戶已經存在"}) pass_word = request.POST.get("password", "") # 此處為上面重寫的authenticate方法 user = authenticate(username=user_name, password=pass_word) if user is not None: # 如果成功返回對象,失敗返回None login(request, user) # 調用login方法登陸賬號 return render(request, "index.html") else: # 登陸失敗 return render(request, "login.html", {"msg":u"用戶名或密碼錯誤"}) else: # form驗證失敗,給出錯誤信息 return render(request, "login.html", {"login_form":login_form})
新聞熱點
疑難解答