首先創(chuàng)建一個(gè)新的login app,用來存放認(rèn)證用到代碼
python manage.py startapp login
修改settings.py中的認(rèn)證項(xiàng)
AUTHENTICATION_BACKENDS = ( 'login.auth.UsernamePasswordAuth', )
自定義認(rèn)證類
在login app下創(chuàng)建auth.py文件,內(nèi)容如下
#coding:utf-8 from django.contrib.auth.models import User class UsernamePasswordAuth(object): def authenticate(self, username=None, password=None): print("UsernamePasswordAuth.authenticate") try: user = User.objects.get(username__iexact=username) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): print("UsernamePasswordAuth.get_user") try: user = User.objects.get(pk=user_id) return user except User.DoesNotExist: return None