django如何用郵箱代替用戶名登錄


有兩種方法

方法一,修改username字段,讓他跟email字段一模一樣,然后把email放到username,email字段里面,username放到firstname或者lastname里面,這樣username其實就是email了。簡單方便,而且代碼改動也比較少,我使用的是這種。

方法二,自己寫一個方法來驗證,然后加進setting里面。

下面方法轉自http://www.cnblogs.com/aguncn/p/5653850.html

就是另一個不同的登陸backend。

而DJANGO會嘗不同的方式,哪個成功就用哪個

authentication.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from  django.contrib.auth.models  import  User
 
 
class  EmailAuthBackend( object ):
     def  authenticate( self , username = None , password = None ):
         try :
             user  =  User.objects.get(email = username)
             if  user.check_password(password):
                 return  user
             return  None
         except  User.DoesNotExist:
             return  None
 
     def  get_user( self , user_id):
         try :
             return  User.objects.get(pk = user_id)
         except  User.DoesNotExist:
             return  None

  setting.py中加一個認證方式:

1
2
3
4
AUTHENTICATION_BACKENDS  =  (
     'django.contrib.auth.backends.ModelBackend' ,
     'account.authentication.EmailAuthBackend' ,
)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM