Django自定義UserModel並實現認證和登錄
阿新 • • 發佈:2018-03-18
eric one email post blog rac ner self object
自定義UserModel
環境:django 1.9.11+python 2.7
from django.contrib.auth.models import AbstractUser class UserProfile(AbstractUser): // AbstractUser是Django自帶的UserModel父類,在繼承的基礎上添加新的用戶字段 nick_name = models.CharField(max_length=50, verbose_name=u"昵稱", default="") birday = models.DateField(verbose_name=u"生日", null=True, blank=True) gender = models.CharField(max_length=7, choices=(("male", u"男"),("female", u"女")), default="female") address = models.CharField(max_length=100, default="") mobile = models.CharField(max_length=11, null=True, blank=True) image = models.ImageField(upload_to="image/%Y/%m", default=u"image/default.png", max_length=100) class Meta: verbose_name = "用戶信息" verbose_name_plural = verbose_name def __unicode__(self): return self.username settings.py AUTH_USER_MODEL = "users.UserProfile" // 要讓自定義UserModel生效,需要在settings文件中聲明
自定義UserModel認證和登錄
from django.shortcuts import render from django.contrib.auth import authenticate, login from django.contrib.auth.backends import ModelBackend from django.db.models import Q from django.views.generic.base import View from .models import UserProfile class CustomBackend(ModelBackend): // 首先需要重寫認證後臺的authenticate方法,因為默認的authenticate方法驗證的是自帶的UserModel def authenticate(self, username=None, password=None, **kwargs): try: user = UserProfile.objects.get(Q(username=username)|Q(email=username)) // Q這個函數表達一種或的關系,即賬號既可以是用戶名也可以是郵箱 if user.check_password(password): // 之前繼承的AbstractUser中自帶了一個check_password方法,作用是將密碼轉換為密文進行驗證 return user // authenticate方法取得對象並驗證密碼成功後會返回user對象 except Exception as e: // get()方法當獲取不到值時會出現異常,check_password()不成功也會有異常 return None // 出現異常則返回None class LoginView(View): def get(self, request): return render(request, "login.html", {}) def post(self, request): login_form = LoginForm(request.POST) if login_form.is_valid(): user_name = request.POST.get("username", "") pass_word = request.POST.get("password", "") user = authenticate(username=user_name, password=pass_word) // 這裏會調用重寫後的authenticate方法 if user is not None: login(request, user) // 調用login()方法進行登錄,實際上是對request進行一些操作,把user寫入request return render(request, "index.html") else: return render(request, "login.html", {"msg": u"用戶名或密碼錯誤", "login_form":login_form}) settings.py // 對於自定義認證後臺,同樣需要在settings文件中進行聲明 AUTHENTICATION_BACKENDS = ( ‘users.views.CustomBackend‘, )
Django自定義UserModel並實現認證和登錄