2016-12-07 52 views
-3

我在網上發現了一個腳本,它可以幫助我更改登錄名,以便同時使用用戶名和電子郵件,而不僅僅是用戶名,但有很多部分我不太瞭解。有人能給我一個例子,這個腳本? django

就像我理解每一行的意思,但我不明白爲什麼這樣做會使我的登錄工作與電子郵件。

class EmailBackend(object): 
    def authenticate(self, username=None, password=None): 
     user_cls = get_user_model() 
     try: 
      user = user_cls.objects.get(email=username) 
      if user.check_password(password): 
       return user 
     except user_cls.DoesNotExist: 
      return None 
     except: 
      return None 

    def get_user(self, user_id): 
     user_cls = get_user_model() 
     try: 
      return user_cls.objects.get(pk=user_id) 
     except user_cls.DoesNotExist: 
      return None 

在此先感謝。

+0

這個腳本中使用的用戶名銜,而不是電子郵件,但是在後端該用戶名必須爲電子郵件用戶'= user_cls.objects.get(電子郵件=用戶名)'您可以更改用戶名電子郵件,沒關係。 – metmirr

回答

1

檢查意見: -

class EmailBackend(object): 
    def authenticate(self, username=None, password=None): 
     user_cls = get_user_model() #Getting user object in one variable 

     try: 
      user = user_cls.objects.get(email=username) #Check any user exist with input email(username) with database email(consider as an username) 
      if user.check_password(password): #if user match then check is password match or not 
       return user #If both email and password match then return user information 
     except user_cls.DoesNotExist: #if user not exist then return None 
      return None 
     except: #got any error in middle return None 
      return None 

    def get_user(self, user_id): 
     user_cls = get_user_model() #Get user object in one variable 
     try: 
      return user_cls.objects.get(pk=user_id) #check user with this user_id exist or not, may be PK (some unique id consider as an user_id) 
     except user_cls.DoesNotExist: #if user_id(PK) not exist return None 
      return None 
+0

但是'(email = username)'中的用戶名是如何得到的?是因爲'def authenticate',它實際上是一個內置在Django中?以及如何使用'def get_user'?沒有這個在我的'html'模板中會出現錯誤。 – Tsuna

+0

@Tsuna,可能是模型,它是電子郵件,他們已將用戶名視爲電子郵件,所以他們正在比較用戶名和電子郵件。 'get_user'是他們創建的用來檢查特定用戶數據(pk)在數據庫中是否可用的函數。如果沒有這個模板,你的模板可能不工作,因爲可能他們已經通過模板參數調用了這個函數作爲user_id。 –

相關問題